java.io.ObjectInputStream Java Examples

The following examples show how to use java.io.ObjectInputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestConfiguration.java    From PalDB with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerialization()
    throws Throwable {
  Configuration c = new Configuration();
  c.set("foo", "bar");
  c.registerSerializer(new PointSerializer());

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream out = new ObjectOutputStream(bos);
  out.writeObject(c);
  out.close();
  bos.close();

  byte[] bytes = bos.toByteArray();
  ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
  ObjectInputStream in = new ObjectInputStream(bis);
  Configuration sc = (Configuration) in.readObject();
  in.close();
  bis.close();

  Assert.assertEquals(sc, c);
}
 
Example #2
Source File: Permissions.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
    // Don't call defaultReadObject()

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

    // Get allPermission
    allPermission = (PermissionCollection) gfields.get("allPermission", null);

    // Get permissions
    // writeObject writes a Hashtable<Class<?>, PermissionCollection> for
    // the perms key, so this cast is safe, unless the data is corrupt.
    @SuppressWarnings("unchecked")
    Hashtable<Class<?>, PermissionCollection> perms =
        (Hashtable<Class<?>, PermissionCollection>)gfields.get("perms", null);
    permsMap = new HashMap<Class<?>, PermissionCollection>(perms.size()*2);
    permsMap.putAll(perms);

    // Set hasUnresolved
    UnresolvedPermissionCollection uc =
    (UnresolvedPermissionCollection) permsMap.get(UnresolvedPermission.class);
    hasUnresolved = (uc != null && uc.elements().hasMoreElements());
}
 
Example #3
Source File: RepositoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
RepositoryImpl(ORB orb, File dbDir, boolean debug)
{
    this.debug = debug ;
    this.orb = orb;
    wrapper = ActivationSystemException.get( orb, CORBALogDomains.ORBD_REPOSITORY ) ;

    // if databse does not exist, create it otherwise read it in
    File dbFile = new File(dbDir, "servers.db");
    if (!dbFile.exists()) {
        db = new RepositoryDB(dbFile);
        db.flush();
    } else {
        try {
            FileInputStream fis = new FileInputStream(dbFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            db = (RepositoryDB) ois.readObject();
            ois.close();
        } catch (Exception e) {
            throw wrapper.cannotReadRepositoryDb( e ) ;
        }
    }

    // export the repository
    orb.connect(this);
}
 
Example #4
Source File: ShortTextTitleTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {

    ShortTextTitle t1 = new ShortTextTitle("ABC");
    ShortTextTitle t2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(t1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        t2 = (ShortTextTitle) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(t1, t2);

}
 
Example #5
Source File: Packager.java    From courier with Apache License 2.0 6 votes vote down vote up
/**
 * In general, this method will only be used by generated code. However, it may be suitable
 * to use this method in some cases (such as in a WearableListenerService).
 *
 * Unpacks the given byte array into an object.
 *
 * This method will use the {@link java.io.Serializable} system to deserialize the data.
 *
 * @param data  The byte array to deserialize into an object.
 * @return An object deserialized from the byte array.
 */
@SuppressWarnings("unchecked")
public static <T> T unpackSerializable(byte[] data) {
    if(data==null || data.length==0) {
        return null;
    }

    try {
        final ByteArrayInputStream bytes = new ByteArrayInputStream(data);
        final ObjectInputStream in = new ObjectInputStream(bytes);

        return (T)in.readObject();
    }catch (Exception e){
        throw new IllegalArgumentException("Unable to deserialize object", e);
    }
}
 
Example #6
Source File: ParameterToolTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Accesses parameter tool parameters and then serializes the given parameter tool and deserializes again.
 * @param parameterTool to serialize/deserialize
 */
private void serializeDeserialize(ParameterTool parameterTool) throws IOException, ClassNotFoundException {
	// weirdly enough, this call has side effects making the ParameterTool serialization fail if not
	// using a concurrent data structure.
	parameterTool.get(UUID.randomUUID().toString());

	try (
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos)) {
		oos.writeObject(parameterTool);
		oos.close();
		baos.close();

		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bais);

		// this should work :-)
		ParameterTool deserializedParameterTool = ((ParameterTool) ois.readObject());
	}
}
 
Example #7
Source File: Ints.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write and read int 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 #8
Source File: CurrencyTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testSerialization() throws Exception {
    Currency currency1 = Currency.getInstance("DEM");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oStream = new ObjectOutputStream(baos);
    oStream.writeObject(currency1);
    oStream.flush();
    byte[] bytes = baos.toByteArray();

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream iStream = new ObjectInputStream(bais);
    Currency currency2 = (Currency) iStream.readObject();

    if (currency1 != currency2) {
        throw new RuntimeException("serialization breaks class invariant");
    }
}
 
Example #9
Source File: PolarPlot.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Provides serialization support.
 *
 * @param stream  the input stream.
 *
 * @throws IOException  if there is an I/O error.
 * @throws ClassNotFoundException  if there is a classpath problem.
 */
private void readObject(ObjectInputStream stream) 
    throws IOException, ClassNotFoundException {
  
    stream.defaultReadObject();
    this.angleGridlineStroke = SerialUtilities.readStroke(stream);
    this.angleGridlinePaint = SerialUtilities.readPaint(stream);
    this.radiusGridlineStroke = SerialUtilities.readStroke(stream);
    this.radiusGridlinePaint = SerialUtilities.readPaint(stream);
    this.angleLabelPaint = SerialUtilities.readPaint(stream);
  
    if (this.axis != null) {
        this.axis.setPlot(this);
        this.axis.addChangeListener(this);
    }
  
    if (this.dataset != null) {
        this.dataset.addChangeListener(this);
    }
}
 
Example #10
Source File: ObjArrays.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write and read object 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]);
    Node[][] arrays = genArrays(size, ncycles);
    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 #11
Source File: Permissions.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
    // Don't call defaultReadObject()

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

    // Get permissions
    // writeObject writes a Hashtable<Class<?>, PermissionCollection> for
    // the perms key, so this cast is safe, unless the data is corrupt.
    @SuppressWarnings("unchecked")
    Hashtable<Permission, Permission> perms =
            (Hashtable<Permission, Permission>)gfields.get("perms", null);
    permsMap = new HashMap<Permission, Permission>(perms.size()*2);
    permsMap.putAll(perms);
}
 
Example #12
Source File: EmptyBlockTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    EmptyBlock b1 = new EmptyBlock(1.0, 2.0);
    EmptyBlock b2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(b1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        b2 = (EmptyBlock) in.readObject();
        in.close();
    }
    catch (Exception e) {
        fail(e.toString());
    }
    assertEquals(b1, b2);
}
 
Example #13
Source File: Blacklist.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
public static Blacklist getInstance(Context context) {
    if(theInstance == null)
        try {
            FileInputStream fileInputStream = context.openFileInput("Blacklist");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

            theInstance = (Blacklist) objectInputStream.readObject();

            objectInputStream.close();
            fileInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            theInstance = new Blacklist();
        }

    return theInstance;
}
 
Example #14
Source File: BatchUpdateExceptionTests.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * De-Serialize a BatchUpdateException from JDBC 4.0 and make sure you can
 * read it back properly
 */
@Test
public void test13() throws Exception {
    String reason1 = "This was the error msg";
    String state1 = "user defined sqlState";
    String cause1 = "java.lang.Throwable: throw 1";
    int errorCode1 = 99999;
    Throwable t = new Throwable("throw 1");
    int[] uc1 = {1, 2, 21};
    long[] luc1 = {1, 2, 21};

    ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(SerializedBatchUpdateException.DATA));
    BatchUpdateException bue = (BatchUpdateException) ois.readObject();
    assertTrue(reason1.equals(bue.getMessage())
            && bue.getSQLState().equals(state1)
            && bue.getErrorCode() == errorCode1
            && cause1.equals(bue.getCause().toString())
            && Arrays.equals(bue.getLargeUpdateCounts(), luc1)
            && Arrays.equals(bue.getUpdateCounts(), uc1));
}
 
Example #15
Source File: CommonWebRowSetTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected WebRowSet readWebRowSetWithOInputStream(ByteArrayOutputStream baos) throws Exception {
    WebRowSet wrs1 = rsf.createWebRowSet();
    try (ObjectInputStream ois
            = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
        wrs1.readXml(ois);
    }
    return wrs1;
}
 
Example #16
Source File: CacheLoaderClient.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public V onInvoke(ObjectInputStream ois,
                  ObjectOutputStream oos) throws IOException, ClassNotFoundException {
  oos.writeObject(key);

  Object o = ois.readObject();

  if (o instanceof RuntimeException) {
    throw (RuntimeException) o;
  } else {
    return (V) o;
  }
}
 
Example #17
Source File: WeekFields.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Restore the state of a WeekFields from the stream.
 * Check that the values are valid.
 * @throws InvalidObjectException if the serialized object has an invalid
 *     value for firstDayOfWeek or minimalDays.
 */
private void readObject(ObjectInputStream s)
     throws IOException, ClassNotFoundException, InvalidObjectException
{
    s.defaultReadObject();
    if (firstDayOfWeek == null) {
        throw new InvalidObjectException("firstDayOfWeek is null");
    }

    if (minimalDays < 1 || minimalDays > 7) {
        throw new InvalidObjectException("Minimal number of days is invalid");
    }
}
 
Example #18
Source File: LHS.java    From beanshell with Apache License 2.0 5 votes vote down vote up
/** Fetch field removed from serializer.
 * @param in secializer.
 * @throws IOException mandatory throwing exception
 * @throws ClassNotFoundException mandatory throwing exception  */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    if ( null == this.object )
        return;
    Class<?> cls = this.object.getClass();
    if ( this.object instanceof Class )
        cls = (Class<?>) this.object;
    this.field = BshClassManager.memberCache.get(cls).findField(varName);
}
 
Example #19
Source File: ClassDesc.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Run benchmark for given number of cycles.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, ObjectStreamClass desc, int ncycles)
    throws Exception
{
    for (int i = 0; i < ncycles; i++) {
        sbuf.reset();
        oout.reset();
        oout.writeObject(desc);
        oout.flush();
        oin.readObject();
    }
}
 
Example #20
Source File: JDKDSAPublicKey.java    From ripple-lib-java with ISC 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 #21
Source File: StrokeMap.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Provides serialization support.
 *
 * @param stream  the input stream.
 *
 * @throws IOException  if there is an I/O error.
 * @throws ClassNotFoundException  if there is a classpath problem.
 */
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    this.store = new TreeMap();
    int keyCount = stream.readInt();
    for (int i = 0; i < keyCount; i++) {
        Comparable key = (Comparable) stream.readObject();
        Stroke stroke = SerialUtilities.readStroke(stream);
        this.store.put(key, stroke);
    }
}
 
Example #22
Source File: RelationTypeSupport.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deserializes a {@link RelationTypeSupport} from an {@link ObjectInputStream}.
 */
private void readObject(ObjectInputStream in)
        throws IOException, ClassNotFoundException {
  if (compat)
  {
    // Read an object serialized in the old serial form
    //
    ObjectInputStream.GetField fields = in.readFields();
    typeName = (String) fields.get("myTypeName", null);
    if (fields.defaulted("myTypeName"))
    {
      throw new NullPointerException("myTypeName");
    }
    roleName2InfoMap = cast(fields.get("myRoleName2InfoMap", null));
    if (fields.defaulted("myRoleName2InfoMap"))
    {
      throw new NullPointerException("myRoleName2InfoMap");
    }
    isInRelationService = fields.get("myIsInRelServFlg", false);
    if (fields.defaulted("myIsInRelServFlg"))
    {
      throw new NullPointerException("myIsInRelServFlg");
    }
  }
  else
  {
    // Read an object serialized in the new serial form
    //
    in.defaultReadObject();
  }
}
 
Example #23
Source File: ClassDesc.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Run benchmark for given number of cycles.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, ObjectStreamClass desc, int ncycles)
    throws Exception
{
    for (int i = 0; i < ncycles; i++) {
        sbuf.reset();
        oout.reset();
        oout.writeObject(desc);
        oout.flush();
        oin.readObject();
    }
}
 
Example #24
Source File: VisorDataTransferObjectInput.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param in Target input.
 * @throws IOException If an I/O error occurs.
 */
public VisorDataTransferObjectInput(ObjectInput in) throws IOException {
    byte[] buf = U.readByteArray(in);

    /* */
    GridByteArrayInputStream bis = new GridByteArrayInputStream(buf);
    ois = new ObjectInputStream(bis);
}
 
Example #25
Source File: DefaultStyledDocument.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void readObject(ObjectInputStream s)
        throws ClassNotFoundException, IOException {
    listeningStyles = new Vector<Style>();
    s.defaultReadObject();
    // Reinstall style listeners.
    if (styleContextChangeListener == null &&
        listenerList.getListenerCount(DocumentListener.class) > 0) {
        styleContextChangeListener = createStyleContextChangeListener();
        if (styleContextChangeListener != null) {
            StyleContext styles = (StyleContext)getAttributeContext();
            styles.addChangeListener(styleContextChangeListener);
        }
        updateStylesListeningTo();
    }
}
 
Example #26
Source File: MBeanTrustPermission.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in)
     throws IOException, ClassNotFoundException {

    // Reading private fields of base class
    in.defaultReadObject();
    try {
        validate(super.getName(),super.getActions());
    } catch (IllegalArgumentException e) {
        throw new InvalidObjectException(e.getMessage());
    }
}
 
Example #27
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void readObject (final ObjectInputStream s) throws ClassNotFoundException, IOException {
    s.defaultReadObject( );
    try {
        Field f = this.getClass().getDeclaredField("logBuilder");
        f.setAccessible(true);
        f.set(this, new LocalLogBuilder(this));
    } catch (NoSuchFieldException | IllegalAccessException ex) {
        StatusLogger.getLogger().warn("Unable to initialize LogBuilder");
    }
}
 
Example #28
Source File: Client.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link Client} that will auto connect to a {@link Server}
 * on the specified port.
 *
 * @param address the {@link InetAddress} on which the {@link Server}
 *                is accepting requests
 * @param port    the port on which the {@link Server} is
 *                is accepting requests
 * @throws IOException when the {@link Client} can't connect to the
 *                     {@link Server}
 */
public Client(InetAddress address, int port) throws IOException {
  Logger logger = Logger.getLogger(this.getClass().getName());
  this.port = port;
  try {
      logger.log(Level.INFO, "Starting " + this.getClass().getCanonicalName() +
              " client connecting to server at address:" + address + " port:" + port);
      this.socket = new Socket(address, port);
  } catch (IOException ioe) {
      throw new IOException("Client failed to connect to server at " + address + ":" + port, ioe);
  }
  this.oos = new ObjectOutputStream(socket.getOutputStream());
  this.ois = new ObjectInputStream(socket.getInputStream());
}
 
Example #29
Source File: State.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
public static State deserialize(File f) throws FileNotFoundException,
        IOException, ClassNotFoundException {
    ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
    State zone = (State) os.readObject();
    os.close();
    return zone;
}
 
Example #30
Source File: ETL.java    From WhiteRabbit with Apache License 2.0 5 votes vote down vote up
/**
 * Create an ETL instance by reading a saved file
 * 
 * @param filename
 *            path of the file
 * @param format
 *            [[FileFormat.Binary]] or [[FileFormat.Json]]
 * @return resulting ETL object
 */
public static ETL fromFile(String filename, FileFormat format) {
	ETL result = null;
	try {
		switch (format) {
			case Binary:
				try (FileInputStream fileInputStream = new FileInputStream(filename);
						GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
						ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
					result = (ETL) objectInputStream.readObject();
				}
				break;
			case GzipJson:
				try (FileInputStream fileInputStream = new FileInputStream(filename);
						GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
						JsonReader jr = new JsonReader(gzipInputStream)) {
					result = (ETL) jr.readObject();
				}
				break;
			case Json:
				try (FileInputStream fileInputStream = new FileInputStream(filename); JsonReader jr = new JsonReader(fileInputStream)) {
					result = (ETL) jr.readObject();
				}
				break;
		}
		result.filename = filename;
	} catch (Exception exception) {
		exception.printStackTrace();
	}
	return result;
}