Cast all elements in a stream to a given type, possibly throwing a
{@link ClassCastException}.

<pre>
{@code
Streams.cast(Stream.of(1, "a", 2, "b", 3),Integer.class)
// throws ClassCastException
}
320281
public static <T, U> Stream<U> cast(final Stream<T> stream, final Class<? extends U> type) {
        return stream.map(type::cast);
    }
961303
public void writeObject(Object object)
        throws IOException
    {
        if (object == null)
            writeNull();
        else if (object instanceof String)
            writeString((String) object);
        else if (object instanceof Boolean)
            writeBoolean(((Boolean) object).booleanValue());
        else if (object instanceof Integer)
            writeInt(((Integer) object).intValue());
        else if (object instanceof Long)
            writeLong(((Long) object).longValue());
        else if (object instanceof Date)
            writeUTCDate(((Date) object).getTime());
        else if (object instanceof byte[]) {
            byte[] data = (byte[]) object;
            writeBytes(data, 0, data.length);
        }
        else if (object instanceof Vector) {
            Vector vector = (Vector) object;

            int size = vector.size();
            writeListBegin(size, null);
            for (int i = 0; i < size; i++)
                writeObject(vector.elementAt(i));

            writeListEnd();
        }
        else if (object instanceof Hashtable) {
            Hashtable hashtable = (Hashtable) object;

            writeMapBegin(null);
            Enumeration e = hashtable.keys();
            while (e.hasMoreElements()) {
                Object key = e.nextElement();
                Object value = hashtable.get(key);

                writeObject(key);
                writeObject(value);
            }
            writeMapEnd();
        }
        else
            writeCustomObject(object);
    }

    /**
     * Applications which override this can do custom serialization.
     *
     * @param object the object to write.
     */
    public void writeCustomObject(Object object)
        throws IOException
    {
        throw new IOException("unexpected object: " + object);
    }

    /**
     * Writes the list header to the stream.  List writers will call
     * <code>writeListBegin</code> followed by the list contents and then
     * call <code>writeListEnd</code>.
     *
     * <code><pre>
     * &lt;list>
     *   &lt;type>java.util.ArrayList&lt;/type>
     *   &lt;length>3&lt;/length>
     *   &lt;int>1&lt;/int>
     *   &lt;int>2&lt;/int>
     *   &lt;int>3&lt;/int>
     * &lt;/list>
     * </pre></code>
     */
    public void writeListBegin(int length, String type)
        throws IOException
    {
        os.write('V');
        os.write('t');
        printLenString(type);

        os.write('l');
        os.write(length >> 24);
        os.write(length >> 16);
        os.write(length >> 8);
        os.write(length);
    }

    /**
     * Writes the tail of the list to the stream.
     */
    public void writeListEnd()
        throws IOException
    {
        os.write('z');
    }

    /**
     * Writes the map header to the stream.  Map writers will call
     * <code>writeMapBegin</code> followed by the map contents and then
     * call <code>writeMapEnd</code>.
     *
     * <code><pre>
     * Mt b16 b8 type (<key> <value>)z
     * </pre></code>
     */
    public void writeMapBegin(String type)
        throws IOException
    {
        os.write('M');
        os.write('t');
        printLenString(type);
    }

    /**
     * Writes the tail of the map to the stream.
     */
    public void writeMapEnd()
        throws IOException
    {
        os.write('z');
    }

    /**
     * Writes a remote object reference to the stream.  The type is the
     * type of the remote interface.
     *
     * <code><pre>
     * 'r' 't' b16 b8 type url
     * </pre></code>
     */
    public void writeRemote(String type, String url)
        throws IOException
    {
        os.write('r');
        os.write('t');
        printLenString(type);
        os.write('S');
        printLenString(url);
    }

    /**
     * Prints a string to the stream, encoded as UTF-8 with preceeding length
     *
     * @param v the string to print.
     */
    public void printLenString(String v)
        throws IOException
    {
        if (v == null) {
            os.write(0);
            os.write(0);
        }
        else {
            int len = v.length();
            os.write(len >> 8);
            os.write(len);

            printString(v, 0, len);
        }
    }

    /**
     * Prints a string to the stream, encoded as UTF-8
     *
     * @param v the string to print.
     */
    public void printString(String v)
        throws IOException
    {
        printString(v, 0, v.length());
    }

    /**
     * Prints a string to the stream, encoded as UTF-8
     *
     * @param v the string to print.
     */
    public void printString(String v, int offset, int length)
        throws IOException
    {
        for (int i = 0; i < length; i++) {
            char ch = v.charAt(i + offset);

            if (ch < 0x80)
                os.write(ch);
            else if (ch < 0x800) {
                os.write(0xc0 + ((ch >> 6) & 0x1f));
                os.write(0x80 + (ch & 0x3f));
            }
            else {
                os.write(0xe0 + ((ch >> 12) & 0xf));
                os.write(0x80 + ((ch >> 6) & 0x3f));
                os.write(0x80 + (ch & 0x3f));
            }
        }
    }
}
1178139
@SuppressWarnings("unchecked")
  public void printType(Type type)
    throws IOException
  {
    if (type instanceof Class<?>) {
      printTypeClass((Class<?>) type);
    } 
    else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      
      printParameterizedType(parameterizedType);
    }
    else if (type instanceof WildcardType) {
      WildcardType wildcardType = (WildcardType) type;
      
      printWildcardType(wildcardType);
    }
    else if (type instanceof TypeVariable<?>) {
      TypeVariable<? extends GenericDeclaration> typeVariable = (TypeVariable<? extends GenericDeclaration>) type;
      
      printTypeVariable(typeVariable);
    }
    else if (type instanceof GenericArrayType) {
      GenericArrayType genericArrayType = (GenericArrayType) type;

      printType(genericArrayType.getGenericComponentType());
      print("[]");
    }
    else {
      throw new UnsupportedOperationException(type.getClass().getName() + " "
          + String.valueOf(type));
    }
  }
233024
public static <T extends Serializable> T deserializeFromStream(InputStream in, Class<T> type) throws ClassNotFoundException, IOException
	{
		ObjectInputStream objIn;
		T obj;

		if(in instanceof ObjectInputStream)
			objIn = (ObjectInputStream)in;
		else
			objIn = new ObjectInputStream(in);

		obj = type.cast(objIn.readObject());
		// to close or not to close... That is the question...
		// we close... It doesn't make too much sense to have a stream with more afterwards...There would be two
		// stream headers...
		objIn.close();
		return obj;
	}
1111536
public static byte[] streamBytes(InputStream stream) throws IOException {

		ByteArrayOutputStream bytes = new ByteArrayOutputStream();

		copyStream(stream, bytes);

		return bytes.toByteArray();
	}
905804
public static <T> Object castToArray(final Class<T> type, final Object val) throws DevFailed {
	Object result = null;
	final Object array1D = val;
	if (val == null || type.isAssignableFrom(val.getClass())) {
	    result = val;
	} else {
	    LOGGER.debug("converting {} to {}", val.getClass().getCanonicalName(), type.getCanonicalName());
	    final Class<?> typeConv = Array.newInstance(type, 0).getClass();
	    final Transmorph transmorph = new Transmorph(creatConv());
	    try {
		result = transmorph.convert(array1D, typeConv);
	    } catch (final ConverterException e) {
		LOGGER.error("convertion error", e);
		throw DevFailedUtils.newDevFailed(e);
	    }
	}
	return result;
    }
934209
@SuppressWarnings("unchecked")
    private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {

        /*
         * Since this is a simple class all we have to do is read each member from the stream.
         * the order has to remain identical to writeObject, so I've just gone alphabetically.
         *
         * If we change the serialversionUID, we may need to modify this method as well.
         */

        if (tc.isEntryEnabled()) {
            Tr.entry(this, tc, "readObject", stream);
        }

        ObjectInputStream.GetField getField = stream.readFields();

        if (tc.isDebugEnabled()) {

            for (int i = 0; i < serialPersistentFields.length; i++) {

                String fieldName = serialPersistentFields[i].getName();

                if (getField.defaulted(fieldName))
                    Tr.debug(this, tc, "Could not de-serialize field " + fieldName + " in class " +
                                       getClass().getName() + "; default value will be used");

            }

        }

        activationConfigProps = (Properties) getField.get("activationConfigProps", null);
        destinationRef = (String) getField.get("destinationRef", null);
        authenticationAlias = (String) getField.get("authenticationAlias", null);
        applicationName = (String) getField.get("applicationName", null);
        qmid = (String) getField.get("qmid", null);

        if (tc.isEntryEnabled())
            Tr.exit(this, tc, "readObject activation config - " + this.toString());
    }
778529
@SuppressWarnings("PMD.LooseCoupling")
    public static Object castValue(Method m, Class<?> castType, String value) {

        try {
            if (castType.isEnum()) {
                Method valueOf;
                try {
                    valueOf = castType.getMethod("valueOf", String.class);
                    return valueOf.invoke(null, value);
                } catch (Exception e) {
                    log.info("enum value of excute error : (" + castType.getName() + ") | " + value);
                    return null;
                }
            } else if (castType == Integer.class || castType == int.class) {
                return Integer.parseInt(value);
            } else if (castType == Long.class || castType == long.class) {
                return Long.parseLong(value);
            } else if (castType == Double.class || castType == double.class) {
                return Double.parseDouble(value);
            } else if (castType == Boolean.class || castType == boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (castType == Float.class || castType == float.class) {
                return Float.parseFloat(value);
            } else if (castType == String.class) {
                return value;
            } else if (castType == ArrayList.class || castType == List.class) {
                ParameterizedType paramType = (ParameterizedType) m.getGenericParameterTypes()[0];
                Class<?> paramClass = (Class<?>) paramType.getActualTypeArguments()[0];
                List<Object> castList = new ArrayList<>();
                String[] values = value.split(",");
                for (String v : values) {
                    castList.add(castValue(m, paramClass, v));
                }

                return castList;
            } else {
                log.info("invalid castType : " + castType);
                return null;
            }
        } catch (NumberFormatException e) {
            log.info("value : " + value + " is invalid value, setter parameter type is  : " + castType);
            return null;
        }
    }
1312031
static IntStream stream(
        IntTuple tuple, int startInclusive, int endExclusive) 
    {
        IntTupleSpliterator intTupleSpliterator = 
            new IntTupleSpliterator(
                tuple, startInclusive, endExclusive);
        return StreamSupport.intStream(intTupleSpliterator, false);
    }
175283
@SuppressWarnings({"unchecked"})
    public static <T> Iterator<T> cast(Iterator<? extends T> itr) {
        return (Iterator)itr;
    }
40972
@SafeVarargs
    public static <T> StreamEx<T> of(T... elements) {
        return of(Arrays.spliterator(elements));
    }
238776
@Override
    public T fromStream(final InputStream in, final boolean close) throws IllegalArgumentException,
        DescriptorImportException {
        // Precondition check
        if (in == null) {
            throw new IllegalArgumentException("InputStream must be specified");
        }

        final Node rootNode = this.getNodeImporter().importAsNode(in, close);

        // Create the end-user view
        final Constructor<T> constructor;
        try {
            constructor = endUserViewImplType.getConstructor(String.class, Node.class);
        } catch (final NoSuchMethodException e) {
            throw new DescriptorImportException("Descriptor impl " + endUserViewImplType.getName()
                + " does not have a constructor accepting " + String.class.getName() + " and " + Node.class.getName(),
                e);
        }
        final T descriptor;
        try {
            descriptor = constructor.newInstance(descriptorName, rootNode);
        } catch (final Exception e) {
            throw new DescriptorImportException("Could not create new instance using " + constructor + " with arg: "
                + rootNode);
        }

        // Return
        return descriptor;
    }
172093
@PublicEvolving
	public boolean shouldAutocastTo(BasicTypeInfo<?> to) {
		for (Class<?> possibleTo: possibleCastTargetTypes) {
			if (possibleTo.equals(to.getTypeClass())) {
				return true;
			}
		}
		return false;
	}
506995
public static <T> Set<T> toSet(Stream<T> stream) {
        return stream.collect(Collectors.<T>toSet());
    }
1360723
@Override
  public StreamImpl stream()
    throws IOException
  {
    if (_streamImpl == null) {
      _streamImpl = new SocketStream();
    }

    _streamImpl.init(_s);

    return _streamImpl;
  }
83351
public static <E extends Enum<E>> StreamableEnumSet<E> allOf (Class<E> elementType)
    {
        StreamableEnumSet<E> set = new StreamableEnumSet<E>(elementType);
        for (E constant : elementType.getEnumConstants()) {
            set.add(constant);
        }
        return set;
    }
1081939
public static <R> Stream<R> of(R... elements) {
        return new Stream<R>(new ArrayIterable.ArrayIterator<R>(elements));
    }