Java Code Examples for java.io.ObjectInputStream

The following are top voted examples for showing how to use java.io.ObjectInputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: asura   File: WebLogicDelegate.java   Source Code and License 7 votes vote down vote up
/**
 * <p>
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
    throws ClassNotFoundException, IOException, SQLException {
    
    Object obj = null;

    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }

    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }

    return obj;
}
 
Example 2
Project: lams   File: OracleDelegate.java   Source Code and License 7 votes vote down vote up
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName)
    throws ClassNotFoundException, IOException, SQLException {
    
    Object obj = null;
    InputStream binaryInput = rs.getBinaryStream(colName);
    if (binaryInput != null) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }

    return obj;
}
 
Example 3
Project: jdk8u-jdk   File: ReadObject.java   Source Code and License 6 votes vote down vote up
private static Object copyObject(Object oldObj) {
    Object newObj = null;
    try {
       //Create a stream in which to serialize the object.
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        ObjectOutputStream p = new ObjectOutputStream(ostream);
        //Serialize the object into the stream
        p.writeObject(oldObj);

        //Create an input stream from which to deserialize the object
        byte[] byteArray = ostream.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(byteArray);
        ObjectInputStream q = new ObjectInputStream(istream);
        //Deserialize the object
        newObj = q.readObject();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return newObj;
}
 
Example 4
Project: quidditchtimekeeper   File: SerializerClass.java   Source Code and License 6 votes vote down vote up
public static Object deserializeObject(byte[] b) {
    try {
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
        Object object = in.readObject();
        in.close();

        return object;
    } catch(ClassNotFoundException cnfe) {
        Log.e("deserializeObject", "class not found error", cnfe);

        return null;
    } catch(IOException ioe) {
        Log.e("deserializeObject", "io error", ioe);

        return null;
    }
}
 
Example 5
Project: openjdk-jdk10   File: IntArrays.java   Source Code and License 6 votes vote down vote up
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, int[][] arrays, int nbatches)
    throws Exception
{
    int ncycles = arrays.length;
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        oout.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeObject(arrays[j]);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readObject();
        }
    }
}
 
Example 6
Project: jdk8u-jdk   File: Scrollbar.java   Source Code and License 6 votes vote down vote up
/**
 * Reads the <code>ObjectInputStream</code> and if
 * it isn't <code>null</code> adds a listener to
 * receive adjustment events fired by the
 * <code>Scrollbar</code>.
 * Unrecognized keys or values will be ignored.
 *
 * @param s the <code>ObjectInputStream</code> to read
 * @exception HeadlessException if
 *   <code>GraphicsEnvironment.isHeadless</code> returns
 *   <code>true</code>
 * @see java.awt.GraphicsEnvironment#isHeadless
 * @see #writeObject(ObjectOutputStream)
 */
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException, HeadlessException
{
  GraphicsEnvironment.checkHeadless();
  s.defaultReadObject();

  Object keyOrNull;
  while(null != (keyOrNull = s.readObject())) {
    String key = ((String)keyOrNull).intern();

    if (adjustmentListenerK == key)
      addAdjustmentListener((AdjustmentListener)(s.readObject()));

    else // skip value for unrecognized key
      s.readObject();
  }
}
 
Example 7
Project: jdk8u-jdk   File: CommunicatorServer.java   Source Code and License 6 votes vote down vote up
/**
 * Controls the way the CommunicatorServer service is deserialized.
 */
private void readObject(ObjectInputStream stream)
    throws IOException, ClassNotFoundException {

    // Call the default deserialization of the object.
    //
    stream.defaultReadObject();

    // Call the specific initialization for the CommunicatorServer service.
    // This is for transient structures to be initialized to specific
    // default values.
    //
    stateLock = new Object();
    state = OFFLINE;
    stopRequested = false;
    servedClientCount = 0;
    clientHandlerVector = new Vector<>();
    mainThread = null;
    notifCount = 0;
    notifInfos = null;
    notifBroadcaster = new NotificationBroadcasterSupport();
    dbgTag = makeDebugTag();
}
 
Example 8
Project: jodis-client   File: CacheUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * 功能描述:自己数组转换成对象 <br>
 * 〈功能详细描述〉
 *
 * @param bytes bytes
 * @return object
 * @throws IOException ioexception
 * @see [相关类/方法](可选)
 * @since [产品/模块版本](可选)
 */
public static Object byteArrayToObject(byte[] bytes) throws IOException {
    if (bytes == null || bytes.length <= 0) {
        return null;
    }
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bis));
        obj = ois.readObject();
        bis.close();
        ois.close();
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
    }
    return obj;
}
 
Example 9
Project: Robin_Java   File: UnsafeTest.java   Source Code and License 6 votes vote down vote up
public static void main( String[] args ) throws IOException, ClassNotFoundException
{
    Person obj = new Person();
    obj.setName( "Robin" );
           
    PersonHack objH = new PersonHack();
      
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(objH);
    
    //反序列化漏洞,如果反序列化的對象可以試任意的,則有可能執行任意有風險額代碼
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream  ois = new ObjectInputStream(bais);
    
    Person objCopy = (Person)ois.readObject();        
    System.out.println(objCopy.getName());

}
 
Example 10
Project: openjdk-jdk10   File: SocketPermission.java   Source Code and License 6 votes vote down vote up
private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    // Don't call in.defaultReadObject()

    // Read in serialized fields
    ObjectInputStream.GetField gfields = in.readFields();

    // Get the one we want
    @SuppressWarnings("unchecked")
    Vector<SocketPermission> permissions = (Vector<SocketPermission>)gfields.get("permissions", null);
    perms = new ConcurrentSkipListMap<>(new SPCComparator());
    for (SocketPermission sp : permissions) {
        perms.put(sp.getName(), sp);
    }
}
 
Example 11
Project: jdk8u-jdk   File: CharArrays.java   Source Code and License 6 votes vote down vote up
/**
 * Write and read char arrays to/from a stream.  The benchmark is run in
 * batches, with each batch consisting of a fixed number of read/write
 * cycles.  The ObjectOutputStream is reset after each batch of cycles has
 * completed.
 * Arguments: <array size> <# batches> <# cycles per batch>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    int nbatches = Integer.parseInt(args[1]);
    int ncycles = Integer.parseInt(args[2]);
    char[][] arrays = new char[ncycles][size];
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, arrays, 1);     // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, arrays, nbatches);
    return System.currentTimeMillis() - start;
}
 
Example 12
Project: openjdk-jdk10   File: SuppressStackTraces.java   Source Code and License 6 votes vote down vote up
private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    in.defaultReadObject();

    /*
     * Verify right at unmarshalling time that this exception instance
     * contains no stack trace data from the server (regardless of whether
     * or not it would be apparent at the RMI client application level).
     */
    StackTraceElement[] trace = getStackTrace();
    if (trace.length > 0) {
        throw new RuntimeException(
            "TEST FAILED: exception contained non-empty stack trace: " +
            Arrays.asList(trace));
    }
}
 
Example 13
Project: openjdk-jdk10   File: Longs.java   Source Code and License 6 votes vote down vote up
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, int nbatches, int ncycles)
    throws Exception
{
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeLong(0);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readLong();
        }
    }
}
 
Example 14
Project: incubator-netbeans   File: SharedClassObject.java   Source Code and License 6 votes vote down vote up
/** Read object.
*/
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
    ois.defaultReadObject();

    if (clazz == null) {
        // Means that the class is no longer available in the restoring classloader.
        // Normal enough if the module has been uninstalled etc. #15654
        if (name != null) {
            throw new ClassNotFoundException(name);
        } else {
            // Compatibility with older WR's.
            throw new ClassNotFoundException();
        }
    }

    object = findObject(clazz, true);
    object.inReadExternal = true;

    try {
        object.readExternal(ois);
    } finally {
        object.inReadExternal = false;
    }
}
 
Example 15
Project: jdk8u-jdk   File: Doubles.java   Source Code and License 6 votes vote down vote up
/**
 * Write and read double values to/from a stream.  The benchmark is run in
 * batches: each "batch" consists of a fixed number of read/write cycles,
 * and the stream is flushed (and underlying stream buffer cleared) in
 * between each batch.
 * Arguments: <# batches> <# cycles per batch>
 */
public long run(String[] args) throws Exception {
    int nbatches = Integer.parseInt(args[0]);
    int ncycles = Integer.parseInt(args[1]);
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, 1, ncycles);    // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, nbatches, ncycles);
    return System.currentTimeMillis() - start;
}
 
Example 16
Project: jdk8u-jdk   File: RepeatObjs.java   Source Code and License 6 votes vote down vote up
/**
 * Write and read repeated objects to/from a stream.  The benchmark is run
 * for a given number of batches.  Within each batch, a set of objects
 * is written to and read from the stream.  The set of objects remains the
 * same between batches (and the serialization streams are not reset) in
 * order to test the speed of object -> wire handle lookup, and vice versa.
 * Arguments: <# objects> <# cycles>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    int nbatches = Integer.parseInt(args[1]);
    Node[] objs = genObjs(size);
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, objs, 1);       // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, objs, nbatches);
    return System.currentTimeMillis() - start;
}
 
Example 17
Project: RxEasyHttp   File: SerializableOkHttpCookies.java   Source Code and License 6 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    long expiresAt = in.readLong();
    String domain = (String) in.readObject();
    String path = (String) in.readObject();
    boolean secure = in.readBoolean();
    boolean httpOnly = in.readBoolean();
    boolean hostOnly = in.readBoolean();
    //boolean persistent = in.readBoolean();
    Cookie.Builder builder = new Cookie.Builder();
    builder = builder.name(name);
    builder = builder.value(value);
    builder = builder.expiresAt(expiresAt);
    builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
    builder = builder.path(path);
    builder = secure ? builder.secure() : builder;
    builder = httpOnly ? builder.httpOnly() : builder;
    clientCookies =builder.build();
}
 
Example 18
Project: underlx   File: ExtraContentCache.java   Source Code and License 6 votes vote down vote up
@Nullable
private String retrieveConnectionInfo(int maxAgeDays, String stationId, String type, String locale) {
    try {
        FileInputStream fis = new FileInputStream(new File(context.getCacheDir(), String.format(CONN_INFO_CACHE_FILENAME, stationId, type, locale)));
        ObjectInputStream is = new ObjectInputStream(fis);
        CachedConnectionInfo cached = (CachedConnectionInfo) is.readObject();
        is.close();
        fis.close();

        if (cached.date.getTime() < new Date().getTime() - 1000 * 60 * 60 * 24 * maxAgeDays && Connectivity.isConnected(context)) {
            return null;
        }
        return cached.html;
    } catch (Exception e) {
        // oh well, we'll have to do without cache
        // caching is best-effort
        return null;
    }
}
 
Example 19
Project: jdk8u-jdk   File: Doubles.java   Source Code and License 6 votes vote down vote up
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, int nbatches, int ncycles)
    throws Exception
{
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeDouble(0.0);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readDouble();
        }
    }
}
 
Example 20
Project: apache-tomcat-7.0.73-with-comment   File: XByteBuffer.java   Source Code and License 6 votes vote down vote up
public static Serializable deserialize(byte[] data, int offset, int length, ClassLoader[] cls) 
    throws IOException, ClassNotFoundException, ClassCastException {
    invokecount.addAndGet(1);
    Object message = null;
    if ( cls == null ) cls = new ClassLoader[0];
    if (data != null && length > 0) {
        InputStream  instream = new ByteArrayInputStream(data,offset,length);
        ObjectInputStream stream = null;
        stream = (cls.length>0)? new ReplicationStream(instream,cls):new ObjectInputStream(instream);
        message = stream.readObject();
        instream.close();
        stream.close();
    }
    if ( message == null ) {
        return null;
    } else if (message instanceof Serializable)
        return (Serializable) message;
    else {
        throw new ClassCastException("Message has the wrong class. It should implement Serializable, instead it is:"+message.getClass().getName());
    }
}
 
Example 21
Project: s-store   File: MapMakerInternalMap.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation") // serialization of deprecated feature
MapMaker readMapMaker(ObjectInputStream in) throws IOException {
  int size = in.readInt();
  MapMaker mapMaker = new MapMaker()
      .initialCapacity(size)
      .setKeyStrength(keyStrength)
      .setValueStrength(valueStrength)
      .keyEquivalence(keyEquivalence)
      .concurrencyLevel(concurrencyLevel);
  mapMaker.removalListener(removalListener);
  if (expireAfterWriteNanos > 0) {
    mapMaker.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
  }
  if (expireAfterAccessNanos > 0) {
    mapMaker.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
  }
  if (maximumSize != MapMaker.UNSET_INT) {
    mapMaker.maximumSize(maximumSize);
  }
  return mapMaker;
}
 
Example 22
Project: jlayer   File: JavaLayerUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Deserializes an object from the given <code>InputStream</code>.
 * The deserialization is delegated to an <code>
 * ObjectInputStream</code> instance. 
 * 
 * @param in	The <code>InputStream</code> to deserialize an object
 *				from.
 * 
 * @return The object deserialized from the stream. 
 * @exception IOException is thrown if there was a problem reading
 *		the underlying stream, or an object could not be deserialized
 *		from the stream.
 * 
 * @see java.io.ObjectInputStream
 */
static public Object deserialize(InputStream in)
	throws IOException
{
	if (in==null)
		throw new NullPointerException("in");
	
	ObjectInputStream objIn = new ObjectInputStream(in);
	
	Object obj;
	
	try
	{
		obj = objIn.readObject();
	}
	catch (ClassNotFoundException ex)
	{
		throw new InvalidClassException(ex.toString());
	}
	
	return obj;
}
 
Example 23
Project: whackpad   File: UintMap.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    in.defaultReadObject();

    int writtenKeyCount = keyCount;
    if (writtenKeyCount != 0) {
        keyCount = 0;
        boolean hasIntValues = in.readBoolean();
        boolean hasObjectValues = in.readBoolean();

        int N = 1 << power;
        if (hasIntValues) {
            keys = new int[2 * N];
            ivaluesShift = N;
        }else {
            keys = new int[N];
        }
        for (int i = 0; i != N; ++i) {
            keys[i] = EMPTY;
        }
        if (hasObjectValues) {
            values = new Object[N];
        }
        for (int i = 0; i != writtenKeyCount; ++i) {
            int key = in.readInt();
            int index = insertNewKey(key);
            if (hasIntValues) {
                int ivalue = in.readInt();
                keys[ivaluesShift + index] = ivalue;
            }
            if (hasObjectValues) {
                values[index] = in.readObject();
            }
        }
    }
}
 
Example 24
Project: mDL-ILP   File: StorageUtils.java   Source Code and License 5 votes vote down vote up
public static Object loadObject(Context context, String key) {
    try (ObjectInputStream os = new ObjectInputStream(context.getApplicationContext().openFileInput(key))) {
        return os.readObject();
    } catch (IOException | ClassNotFoundException e) {
        Log.e("StorageUtils", "Error loading object", e);
    }

    return null;
}
 
Example 25
Project: Java_Swing_Programming   File: Soru2Okuma.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    try {
        ObjectInputStream oOS=new ObjectInputStream(new BufferedInputStream(new FileInputStream("Ayşe")));
        System.out.println(oOS.readUTF());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Soru2Okuma.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 26
Project: OpenJSharp   File: JapaneseImperialCalendar.java   Source Code and License 5 votes vote down vote up
/**
 * Updates internal state.
 */
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    if (jdate == null) {
        jdate = jcal.newCalendarDate(getZone());
        cachedFixedDate = Long.MIN_VALUE;
    }
}
 
Example 27
Project: logistimo-web-service   File: EventSummaryConfigModel.java   Source Code and License 5 votes vote down vote up
public EventSummaryConfigModel copy() throws IOException, ClassNotFoundException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(this);
    ByteArrayInputStream
        byteArrayInputStream =
        new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    return (EventSummaryConfigModel) objectInputStream.readObject();

}
 
Example 28
Project: openjdk-jdk10   File: TCKChronoPeriod.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="calendars")
public void test_serialization(Chronology chrono) throws Exception {
    ChronoPeriod period = chrono.period(1, 2, 3);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(period);
    out.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    ObjectInputStream in = new ObjectInputStream(bais);
    ChronoPeriod ser = (ChronoPeriod) in.readObject();
    assertEquals(ser, period, "deserialized ChronoPeriod is wrong");
}
 
Example 29
Project: morpheus-core   File: SparseArrayOfZonedDateTimes.java   Source Code and License 5 votes vote down vote up
@Override
public final void read(ObjectInputStream is, int count) throws IOException {
    for (int i=0; i<count; ++i) {
        final long value = is.readLong();
        this.values.put(i, value);
        if (value != defaultValueAsLong) {
            final short zoneId = is.readShort();
            this.zoneIds.put(i, zoneId);
        }
    }
}
 
Example 30
Project: Pogamut3   File: TCMessageData.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused")
private void readObject(ObjectInputStream ois) {
	try {
		ois.defaultReadObject();			
		if (this.messageType != null) {
			this.messageType = Tokens.get(this.messageType.getToken());
		}
	} catch (RuntimeException re) {
		throw re;
	} catch (Exception e) {
		throw new RuntimeException("Failed to deserialize the object.", e);
	}
}
 
Example 31
Project: Orsum-occulendi   File: RSAUtil.java   Source Code and License 5 votes vote down vote up
public static PrivateKey privateKeyFromString(String exported) throws IOException, ClassNotFoundException {
	byte [] data = Base64.getDecoder().decode(exported);
	ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
	PrivateKey o = (PrivateKey)ois.readObject();
	ois.close();
	return o;
}
 
Example 32
Project: letv   File: bi.java   Source Code and License 5 votes vote down vote up
private void a(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
    try {
        this.i = (byte) 0;
        a(new cs(new dk((InputStream) objectInputStream)));
    } catch (cf e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 33
Project: GitHub   File: BodyRequest.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    String mediaTypeString = (String) in.readObject();
    if (!TextUtils.isEmpty(mediaTypeString)) {
        mediaType = MediaType.parse(mediaTypeString);
    }
}
 
Example 34
Project: MyFlightbookAndroid   File: MFBUtil.java   Source Code and License 5 votes vote down vote up
public static <T> T deserializeFromString(String s) {
    if (s == null || s.length() == 0)
        return null;

    try {
        byte rgb[] = Base64.decode(s, Base64.DEFAULT);
        ByteArrayInputStream bis = new ByteArrayInputStream(rgb);
        ObjectInputStream ois = new ObjectInputStream(bis);
        //noinspection unchecked
        return (T) ois.readObject();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
 
Example 35
Project: letv   File: bk.java   Source Code and License 5 votes vote down vote up
private void a(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
    try {
        this.j = (byte) 0;
        a(new cs(new dk((InputStream) objectInputStream)));
    } catch (cf e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 36
Project: android-project-gallery   File: SerializableCookie.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    String name = (String) in.readObject();
    String value = (String) in.readObject();
    clientCookie = new BasicClientCookie(name, value);
    clientCookie.setComment((String) in.readObject());
    clientCookie.setDomain((String) in.readObject());
    clientCookie.setExpiryDate((Date) in.readObject());
    clientCookie.setPath((String) in.readObject());
    clientCookie.setVersion(in.readInt());
    clientCookie.setSecure(in.readBoolean());
}
 
Example 37
Project: ipack   File: JDKDSAPublicKey.java   Source Code and License 5 votes vote down vote up
private void readObject(
    ObjectInputStream in)
    throws IOException, ClassNotFoundException
{
    this.y = (BigInteger)in.readObject();
    this.dsaSpec = new DSAParameterSpec((BigInteger)in.readObject(), (BigInteger)in.readObject(), (BigInteger)in.readObject());
}
 
Example 38
Project: NoRiskNoFun   File: AttackMessagesTests.java   Source Code and License 5 votes vote down vote up
@Test
public void DiceAmount() throws IOException, ClassNotFoundException {

    DiceAmount diceAmount = new DiceAmount(10);
    diceAmount.setAmount(10);
    oos.writeObject (diceAmount);
    ByteArrayInputStream bais = new ByteArrayInputStream (baos.toByteArray ());
    ObjectInputStream ois = new ObjectInputStream (bais);
    DiceAmount diceAmount1 =(DiceAmount) ois.readObject();
    assertEquals(diceAmount1.getAmount(),  10);

}
 
Example 39
Project: TuLiPA-frames   File: CollectionUtilities.java   Source Code and License 5 votes vote down vote up
public static Object deepCopy(Object original) throws Exception {
	Object ret = null;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ObjectOutputStream out = new ObjectOutputStream(bos);
	out.writeObject(original);
	out.flush();
	out.close();
	ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
	ret = in.readObject();
	return ret;
}
 
Example 40
Project: openjdk-jdk10   File: ChoiceFormat.java   Source Code and License 5 votes vote down vote up
/**
 * After reading an object from the input stream, do a simple verification
 * to maintain class invariants.
 * @throws InvalidObjectException if the objects read from the stream is invalid.
 */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    if (choiceLimits.length != choiceFormats.length) {
        throw new InvalidObjectException(
                "limits and format arrays of different length.");
    }
}
 
Example 41
Project: Embeddable-BSBM   File: Qualification.java   Source Code and License 5 votes vote down vote up
public Qualification(String correctFile, String testFile, String[] args) {
    try {
        examineStream = new ObjectInputStream(new FileInputStream(testFile));
        correctStream = new ObjectInputStream(new FileInputStream(correctFile));
        int maxQuery = Math.max(examineStream.readInt(), correctStream.readInt());
        totalQueryCount = new int[maxQuery];
        correctQueryCount = new int[maxQuery];
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
    processProgramParameters(args);
}
 
Example 42
Project: HL4A   File: XmlProcessor.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    this.dom = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    this.dom.setNamespaceAware(true);
    this.dom.setIgnoringComments(false);
    this.xform = javax.xml.transform.TransformerFactory.newInstance();
    int poolSize = Runtime.getRuntime().availableProcessors() * 2;
    this.documentBuilderPool = new LinkedBlockingDeque<DocumentBuilder>(poolSize);
}
 
Example 43
Project: Robust   File: JavaUtils.java   Source Code and License 5 votes vote down vote up
public static Object getMapFromZippedFile(String path) {
    File file = new File(path);
    Object result = null;
    try {
        if (file.exists()) {
            FileInputStream fileIn = new FileInputStream(file);
            GZIPInputStream gzipIn = new GZIPInputStream(fileIn);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            int count;
            byte[] data = new byte[1024];
            while ((count = gzipIn.read(data, 0, 1024)) != -1) {
                byteOut.write(data, 0, count);
            }
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(byteIn);
            result = oi.readObject();
            fileIn.close();
            gzipIn.close();
            oi.close();
        } else {
            throw new RuntimeException("getMapFromZippedFile error,file doesn't exist ,path is " + path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("getMapFromZippedFile from " + path + "  error ");
    }
    return result;
}
 
Example 44
Project: openjdk-jdk10   File: LdapName.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();
    unparsed = (String)s.readObject();
    try {
        parse();
    } catch (InvalidNameException e) {
        // shouldn't happen
        throw new java.io.StreamCorruptedException(
                "Invalid name: " + unparsed);
    }
}
 
Example 45
Project: gamesboard   File: ChessControllerTest.java   Source Code and License 5 votes vote down vote up
private String getSave(String serializedModel) {
	Memento memento = null;
	try {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.decode(serializedModel));
		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
		memento = (Memento) objectInputStream.readObject();
		objectInputStream.close();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return memento.getData();
}
 
Example 46
Project: guava-mock   File: EnumBiMap.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked") // reading fields populated by writeObject
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  keyType = (Class<K>) stream.readObject();
  valueType = (Class<V>) stream.readObject();
  setDelegates(
      WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
      WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
  Serialization.populateMap(this, stream);
}
 
Example 47
Project: OpenJSharp   File: InetAddress.java   Source Code and License 5 votes vote down vote up
private void readObject (ObjectInputStream s) throws
                     IOException, ClassNotFoundException {
    if (getClass().getClassLoader() != null) {
        throw new SecurityException ("invalid address type");
    }
    GetField gf = s.readFields();
    String host = (String)gf.get("hostName", null);
    int address= gf.get("address", 0);
    int family= gf.get("family", 0);
    InetAddressHolder h = new InetAddressHolder(host, address, family);
    UNSAFE.putObject(this, FIELDS_OFFSET, h);
}
 
Example 48
Project: monarch   File: JavaSerializationJUnitTest.java   Source Code and License 5 votes vote down vote up
private void verifyJavaSerialization(Object obj) throws Exception {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream out = new ObjectOutputStream(baos);
  out.writeObject(obj);
  out.close();
  baos.close();
  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream in = new ObjectInputStream(bais);
  Object obj2 = in.readObject();
  in.close();
  bais.close();
  assert (obj.equals(obj2));
}
 
Example 49
Project: lams   File: PackageAliasingMapper.java   Source Code and License 5 votes vote down vote up
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    packageToName = new TreeMap<String, String>(REVERSE);
    @SuppressWarnings("unchecked")
    final Map<String, String> map = (Map<String, String>)in.readObject();
    packageToName.putAll(map);
    nameToPackage = new HashMap<String, String>();
    for (final Map.Entry<String, String> entry : packageToName.entrySet()) {
        nameToPackage.put(entry.getValue(), entry.getKey());
    }
}
 
Example 50
Project: jdk8u-jdk   File: ActionMap.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
                                             IOException {
    s.defaultReadObject();
    for (int counter = s.readInt() - 1; counter >= 0; counter--) {
        put(s.readObject(), (Action)s.readObject());
    }
}
 
Example 51
Project: jdk8u-jdk   File: Correctness.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
 
Example 52
Project: sstore-soft   File: LinkedListMultimap.java   Source Code and License 5 votes vote down vote up
@GwtIncompatible("java.io.ObjectInputStream")
private void readObject(ObjectInputStream stream)
    throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  keyToKeyList = Maps.newLinkedHashMap();
  int size = stream.readInt();
  for (int i = 0; i < size; i++) {
    @SuppressWarnings("unchecked") // reading data stored by writeObject
    K key = (K) stream.readObject();
    @SuppressWarnings("unchecked") // reading data stored by writeObject
    V value = (V) stream.readObject();
    put(key, value);
  }
}
 
Example 53
Project: OpenJSharp   File: JTabbedPane.java   Source Code and License 5 votes vote down vote up
/**
 * See <code>readObject</code> and <code>writeObject</code> in
 * <code>JComponent</code> for more
 * information about serialization in Swing.
 */
private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
{
    s.defaultReadObject();
    if ((ui != null) && (getUIClassID().equals(uiClassID))) {
        ui.installUI(this);
    }
    // If ToolTipText != null, then the tooltip has already been
    // registered by JComponent.readObject()
    if (getToolTipText() == null && haveRegistered) {
        ToolTipManager.sharedInstance().registerComponent(this);
    }
}
 
Example 54
Project: jtk   File: ArrayVect3f.java   Source Code and License 5 votes vote down vote up
private void readObject(final ObjectInputStream in)
        throws IOException, ClassNotFoundException {

    @SuppressWarnings("unchecked") final Map<String, Object> map =
            (Map<String, Object>) in.readObject();

    _data = (float[][][]) map.get("data");
    _variance = (Double) map.get("variance");

    final int version = (Integer) map.get("VERSION");
    if (version != VERSION) {
        Logger.getLogger(getClass().getName()).warning
                ("Need to convert data from version " + version + " to " + VERSION);
    }
}
 
Example 55
Project: incubator-netbeans   File: JShellConnection.java   Source Code and License 5 votes vote down vote up
synchronized boolean acceptSocketAndKey(int key, SocketChannel socket, ObjectInputStream istm) throws IOException {
    if (closed) {
        return false;
    }
    if (id != key) {
        return false;
    }
    this.ostm = Channels.newOutputStream(socket);
    this.istm = istm;
    this.controlSocket = socket;
    notify();
    return true;
}
 
Example 56
Project: openjdk-jdk10   File: InputMethodEvent.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes the {@code when} field if it is not present in the
 * object input stream. In that case, the field will be initialized by
 * invoking {@link java.awt.EventQueue#getMostRecentEventTime()}.
 */
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
    s.defaultReadObject();
    if (when == 0) {
        // Can't use getMostRecentEventTimeForSource because source is always null during deserialization
        when = EventQueue.getMostRecentEventTime();
    }
}
 
Example 57
Project: clearwsd   File: DummyClassifier.java   Source Code and License 5 votes vote down vote up
@Override
public void load(ObjectInputStream inputStream) {
    try {
        label = inputStream.readInt();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 58
Project: OpenJSharp   File: ActionMap.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream s) throws ClassNotFoundException,
                                             IOException {
    s.defaultReadObject();
    for (int counter = s.readInt() - 1; counter >= 0; counter--) {
        put(s.readObject(), (Action)s.readObject());
    }
}
 
Example 59
Project: routerapp   File: MersenneTwister.java   Source Code and License 5 votes vote down vote up
private synchronized void readObject (final ObjectInputStream in)
     throws IOException, ClassNotFoundException
  {

/*
**  just so we're synchronized.
*/

    in.defaultReadObject();
  }
 
Example 60
Project: jdk8u-jdk   File: MBeanInfo.java   Source Code and License 5 votes vote down vote up
/**
 * Deserializes an {@link MBeanInfo} from an {@link ObjectInputStream}.
 * @serialData
 * For compatibility reasons, an object of this class is deserialized as follows.
 * <p>
 * The method {@link ObjectInputStream#defaultReadObject defaultReadObject()}
 * is called first to deserialize the object except the field
 * {@code descriptor}, which is not serialized in the default way. Then the method
 * {@link ObjectInputStream#read read()} is called to read a byte, the field
 * {@code descriptor} is deserialized according to the value of the byte value:
 *    <ul>
 *    <li>1. The method {@link ObjectInputStream#readObject readObject()}
 *       is called twice to obtain the field names (a {@code String[]}) and
 *       the field values (a {@code Object[]}) of the {@code descriptor}.
 *       The two obtained values then are used to construct
 *       an {@link ImmutableDescriptor} instance for the field
 *       {@code descriptor};</li>
 *    <li>0. The value for the field {@code descriptor} is obtained directly
 *       by calling the method {@link ObjectInputStream#readObject readObject()}.
 *       If the obtained value is null, the field {@code descriptor} is set to
 *       {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li>
 *    <li>-1. This means that there is no byte to read and that the object is from
 *       an earlier version of the JMX API. The field {@code descriptor} is set to
 *       {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}.</li>
 *    <li>Any other value. A {@link StreamCorruptedException} is thrown.</li>
 *    </ul>
 *
 * @since 1.6
 */

private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException {

    in.defaultReadObject();

    switch (in.read()) {
    case 1:
        final String[] names = (String[])in.readObject();

        final Object[] values = (Object[]) in.readObject();
        descriptor = (names.length == 0) ?
            ImmutableDescriptor.EMPTY_DESCRIPTOR :
            new ImmutableDescriptor(names, values);

        break;
    case 0:
        descriptor = (Descriptor)in.readObject();

        if (descriptor == null) {
            descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
        }

        break;
    case -1: // from an earlier version of the JMX API
        descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;

        break;
    default:
        throw new StreamCorruptedException("Got unexpected byte.");
    }
}