Java Code Examples for java.io.ObjectInputStream#readObject()

The following examples show how to use java.io.ObjectInputStream#readObject() . 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: SimpleSerialization.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Vector<String> v1 = new Vector<>();

    v1.add("entry1");
    v1.add("entry2");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject(v1);
    oos.close();

    final byte[] data = baos.toByteArray();
    final ByteArrayInputStream bais = new ByteArrayInputStream(data);
    final ObjectInputStream ois = new ObjectInputStream(bais);

    final Object deserializedObject = ois.readObject();
    ois.close();

    if (false == v1.equals(deserializedObject)) {
        throw new RuntimeException(getFailureText(v1, deserializedObject));
    }
}
 
Example 2
Source File: ReferencesClassifierAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    super.initialize(context);
    try {
        // load model for inference
        File modelfile = new File(ReferencesHelper.REFERENCES_RESOURCES
                + "models/" + modelName);
        checkArgument(modelfile.exists(), "no modelFile at " + modelName);
        ObjectInputStream s = new ObjectInputStream(new FileInputStream(
                modelfile));
        classifier = (Classifier) s.readObject();
        s.close();
        checkArgument(classifier != null);
        pipes = classifier.getInstancePipe();
    } catch (Exception e) {
        throw new ResourceInitializationException(e);
    }
}
 
Example 3
Source File: TestLocalDate_Basics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testSerialization() throws Exception {
    LocalDate test = new LocalDate(1972, 6, 9, COPTIC_PARIS);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(test);
    byte[] bytes = baos.toByteArray();
    oos.close();
    
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    LocalDate result = (LocalDate) ois.readObject();
    ois.close();
    
    assertEquals(test, result);
    assertTrue(Arrays.equals(test.getValues(), result.getValues()));
    assertTrue(Arrays.equals(test.getFields(), result.getFields()));
    assertEquals(test.getChronology(), result.getChronology());
}
 
Example 4
Source File: JMenuBar.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * See JComponent.readObject() for information about serialization
 * in Swing.
 */
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
{
    s.defaultReadObject();
    Object[] kvData = (Object[])(s.readObject());

    for(int i = 0; i < kvData.length; i += 2) {
        if (kvData[i] == null) {
            break;
        }
        else if (kvData[i].equals("selectionModel")) {
            selectionModel = (SingleSelectionModel)kvData[i + 1];
        }
    }

}
 
Example 5
Source File: SmallObjTrees.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run benchmark for given number of batches, with each batch containing the
 * given number of cycles.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, Node[] trees, int nbatches)
    throws Exception
{
    int ncycles = trees.length;
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        oout.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeObject(trees[j]);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readObject();
        }
    }
}
 
Example 6
Source File: ContainerEntity.java    From depends with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void reloadExpression(EntityRepo repo) {
	if (expressionCount ==0) return;
	try
      {
         FileInputStream fileIn = new FileInputStream(TemporaryFile.getInstance().exprPath(this.id));
         ObjectInputStream in = new ObjectInputStream(fileIn);
         expressionList = (ArrayList<Expression>) in.readObject();
         if (expressionList==null) expressionList = new ArrayList<>();
         for (Expression expr:expressionList) {
        	 expr.reload(repo,expressionList);
         }
         in.close();
         fileIn.close();
      }catch(IOException | ClassNotFoundException i)
      {
         return;
      }
}
 
Example 7
Source File: IOGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Iterates through the given object stream object by object. The
 * ObjectInputStream is closed afterwards.
 *
 * @param ois     an ObjectInputStream, closed after the operation
 * @param closure a closure
 * @throws IOException            if an IOException occurs.
 * @throws ClassNotFoundException if the class  is not found.
 * @since 1.0
 */
public static void eachObject(ObjectInputStream ois, Closure closure) throws IOException, ClassNotFoundException {
    try {
        while (true) {
            try {
                Object obj = ois.readObject();
                // we allow null objects in the object stream
                closure.call(obj);
            } catch (EOFException e) {
                break;
            }
        }
        InputStream temp = ois;
        ois = null;
        temp.close();
    } finally {
        closeWithWarning(ois);
    }
}
 
Example 8
Source File: TestUtils.java    From mapbox-java with MIT License 5 votes vote down vote up
public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> cl)
  throws IOException, ClassNotFoundException {
  ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  ObjectInputStream ois = new ObjectInputStream(bais);
  Object object = ois.readObject();
  return cl.cast(object);
}
 
Example 9
Source File: DragSource.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * Deserializes this <code>DragSource</code>. This method first performs
 * default deserialization. Next, this object's <code>FlavorMap</code> is
 * deserialized by using the next object in the stream.
 * If the resulting <code>FlavorMap</code> is <code>null</code>, this
 * object's <code>FlavorMap</code> is set to the default FlavorMap for
 * this thread's <code>ClassLoader</code>.
 * Next, this object's listeners are deserialized by reading a
 * <code>null</code>-terminated sequence of 0 or more key/value pairs
 * from the stream:
 * <ul>
 * <li>If a key object is a <code>String</code> equal to
 * <code>dragSourceListenerK</code>, a <code>DragSourceListener</code> is
 * deserialized using the corresponding value object and added to this
 * <code>DragSource</code>.
 * <li>If a key object is a <code>String</code> equal to
 * <code>dragSourceMotionListenerK</code>, a
 * <code>DragSourceMotionListener</code> is deserialized using the
 * corresponding value object and added to this <code>DragSource</code>.
 * <li>Otherwise, the key/value pair is skipped.
 * </ul>
 *
 * @see java.awt.datatransfer.SystemFlavorMap#getDefaultFlavorMap
 * @since 1.4
 */
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException {
    s.defaultReadObject();

    // 'flavorMap' was written explicitly
    flavorMap = (FlavorMap)s.readObject();

    // Implementation assumes 'flavorMap' is never null.
    if (flavorMap == null) {
        flavorMap = SystemFlavorMap.getDefaultFlavorMap();
    }

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

        if (dragSourceListenerK == key) {
            addDragSourceListener((DragSourceListener)(s.readObject()));
        } else if (dragSourceMotionListenerK == key) {
            addDragSourceMotionListener(
                (DragSourceMotionListener)(s.readObject()));
        } else {
            // skip value for unrecognized key
            s.readObject();
        }
    }
}
 
Example 10
Source File: BodyRequest.java    From DoraemonKit with Apache License 2.0 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 11
Source File: ServantManagerImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public NamingContextImpl readInContext(String objKey)
{
    NamingContextImpl context = (NamingContextImpl) contexts.get(objKey);
    if( context != null )
    {
            // Returning Context from Cache
            return context;
    }

    File contextFile = new File(logDir, objKey);
    if (contextFile.exists()) {
        try {
            FileInputStream fis = new FileInputStream(contextFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            context = (NamingContextImpl) ois.readObject();
            context.setORB( orb );
            context.setServantManagerImpl( this );
            context.setRootNameService( theNameService );
            ois.close();
        } catch (Exception ex) {
        }
    }

    if (context != null)
    {
            contexts.put(objKey, context);
    }
    return context;
}
 
Example 12
Source File: FileUtil.java    From ShootPlane with Apache License 2.0 5 votes vote down vote up
public static List<Score> readScore(String filePath) throws FileNotFoundException, IOException,
    ClassNotFoundException {
List<Score> scoreList = new ArrayList<Score>();
ObjectInputStream objInputStream = new ObjectInputStream(new FileInputStream(filePath));
Object obj = null;
while ((obj = objInputStream.readObject()) != null) {
    scoreList.add((Score) obj);
}
objInputStream.close();
return scoreList;
   }
 
Example 13
Source File: MasterReport.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * A helper method that deserializes a object from the given stream.
 *
 * @param stream
 *          the stream from which to read the object data.
 * @throws IOException
 *           if an IO error occured.
 * @throws ClassNotFoundException
 *           if an referenced class cannot be found.
 */
private void readObject( final ObjectInputStream stream ) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();

  updateResourceBundleFactoryInternal();

  reportConfiguration.reconnectConfiguration( ClassicEngineBoot.getInstance().getGlobalConfig() );
  addReportModelListener( new DocumentBundleChangeHandler() );

  try {
    final String bundleType = (String) stream.readObject();

    final byte[] bundleRawZip = (byte[]) stream.readObject();
    final ResourceManager mgr = getResourceManager();
    final Resource bundleResource = mgr.createDirectly( bundleRawZip, DocumentBundle.class );
    final DocumentBundle bundle = (DocumentBundle) bundleResource.getResource();

    final MemoryDocumentBundle mem = new MemoryDocumentBundle( getContentBase() );
    BundleUtilities.copyStickyInto( mem, bundle );
    BundleUtilities.copyInto( mem, bundle, LegacyBundleResourceRegistry.getInstance().getRegisteredFiles(), true );
    BundleUtilities.copyMetaData( mem, bundle );
    mem.getWriteableDocumentMetaData().setBundleType( bundleType );
    setBundle( mem );
  } catch ( ResourceException e ) {
    throw new IOException( e );
  }
}
 
Example 14
Source File: LoadAndDraw.java    From Canova with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) throws Exception {
	MnistDataSetIterator iter = new MnistDataSetIterator(60,60000);
	@SuppressWarnings("unchecked")
	ObjectInputStream ois = new ObjectInputStream(new FileInputStream(args[0]));
	
	BasePretrainNetwork network = (BasePretrainNetwork) ois.readObject();
	
	
	DataSet test = null;
	while(iter.hasNext()) {
		INDArray reconstructed = network.transform(test.getFeatureMatrix());
		for(int i = 0; i < test.numExamples(); i++) {
			INDArray draw1 = test.get(i).getFeatureMatrix().mul(255);
			INDArray reconstructed2 = reconstructed.getRow(i);
			INDArray draw2 = Sampling.binomial(reconstructed2, 1, new MersenneTwister(123)).mul(255);

			DrawReconstruction d = new DrawReconstruction(draw1);
			d.title = "REAL";
			d.draw();
			DrawReconstruction d2 = new DrawReconstruction(draw2,100,100);
			d2.title = "TEST";
			d2.draw();
			Thread.sleep(10000);
			d.frame.dispose();
			d2.frame.dispose();
		}
	}
	
	
}
 
Example 15
Source File: BytesUtil.java    From RCT with Apache License 2.0 5 votes vote down vote up
/**
 * 数组转对象
 */
public static Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
	if (bytes == null || bytes.length == 0) {
		return null;
	}
	Object obj = null;
	ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
	ObjectInputStream ois = new ObjectInputStream(bis);
	obj = ois.readObject();
	ois.close();
	bis.close();
	return obj;
}
 
Example 16
Source File: Log.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public static void loadLogs(StyledText styledTextLog,
								Display display,
								String file,
								String taskName,
								String loop,
								String logName,
								int index)
{
	try{
		FileInputStream instream = new FileInputStream(file);
        ObjectInputStream in = new ObjectInputStream(instream);
        int count = 0;
        while(true){
        	try{
        		LogInfo logInfo = (LogInfo)in.readObject();
        		
        		if(logInfo.task.equals(taskName) && logInfo.loop == Integer.parseInt(loop)){
        			if(logInfo.name.trim().equals(logName)){
        				
	        			count++;
	        			if(count == index){
	        				styledTextLog.setText(logInfo.getRunLog().toString());
	        				break;
	        			}
	        		}
        		}
        	}catch(Exception eof){
        		break;
        	}
        }
        in.close();
	}catch(Exception ex){
		ex.printStackTrace();
	}
}
 
Example 17
Source File: GraggBulirschStoerStepInterpolatorTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void serialization()
  throws DerivativeException, IntegratorException,
         IOException, ClassNotFoundException {

  TestProblem3 pb  = new TestProblem3(0.9);
  double minStep   = 0;
  double maxStep   = pb.getFinalTime() - pb.getInitialTime();
  double absTolerance = 1.0e-8;
  double relTolerance = 1.0e-8;

  GraggBulirschStoerIntegrator integ =
    new GraggBulirschStoerIntegrator(minStep, maxStep,
                                     absTolerance, relTolerance);
  integ.addStepHandler(new ContinuousOutputModel());
  integ.integrate(pb,
                  pb.getInitialTime(), pb.getInitialState(),
                  pb.getFinalTime(), new double[pb.getDimension()]);

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream    oos = new ObjectOutputStream(bos);
  for (StepHandler handler : integ.getStepHandlers()) {
      oos.writeObject(handler);
  }

  assertTrue(bos.size () > 33000);
  assertTrue(bos.size () < 34000);

  ByteArrayInputStream  bis = new ByteArrayInputStream(bos.toByteArray());
  ObjectInputStream     ois = new ObjectInputStream(bis);
  ContinuousOutputModel cm  = (ContinuousOutputModel) ois.readObject();

  Random random = new Random(347588535632l);
  double maxError = 0.0;
  for (int i = 0; i < 1000; ++i) {
    double r = random.nextDouble();
    double time = r * pb.getInitialTime() + (1.0 - r) * pb.getFinalTime();
    cm.setInterpolatedTime(time);
    double[] interpolatedY = cm.getInterpolatedState ();
    double[] theoreticalY  = pb.computeTheoreticalState(time);
    double dx = interpolatedY[0] - theoreticalY[0];
    double dy = interpolatedY[1] - theoreticalY[1];
    double error = dx * dx + dy * dy;
    if (error > maxError) {
      maxError = error;
    }
  }

  assertTrue(maxError < 5.0e-10);

}
 
Example 18
Source File: SerializationTester.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
    Object result = in.readObject();
    assertEquals(-1, in.read());
    return result;
}
 
Example 19
Source File: SerialTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
private static Serializable deserialize(byte[] bytes) throws Exception {
  ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
  ObjectInputStream objectStream = new ObjectInputStream(stream);
  return (Serializable) objectStream.readObject();
}
 
Example 20
Source File: LocalDateTime.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Reads the property from a safe serialization format.
 */
private void readObject(ObjectInputStream oos) throws IOException, ClassNotFoundException {
    iInstant = (LocalDateTime) oos.readObject();
    DateTimeFieldType type = (DateTimeFieldType) oos.readObject();
    iField = type.getField(iInstant.getChronology());
}