Java Code Examples for java.io.ObjectOutputStream#close()

The following examples show how to use java.io.ObjectOutputStream#close() . 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: LinkedBlockingQueueTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A deserialized serialized queue has same elements in same order
 */
public void testSerialization() throws Exception {
    LinkedBlockingQueue q = populatedQueue(SIZE);

    ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
    out.writeObject(q);
    out.close();

    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
    LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
    assertEquals(q.size(), r.size());
    while (!q.isEmpty())
        assertEquals(q.remove(), r.remove());
}
 
Example 2
Source File: SimpleSerialization.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final EnumMap<TestEnum, String> enumMap = new EnumMap<>(TestEnum.class);

    enumMap.put(TestEnum.e01, TestEnum.e01.name());
    enumMap.put(TestEnum.e04, TestEnum.e04.name());
    enumMap.put(TestEnum.e05, TestEnum.e05.name());

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

    oos.writeObject(enumMap);
    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 == enumMap.equals(deserializedObject)) {
        throw new RuntimeException(getFailureText(enumMap, deserializedObject));
    }
}
 
Example 3
Source File: TestDateMidnight_Basics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testSerialization() throws Exception {
    DateMidnight test = new DateMidnight(TEST_TIME_NOW_UTC);
    
    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);
    DateMidnight result = (DateMidnight) ois.readObject();
    ois.close();
    
    assertEquals(test, result);
}
 
Example 4
Source File: TelnetCodecTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
protected byte[] objectToByte(Object obj){
    byte[] bytes; 
    if (obj instanceof String){
        bytes = ((String)obj).getBytes();
    } else if (obj instanceof byte[]){
        bytes = (byte[]) obj;
    } else {
        try { 
            //object to bytearray 
            ByteArrayOutputStream bo = new ByteArrayOutputStream(); 
            ObjectOutputStream oo = new ObjectOutputStream(bo); 
            oo.writeObject(obj); 
            bytes = bo.toByteArray(); 
            bo.close(); 
            oo.close();     
        } 
        catch(Exception e){ 
            throw new RuntimeException(e);
        } 
    }
    return(bytes); 
}
 
Example 5
Source File: AutomaticLazyLoadingTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
/**
 * Disable lazy loaders by serializing / deserializing the element
 */
private Element disableLazyLoaders(Element anElement) 
throws Exception {
  ByteArrayOutputStream myBuffer = new ByteArrayOutputStream();
  
  ObjectOutputStream myObjectOutputStream = new ObjectOutputStream(myBuffer);
  myObjectOutputStream.writeObject(anElement);
  myObjectOutputStream.close();
  
  myBuffer.close();
  
  ObjectInputStream myObjectInputStream = new ObjectInputStream(new ByteArrayInputStream(myBuffer.toByteArray()));
  Element myResult = (Element)myObjectInputStream.readObject();
  myObjectInputStream.close();
  
  return myResult;
}
 
Example 6
Source File: EggTool.java    From frog with Apache License 2.0 6 votes vote down vote up
/**
 * Frogs which have higher energy lay eggs
 * 
 * 利用Java串行机制存盘。 能量多(也就是吃的更多)的Frog下蛋并存盘, 以进行下一轮测试,能量少的Frog被淘汰,没有下蛋的资格。
 * 用能量的多少来简化生存竟争模拟,每次下蛋数量固定为EGG_QTY个
 */
public static void layEggs() {
	sortFrogsOrderByEnergyDesc();

	Frog first = Env.frogs.get(0);
	Frog last = Env.frogs.get(Env.frogs.size() - 1);

	try {
		Env.eggs.clear();
		for (int i = 0; i < Env.EGG_QTY; i++)
			Env.eggs.add(new Egg(Env.frogs.get(i)));
		FileOutputStream fo = new FileOutputStream(Application.CLASSPATH + "eggs.ser");
		ObjectOutputStream so = new ObjectOutputStream(fo);
		so.writeObject(Env.eggs);
		so.close();
		System.out.print("\r1st frog has " + first.organs.size() + " organs, energy=" + first.energy + ", seeDist="
				+ ((Eye) first.organs.get(6)).seeDistance + ", chance=" + ((Chance) first.organs.get(10)).percent);
		System.out.println(", Last frog has " + last.organs.size() + " organs,  energy=" + last.energy);
		System.out.println("Saved "+Env.eggs.size() +" eggs to file '" + Application.CLASSPATH + "eggs.ser'");
	} catch (IOException e) {
		System.out.println(e);
	}
}
 
Example 7
Source File: SerializationUtilsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testSerializeStream() throws Exception {
    ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
    SerializationUtils.serialize(iMap, streamTest);

    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(iMap);
    oos.flush();
    oos.close();

    byte[] testBytes = streamTest.toByteArray();
    byte[] realBytes = streamReal.toByteArray();
    assertEquals(testBytes.length, realBytes.length);
    for (int i = 0; i < realBytes.length; i++) {
        assertEquals(realBytes[i], testBytes[i]);
    }
}
 
Example 8
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Serializes the given object into the path. Returns false on failure. */
public boolean serialize(final Object ob, final String path) {
	try {
		// 1 - Check that the parent chain of folders exists, and attempt to create it when not:
		final File fdir = new File(path).getParentFile();
		if (null == fdir) return false;
		fdir.mkdirs();
		if (!fdir.exists()) {
			Utils.log2("Could not create folder " + fdir.getAbsolutePath());
			return false;
		}
		// 2 - Serialize the given object:
		final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
		out.writeObject(ob);
		out.close();
		return true;
	} catch (final Exception e) {
		IJError.print(e);
	}
	return false;
}
 
Example 9
Source File: TCKChronoPeriod.java    From openjdk-jdk8u with GNU General Public License v2.0 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 10
Source File: ProcessInstanceResolverStrategyTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private int calculateNumBytesForLong(String longVal) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeUTF(longVal);
    baos.close();
    oos.close();
    return baos.toByteArray().length;
}
 
Example 11
Source File: Serializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize an object
 *
 * @param obj the object to serialize
 * @return the byte array of the serialized object
 * @throws IOException the possible io exception
 */
public static byte[] serialize(Object obj) throws IOException {
  final ByteArrayOutputStream b = new ByteArrayOutputStream();
  final ObjectOutputStream o = new ObjectOutputStream(b);
  o.writeObject(obj);
  o.close();
  return b.toByteArray();
}
 
Example 12
Source File: TestDateTimeFieldType.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private DateTimeFieldType doSerialization(DateTimeFieldType type) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(type);
    byte[] bytes = baos.toByteArray();
    oos.close();
    
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    DateTimeFieldType result = (DateTimeFieldType) ois.readObject();
    ois.close();
    return result;
}
 
Example 13
Source File: SerializationUtilsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testSerializeBytes() throws Exception {
    byte[] testBytes = SerializationUtils.serialize(iMap);

    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(iMap);
    oos.flush();
    oos.close();

    byte[] realBytes = streamReal.toByteArray();
    assertEquals(testBytes.length, realBytes.length);
    for (int i = 0; i < realBytes.length; i++) {
        assertEquals(realBytes[i], testBytes[i]);
    }
}
 
Example 14
Source File: RepositoryImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void flush()
{
    try {
        db.delete();
        FileOutputStream fos = new FileOutputStream(db);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this);
        oos.flush();
        oos.close();
    } catch (Exception ex) {
        throw wrapper.cannotWriteRepositoryDb( ex ) ;
    }
}
 
Example 15
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobSerializableType() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(baos);
	oos.writeObject("content");
	oos.close();

	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(new ByteArrayInputStream(baos.toByteArray()));

	BlobSerializableType type = new BlobSerializableType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(Serializable.class, type.returnedClass());
	assertTrue(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
 
Example 16
Source File: Originator.java    From training with MIT License 5 votes vote down vote up
public Memento generateMemento() {
	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(this);
		oos.close();
		return new Memento(baos.toByteArray());
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 17
Source File: ResolvableTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private ResolvableType testSerialization(ResolvableType type) throws Exception {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(bos);
	oos.writeObject(type);
	oos.close();
	ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
	ResolvableType read = (ResolvableType) ois.readObject();
	assertThat(read, equalTo(type));
	assertThat(read.getType(), equalTo(type.getType()));
	assertThat(read.resolve(), equalTo((Class) type.resolve()));
	return read;
}
 
Example 18
Source File: FirstInstance.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
public static boolean openFiles(List<String> files) {
    try {
        ObjectOutputStream oos = startCommand("open");
        oos.writeInt(files.size());
        for (String s : files) {
            oos.writeUTF(s);
        }
        oos.close();
        return true;
    } catch (IOException ex) {
        return false;
    }
}
 
Example 19
Source File: DfaBuilder.java    From dfalex with Apache License 2.0 4 votes vote down vote up
private String _getCacheKey(final int dfaType, List<Set<MATCHRESULT>> languages, DfaAmbiguityResolver<? super MATCHRESULT> ambiguityResolver)
{
    String cacheKey;
    try
    {
        //generate the cache key by serializing key info into an SHA hash
        SHAOutputStream sha = new SHAOutputStream();
        sha.on(false);
        ObjectOutputStream os = new ObjectOutputStream(sha);
        os.flush();
        sha.on(true);
        os.writeInt(dfaType);
        final int numLangs = languages.size();
        os.writeInt(numLangs);
        
        //write key stuff out in an order based on our LinkedHashMap, for deterministic serialization
        for (Entry<MATCHRESULT, List<Matchable>> patEntry : m_patterns.entrySet())
        {
            boolean included = false;
            List<Matchable> patList = patEntry.getValue();
            if (patList.isEmpty())
            {
                continue;
            }
            for (int i=0; i<numLangs; ++i)
            {
                if (!languages.get(i).contains(patEntry.getKey()))
                {
                    continue;
                }
                included = true;
                break;
            }
            if (!included)
            {
                continue;
            }
            os.writeInt(patList.size());
            if (numLangs>1)
            {
                int bits=languages.get(0).contains(patEntry.getKey()) ? 1:0;
                for (int i=1; i<languages.size(); ++i)
                {
                    if ((i&31)==0)
                    {
                        os.writeInt(bits);
                        bits=0;
                    }
                    if (languages.get(i).contains(patEntry.getKey()))
                    {
                        bits |= 1<<(i&31);
                    }
                }
                os.writeInt(bits);
            }
            for (Matchable pat : patList)
            {
                os.writeObject(pat);
            }
            os.writeObject(patEntry.getKey());
        }
        os.writeInt(0); //0-size pattern list terminates pattern map
        os.writeObject(ambiguityResolver);
        os.flush();
        
        cacheKey = sha.getBase32Digest();
        os.close();
    }
    catch(IOException e)
    {
        //doesn't really happen
        throw new RuntimeException(e);
    }
    return cacheKey;
}
 
Example 20
Source File: OAuthUtils.java    From yfiton with Apache License 2.0 4 votes vote down vote up
public static void writeAuthorizationInfo(Path file, AuthorizationData data) throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(file));
    oos.writeObject(data);
    oos.close();
}