Java Code Examples for java.io.ObjectOutputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Absolute-Android-RSS, under directory /src/com/AA/Services/.

Source file: RssService.java

  20 
vote

/** 
 * Writes the received data to the application settings so that data restoration is easier
 * @param articleList - List of all the articles that have been aggregated from the stream
 */
public static void writeData(Context context,List<Article> articleList){
  try {
    FileOutputStream fileStream=context.openFileOutput("articles",Context.MODE_PRIVATE);
    ObjectOutputStream writer=new ObjectOutputStream(fileStream);
    writer.writeObject(articleList);
    writer.close();
    fileStream.close();
  }
 catch (  IOException e) {
    Log.e("AARSS","Problem saving file.",e);
    return;
  }
}
 

Example 2

From project aether-core, under directory /aether-api/src/test/java/org/eclipse/aether/.

Source file: RepositoryExceptionTest.java

  18 
vote

private void assertSerializable(RepositoryException e){
  try {
    ObjectOutputStream oos=new ObjectOutputStream(new ByteArrayOutputStream());
    oos.writeObject(e);
    oos.close();
  }
 catch (  IOException ioe) {
    throw new IllegalStateException(ioe);
  }
}
 

Example 3

From project agraph-java-client, under directory /src/test/.

Source file: RepositoryConnectionTest.java

  18 
vote

@Test public void testStatementSerialization() throws Exception {
  testCon.add(bob,name,nameBob);
  Statement st;
  RepositoryResult<Statement> statements=testCon.getStatements(null,null,null,true);
  try {
    st=statements.next();
  }
  finally {
    statements.close();
  }
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(baos);
  out.writeObject(st);
  out.close();
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream in=new ObjectInputStream(bais);
  Statement deserializedStatement=(Statement)in.readObject();
  in.close();
  assertTrue(st.equals(deserializedStatement));
  assertTrue(testCon.hasStatement(st,true));
  assertTrue(testCon.hasStatement(deserializedStatement,true));
}
 

Example 4

From project airlift, under directory /jmx-http-rpc/src/main/java/io/airlift/jmx/http/rpc/.

Source file: HttpMBeanServerRpc.java

  18 
vote

public static byte[] serialize(Object object) throws IOException {
  ByteArrayOutputStream bytes=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(bytes);
  objectOutputStream.writeObject(object);
  objectOutputStream.flush();
  objectOutputStream.close();
  return bytes.toByteArray();
}
 

Example 5

From project Airports, under directory /src/com/nadmm/airports/wx/.

Source file: NoaaService.java

  18 
vote

protected void writeObject(Object object,File objFile){
  try {
    ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(objFile));
    out.writeObject(object);
    out.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 6

From project AlarmApp-Android, under directory /src/org/alarmapp/util/.

Source file: Store.java

  18 
vote

public void write(T instance){
  FileOutputStream out;
  try {
    out=new FileOutputStream(this.file);
    ObjectOutputStream outStream=new ObjectOutputStream(out);
    outStream.writeObject(instance);
    out.close();
  }
 catch (  FileNotFoundException e) {
    LogEx.exception(e);
  }
catch (  IOException e) {
    LogEx.exception(e);
  }
catch (  Exception ex) {
    LogEx.exception(ex);
  }
}
 

Example 7

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/.

Source file: SerializableEntity.java

  18 
vote

private void createBytes(Serializable ser) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(baos);
  out.writeObject(ser);
  out.flush();
  this.objSer=baos.toByteArray();
}
 

Example 8

From project amplafi-sworddance, under directory /src/test/java/com/sworddance/taskcontrol/.

Source file: TestFutureListenerNotifier.java

  18 
vote

private <F>F serializeDeserialize(F futureResult) throws IOException, ClassNotFoundException {
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(out);
  objectOutputStream.writeObject(futureResult);
  objectOutputStream.close();
  ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
  ObjectInputStream objectInputStream=new ObjectInputStream(in);
  F f=(F)objectInputStream.readObject();
  assertNotNull(f);
  return f;
}
 

Example 9

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: PersistentCookieStore.java

  18 
vote

protected String encodeCookie(SerializableCookie cookie){
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  try {
    ObjectOutputStream outputStream=new ObjectOutputStream(os);
    outputStream.writeObject(cookie);
  }
 catch (  Exception e) {
    return null;
  }
  return byteArrayToHexString(os.toByteArray());
}
 

Example 10

From project android-vpn-server, under directory /src/com/android/server/vpn/.

Source file: VpnServiceBinder.java

  18 
vote

void saveStates() throws IOException {
  if (DBG)   Log.d("VpnServiceBinder","     saving states");
  ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(getStateFilePath()));
  oos.writeObject(mService);
  oos.close();
}
 

Example 11

From project android-vpn-settings, under directory /src/com/android/settings/vpn/.

Source file: VpnSettings.java

  18 
vote

static void saveProfileToStorage(VpnProfile p) throws IOException {
  File f=new File(getProfileDir(p));
  if (!f.exists())   f.mkdirs();
  ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File(f,PROFILE_OBJ_FILE)));
  oos.writeObject(p);
  oos.close();
}
 

Example 12

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: SOContainer.java

  18 
vote

public static byte[] serialize(Serializable obj) throws IOException {
  final ByteArrayOutputStream bos=new ByteArrayOutputStream();
  final ObjectOutputStream oos=new ObjectOutputStream(bos);
  oos.writeObject(obj);
  return bos.toByteArray();
}
 

Example 13

From project android_5, under directory /src/aarddict/android/.

Source file: DictionariesActivity.java

  18 
vote

void saveVerifyData() throws IOException {
  File verifyDir=getDir("verify",0);
  File verifyFile=new File(verifyDir,"verifydata");
  FileOutputStream fout=new FileOutputStream(verifyFile);
  ObjectOutputStream oout=new ObjectOutputStream(fout);
  oout.writeObject(verifyData);
}
 

Example 14

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/vpn/.

Source file: VpnSettings.java

  18 
vote

static void saveProfileToStorage(VpnProfile p) throws IOException {
  File f=new File(getProfileDir(p));
  if (!f.exists())   f.mkdirs();
  ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File(f,PROFILE_OBJ_FILE)));
  oos.writeObject(p);
  oos.close();
}
 

Example 15

From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.

Source file: AreaCodeMap.java

  18 
vote

/** 
 * Gets the size of the provided area code map storage. The map storage passed-in will be filled as a result.
 */
private static int getSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategy mapStorage,SortedMap<Integer,String> areaCodeMap) throws IOException {
  mapStorage.readFromSortedMap(areaCodeMap);
  ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
  mapStorage.writeExternal(objectOutputStream);
  objectOutputStream.flush();
  int sizeOfStorage=byteArrayOutputStream.size();
  objectOutputStream.close();
  return sizeOfStorage;
}
 

Example 16

From project apb, under directory /modules/apb-base/src/apb/testrunner/.

Source file: Main.java

  18 
vote

private static void saveOutput(@NotNull TestReport report,@Nullable String reportSpecFile){
  if (reportSpecFile != null) {
    try {
      ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(reportSpecFile));
      os.writeObject(report);
      os.close();
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 

Example 17

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.

Source file: PersistentHash.java

  18 
vote

private synchronized void appendEntryToStore(Message message) throws IOException {
  String filename=message.getKey();
  File file=new File(dirname,filename);
  FileOutputStream fos=new FileOutputStream(file,true);
  BufferedOutputStream bos=new BufferedOutputStream(fos);
  ObjectOutputStream oos=new ObjectOutputStream(bos);
  oos.writeObject(message);
  oos.flush();
  oos.close();
  fos.flush();
  fos.close();
}
 

Example 18

From project arquillian-core, under directory /protocols/jmx/src/main/java/org/jboss/arquillian/protocol/jmx/.

Source file: Serializer.java

  18 
vote

public static byte[] toByteArray(Object object){
  try {
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    ObjectOutputStream outObj=new ObjectOutputStream(out);
    outObj.writeObject(object);
    outObj.flush();
    return out.toByteArray();
  }
 catch (  Exception e) {
    throw new RuntimeException("Could not serialize object: " + object,e);
  }
}
 

Example 19

From project arquillian-extension-drone, under directory /drone-webdriver/src/main/java/org/jboss/arquillian/drone/webdriver/factory/remote/reusable/.

Source file: SerializationUtils.java

  18 
vote

/** 
 * Takes serializable object and serializes it to the byte array
 * @param object object to serialize
 * @return the byte array representing serializable object
 * @throws InvalidClassException Something is wrong with a class used by serialization.
 * @throws NotSerializableException Some object to be serialized does not implement the java.io.Serializable interface.
 * @throws IOException Any exception thrown by the underlying OutputStream.
 */
public static byte[] serializeToBytes(Serializable object) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(object);
  return baos.toByteArray();
}
 

Example 20

From project arquillian-extension-jrebel, under directory /impl/src/main/java/org/jboss/arquillian/extension/jrebel/.

Source file: Serializer.java

  18 
vote

public static byte[] toByteArray(Object object){
  try {
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    ObjectOutputStream outObj=new ObjectOutputStream(out);
    outObj.writeObject(object);
    outObj.flush();
    return out.toByteArray();
  }
 catch (  Exception e) {
    throw new RuntimeException("Could not serialize object: " + object,e);
  }
}
 

Example 21

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/utils/.

Source file: SerializationUtils.java

  18 
vote

public static byte[] serializeToBytes(Serializable object){
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(object);
    return baos.toByteArray();
  }
 catch (  IOException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 22

From project arquillian_deprecated, under directory /protocols/jmx/src/main/java/org/jboss/arquillian/protocol/jmx/.

Source file: JMXTestRunner.java

  18 
vote

public InputStream runTestMethodRemote(String className,String methodName){
  TestResult result=runTestMethodInternal(className,methodName);
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(result);
    oos.close();
    return new ByteArrayInputStream(baos.toByteArray());
  }
 catch (  IOException ex) {
    throw new IllegalStateException("Cannot marshall response",ex);
  }
}
 

Example 23

From project astyanax, under directory /src/main/java/com/netflix/astyanax/serializers/.

Source file: ObjectSerializer.java

  18 
vote

@Override public ByteBuffer toByteBuffer(Object obj){
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(obj);
    oos.close();
    return ByteBuffer.wrap(baos.toByteArray());
  }
 catch (  IOException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 24

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.

Source file: Response.java

  18 
vote

/** 
 * Serializes the Response into an  {@link OutputStream}
 * @param outStream the {@link OutputStream} which write objects to
 * @throws IOException the OutputStream default exception
 */
public final void serialize(OutputStream outStream) throws IOException {
  ObjectOutputStream out=new ObjectOutputStream(outStream);
  out.writeInt(this.format.ordinal());
  out.writeInt(this.status);
  out.writeObject(this.getBody());
  out.close();
}
 

Example 25

From project AuToBI, under directory /test/edu/cuny/qc/speech/AuToBI/.

Source file: AuToBITest.java

  18 
vote

private void writeClassifierToFile(String filename,AuToBIClassifier classifier) throws IOException {
  FileOutputStream fos;
  ObjectOutputStream out;
  fos=new FileOutputStream(filename);
  out=new ObjectOutputStream(fos);
  out.writeObject(classifier);
  out.close();
}
 

Example 26

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/test/java/com/microsoft/samples/federation/.

Source file: ClaimTest.java

  18 
vote

public void testClaimShouldSerialize() throws Exception {
  OutputStream outputStreamStub=new OutputStream(){
    public void write(    int b) throws IOException {
    }
  }
;
  ObjectOutputStream objectStream=new ObjectOutputStream(outputStreamStub);
  Claim claim=new Claim("http://mysite/myclaim","claimValue");
  objectStream.writeObject(claim);
}
 

Example 27

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.

Source file: Serializer.java

  18 
vote

/** 
 * Serializes an object using default serialization.
 * @param obj an object need to serialize
 * @return the byte array of the serialized object
 * @throws IOException io exception
 */
public static byte[] serialize(final Serializable obj) throws IOException {
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  final ObjectOutputStream oos=new ObjectOutputStream(baos);
  try {
    oos.writeObject(obj);
  }
  finally {
    oos.close();
  }
  return baos.toByteArray();
}
 

Example 28

From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/.

Source file: ObjectOrientedSocketHandler.java

  18 
vote

/** 
 * ------------------------------------ Instance Initialization ------------------------------------
 * @param host  DOCUMENT ME!
 * @param port  DOCUMENT ME!
 */
public ObjectOrientedSocketHandler(final String host,final int port){
  final Socket socket;
  final OutputStream outStream;
  ObjectOutputStream localStream=null;
  try {
    socket=new Socket(host,port);
    outStream=socket.getOutputStream();
    localStream=new ObjectOutputStream(outStream);
  }
 catch (  IOException e) {
    reportError(e.getMessage(),e,ErrorManager.OPEN_FAILURE);
  }
  this.stream=localStream;
}
 

Example 29

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/dal/.

Source file: CacheContext.java

  18 
vote

public synchronized <T>void saveData(T data) throws FileAccessException {
  try {
    FileOutputStream fStr=new FileOutputStream(new File(cacheDir,cacheName));
    ObjectOutputStream out=new ObjectOutputStream(fStr);
    out.writeObject(data);
    out.close();
  }
 catch (  IOException e) {
    String message=String.format("Data isn't stored in the cache %1$s%2$s: $3$s",cacheDir,cacheName,e.getMessage());
    throw new FileAccessException(message);
  }
}
 

Example 30

From project big-data-plugin, under directory /shims/api/src/org/pentaho/hbase/shim/api/.

Source file: HBaseValueMeta.java

  18 
vote

/** 
 * Encodes and object via serialization
 * @param obj the object to encode
 * @return an array of bytes containing the serialized object
 * @throws IOException if serialization fails
 */
public static byte[] encodeObject(Object obj) throws IOException {
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  BufferedOutputStream buf=new BufferedOutputStream(bos);
  ObjectOutputStream oos=new ObjectOutputStream(buf);
  oos.writeObject(obj);
  buf.flush();
  return bos.toByteArray();
}
 

Example 31

From project Carolina-Digital-Repository, under directory /services/src/main/java/edu/unc/lib/dl/cdr/services/model/.

Source file: FailedObjectHashMap.java

  18 
vote

public synchronized void serializeFailedEnhancements(String filePath) throws IOException {
  log.debug("Serializing failed object hashmap to " + filePath);
  FileOutputStream fileOutputStream=new FileOutputStream(filePath);
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
  objectOutputStream.writeObject(this);
}
 

Example 32

From project cascading, under directory /src/hadoop/cascading/flow/hadoop/util/.

Source file: JavaObjectSerializer.java

  18 
vote

@Override public <T>byte[] serialize(T object,boolean compress) throws IOException {
  if (object instanceof Map)   return serializeMap((Map<String,?>)object,compress);
  if (object instanceof List)   return serializeList((List<?>)object,compress);
  ByteArrayOutputStream bytes=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(compress ? new GZIPOutputStream(bytes) : bytes);
  try {
    out.writeObject(object);
  }
  finally {
    out.close();
  }
  return bytes.toByteArray();
}
 

Example 33

From project cascading-avro, under directory /cascading-avro/src/test/java/com/maxpoint/cascading/avro/.

Source file: AvroSchemeTest.java

  18 
vote

@Test public void testSerialization() throws Exception {
  final Schema.Parser parser=new Schema.Parser();
  final Schema schema=parser.parse(getClass().getResourceAsStream("test1.avsc"));
  final AvroScheme expected=new AvroScheme(schema);
  final ByteArrayOutputStream bytes=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(bytes);
  oos.writeObject(expected);
  oos.close();
  final ObjectInputStream iis=new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
  final AvroScheme actual=(AvroScheme)iis.readObject();
  assertEquals(expected,actual);
}
 

Example 34

From project Cassandra-Client-Tutorial, under directory /src/test/java/com/jeklsoft/cassandraclient/hector/.

Source file: TestExtendedTypeInferringSerializer.java

  18 
vote

private byte[] createByteArrayFromObject(Object obj) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
  objectOutputStream.writeObject(obj);
  objectOutputStream.close();
  return byteArrayOutputStream.toByteArray();
}
 

Example 35

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/util/.

Source file: SerializationUtils.java

  18 
vote

public static byte[] serializeToBytes(Serializable object){
  try {
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(object);
    return baos.toByteArray();
  }
 catch (  IOException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 36

From project ciel-java, under directory /bindings/src/main/java/com/asgow/ciel/executor/.

Source file: Ciel.java

  18 
vote

public static Reference[] spawn(FirstClassJavaTask taskObject,String[] args,int numOutputs) throws IOException {
  WritableReference objOut=Ciel.RPC.getNewObjectFilename("obj");
  ObjectOutputStream oos=new ObjectOutputStream(objOut.open());
  oos.writeObject(taskObject);
  oos.close();
  Reference objRef=objOut.getCompletedRef();
  FirstClassJavaTaskInformation fcjti=new FirstClassJavaTaskInformation(objRef,Ciel.jarLib,args,numOutputs);
  for (  Reference dependency : taskObject.getDependencies()) {
    if (dependency != null) {
      fcjti.addDependency(dependency);
    }
  }
  return Ciel.RPC.spawnTask(fcjti);
}
 

Example 37

From project Cilia_1, under directory /components/tcp-adapter/src/main/java/fr/liglab/adele/cilia/tcp/.

Source file: TCPSender.java

  18 
vote

private byte[] serializeObject(Object message) throws IOException {
  if (message instanceof byte[]) {
    return (byte[])message;
  }
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(message);
  return baos.toByteArray();
}
 

Example 38

From project citrus-sample, under directory /petstore/dal/src/test/java/com/alibaba/sample/petstore/dal/dataobject/.

Source file: CartTests.java

  18 
vote

private Cart deepClone() throws Exception {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(cart);
  oos.close();
  ObjectInputStream ois=new ObjectInputStream(baos.toInputStream());
  try {
    return (Cart)ois.readObject();
  }
  finally {
    ois.close();
  }
}
 

Example 39

From project cogroo4, under directory /cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/applier/.

Source file: RulesTreesSerializedAccess.java

  18 
vote

public void persist(RulesTrees newRulesTrees){
  if (newRulesTrees == null) {
    throw new IllegalArgumentException();
  }
  long start=System.nanoTime();
  try {
    ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(serializedRulesFile));
    out.writeObject(newRulesTrees);
    LOGGER.info("Rules trees serialized in " + (System.nanoTime() - start) / 1000000 + "ms");
  }
 catch (  IOException e) {
    LOGGER.warn("Could not serialize rules trees");
  }
}
 

Example 40

From project collections-generic, under directory /src/test/org/apache/commons/collections15/comparators/.

Source file: TestReverseComparator.java

  18 
vote

/** 
 * Override this inherited test since Collections.reverseOrder doesn't adhere to the "soft" Comparator contract, and we've already "cannonized" the comparator returned by makeComparator.
 */
public void testSerializeDeserializeThenCompare() throws Exception {
  Comparator comp=new ReverseComparator(new ComparableComparator());
  ByteArrayOutputStream buffer=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(buffer);
  out.writeObject(comp);
  out.close();
  ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
  Object dest=in.readObject();
  in.close();
  assertEquals("obj != deserialize(serialize(obj))",comp,dest);
}
 

Example 41

From project comm, under directory /src/main/java/io/s4/comm/util/.

Source file: IOUtil.java

  18 
vote

public static void save(Object obj,String path) throws Exception {
  File f=new File(path);
  FileOutputStream fos=new FileOutputStream(f);
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(fos);
  objectOutputStream.writeObject(obj);
  objectOutputStream.close();
}
 

Example 42

From project commons-io, under directory /src/test/java/org/apache/commons/io/input/.

Source file: ClassLoaderObjectInputStreamTest.java

  18 
vote

public void testExpected() throws Exception {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(Boolean.FALSE);
  InputStream bais=new ByteArrayInputStream(baos.toByteArray());
  ClassLoaderObjectInputStream clois=new ClassLoaderObjectInputStream(getClass().getClassLoader(),bais);
  Boolean result=(Boolean)clois.readObject();
  assertTrue(!result.booleanValue());
}
 

Example 43

From project commons-logging, under directory /src/test/org/apache/commons/logging/jdk14/.

Source file: DefaultConfigTestCase.java

  18 
vote

public void testSerializable() throws Exception {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(log);
  oos.close();
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream ois=new ObjectInputStream(bais);
  log=(Log)ois.readObject();
  ois.close();
  checkLog();
}
 

Example 44

From project components, under directory /hornetq/src/main/java/org/switchyard/component/hornetq/.

Source file: HornetQProducer.java

  18 
vote

@Override public void process(final Exchange exchange) throws Exception {
  final Object body=exchange.getIn().getBody();
  final ClientMessage message=_session.createMessage(_hornetQEndpoint.isDurable());
  final ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
  final ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteOut);
  objectOutputStream.writeObject(body);
  message.getBodyBuffer().writeBytes(byteOut.toByteArray());
  _producer.send(message);
}
 

Example 45

From project core_1, under directory /runtime/src/main/java/org/switchyard/internal/io/.

Source file: ObjectStreamSerializer.java

  18 
vote

/** 
 * {@inheritDoc}
 */
@Override public <T>int serialize(T obj,Class<T> type,OutputStream out,int bufferSize) throws IOException {
  out=new CountingOutputStream(new BufferedOutputStream(out,bufferSize));
  try {
    ObjectOutputStream oos=new ObjectOutputStream(out);
    oos.writeObject(obj);
    oos.flush();
  }
  finally {
    if (isCloseEnabled()) {
      out.close();
    }
  }
  return ((CountingOutputStream)out).getCount();
}
 

Example 46

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  18 
vote

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
  prop=new Properties();
  prop.load(new FileInputStream("ferryinpres.properties"));
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  Socket sock=new Socket(prop.getProperty("IDENTITY_SERVER"),Integer.parseInt(prop.getProperty("IDENTITY_PORT")));
  ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream());
  ObjectInputStream in=new ObjectInputStream(sock.getInputStream());
  SecretKey sessionKey=keyExchange(in,out);
  Cipher cryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  cryptor.init(Cipher.ENCRYPT_MODE,sessionKey);
  Cipher decryptor=Cipher.getInstance("DES/ECB/PKCS5Padding");
  decryptor.init(Cipher.DECRYPT_MODE,sessionKey);
  login(in,out,cryptor,decryptor);
}
 

Example 47

From project crash, under directory /shell/core/src/test/java/org/crsh/shell/impl/remoting/.

Source file: RemoteShellTestCase.java

  18 
vote

@Override protected void setUp() throws Exception {
  PipedChannel a=new PipedChannel();
  PipedChannel b=new PipedChannel();
  ObjectOutputStream clientOOS=new ObjectOutputStream(a.getOut());
  clientOOS.flush();
  ObjectOutputStream serverOOS=new ObjectOutputStream(b.getOut());
  serverOOS.flush();
  ObjectInputStream serverOIS=new ObjectInputStream(a.getIn());
  ObjectInputStream clientOIS=new ObjectInputStream(b.getIn());
  this.clientOIS=clientOIS;
  this.clientOOS=clientOOS;
  this.serverOIS=serverOIS;
  this.serverOOS=serverOOS;
}
 

Example 48

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  17 
vote

void save(Writer w) throws IOException {
  if (expired)   return;
  w.write(id);
  w.write(':');
  w.write(Integer.toString(inactiveInterval));
  w.write(':');
  w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext.getServletContextName());
  w.write(':');
  w.write(Long.toString(lastAccessTime));
  w.write("\r\n");
  Enumeration<String> e=getAttributeNames();
  ByteArrayOutputStream os=new ByteArrayOutputStream(1024 * 16);
  while (e.hasMoreElements()) {
    String aname=(String)e.nextElement();
    Object so=get(aname);
    if (so instanceof Serializable) {
      os.reset();
      ObjectOutputStream oos=new ObjectOutputStream(os);
      try {
        oos.writeObject(so);
        w.write(aname);
        w.write(":");
        w.write(Utils.base64Encode(os.toByteArray()));
        w.write("\r\n");
      }
 catch (      IOException ioe) {
        servletContext.log("Can't replicate/store a session value of '" + aname + "' class:"+ so.getClass().getName(),ioe);
      }
    }
 else     servletContext.log("Non serializable session object has been " + so.getClass().getName() + " skiped in storing of "+ aname,null);
    if (so instanceof HttpSessionActivationListener)     ((HttpSessionActivationListener)so).sessionWillPassivate(new HttpSessionEvent((HttpSession)this));
  }
  w.write("$$\r\n");
}
 

Example 49

From project abalone-android, under directory /src/com/bytopia/abalone/.

Source file: GameActivity.java

  17 
vote

@Override protected void onPause(){
  Log.d("state","paused");
  try {
    FileOutputStream fos=openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
    ObjectOutputStream oos=new ObjectOutputStream(fos);
    oos.writeObject(game.getBoard());
    oos.writeByte(game.getSide());
    oos.writeByte(game.getVsType());
    if (cpuType != null) {
      oos.writeObject(cpuType);
    }
    oos.writeByte((byte)game.getBoard().getMarblesCaptured(Side.BLACK));
    oos.writeByte((byte)game.getBoard().getMarblesCaptured(Side.WHITE));
    oos.close();
  }
 catch (  FileNotFoundException e) {
    Log.d("state","FileNotFound");
  }
catch (  IOException e) {
    Log.d("state","IO Exception");
  }
  super.onPause();
}
 

Example 50

From project activemq-apollo, under directory /apollo-openwire/src/main/scala/org/apache/activemq/apollo/openwire/command/.

Source file: ActiveMQObjectMessage.java

  17 
vote

public void storeContent(){
  Buffer bodyAsBytes=getContent();
  if (bodyAsBytes == null && object != null) {
    try {
      ByteArrayOutputStream bytesOut=new ByteArrayOutputStream();
      OutputStream os=bytesOut;
      if (Settings.enable_compression()) {
        compressed=true;
        os=new DeflaterOutputStream(os);
      }
      DataOutputStream dataOut=new DataOutputStream(os);
      ObjectOutputStream objOut=new ObjectOutputStream(dataOut);
      objOut.writeObject(object);
      objOut.flush();
      objOut.reset();
      objOut.close();
      setContent(bytesOut.toBuffer());
    }
 catch (    IOException ioe) {
      throw new RuntimeException(ioe.getMessage(),ioe);
    }
  }
}
 

Example 51

From project Android, under directory /app/src/main/java/com/github/mobile/.

Source file: RequestWriter.java

  17 
vote

/** 
 * Write request to file
 * @param request
 * @return request
 */
public <V>V write(V request){
  RandomAccessFile dir=null;
  FileLock lock=null;
  ObjectOutputStream output=null;
  try {
    createDirectory(handle.getParentFile());
    dir=new RandomAccessFile(handle,"rw");
    lock=dir.getChannel().lock();
    output=new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(dir.getFD()),8192));
    output.writeInt(version);
    output.writeObject(request);
  }
 catch (  IOException e) {
    Log.d(TAG,"Exception writing cache " + handle.getName(),e);
    return null;
  }
 finally {
    if (output != null)     try {
      output.close();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception closing stream",e);
    }
    if (lock != null)     try {
      lock.release();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception unlocking file",e);
    }
    if (dir != null)     try {
      dir.close();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception closing file",e);
    }
  }
  return request;
}
 

Example 52

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.

Source file: FFXIEQSettings.java

  17 
vote

public long saveCharInfo(long id,String name,FFXICharacter charInfo){
  byte[] chardata;
  charInfo.reload();
  try {
    ObjectOutputStream oos;
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ;
    oos=new ObjectOutputStream(baos);
    oos.writeObject(charInfo);
    oos.close();
    chardata=baos.toByteArray();
    baos.close();
  }
 catch (  IOException e) {
    return -1;
  }
  return saveCharInfo(id,name,chardata,charInfo.getMeritPointId());
}
 

Example 53

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: AndroidFlashcards.java

  17 
vote

private LessonListItem parseLesson(File f,File bf,String fbase){
  Lesson l=null;
  LessonListItem lli=null;
  handler.sendMessage(handler.obtainMessage(2,"Parsing: " + fbase));
  if (f.length() <= 0) {
    if (f.delete())     handler.sendMessage(handler.obtainMessage(3,f.getName()));
    return null;
  }
  try {
    FileOutputStream fos=new FileOutputStream(bf);
    ObjectOutputStream oos=new ObjectOutputStream(fos);
    if (f.getName().endsWith(".xml"))     l=parseXML(f,fbase);
 else     if (f.getName().endsWith(".csv"))     l=parseCSV(f,fbase);
    if (l != null) {
      oos.writeObject(l);
      oos.close();
      lli=new LessonListItem(bf.getAbsolutePath(),f.getAbsolutePath(),l.name(),l.description(),"Cards: " + l.cardCount(),false);
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return lli;
}
 

Example 54

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: TileMemoryCardCache.java

  17 
vote

/** 
 * Serializes the cache map.
 * @return true if the map was serialized successfully, false otherwise.
 */
private synchronized boolean serializeCacheMap(){
  try {
    File file=new File(this.tempDir,SERIALIZATION_FILE_NAME);
    if (file.exists() && !file.delete()) {
      return false;
    }
    if (this.map == null) {
      return false;
    }
    FileOutputStream outputStream=new FileOutputStream(file);
    ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(this.map);
    objectOutputStream.close();
    outputStream.close();
    return true;
  }
 catch (  IOException e) {
    Logger.exception(e);
    return false;
  }
}
 

Example 55

From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.

Source file: ListAccountsActivity.java

  17 
vote

private void writeAccounts(){
  FileOutputStream fos;
  ObjectOutputStream out=null;
  try {
    fos=openFileOutput(FILENAME,Context.MODE_PRIVATE);
    out=new ObjectOutputStream(fos);
    out.writeObject(accounts);
    out.flush();
    out.close();
  }
 catch (  FileNotFoundException e) {
    showAlert("Error","Could not save accounts.");
    e.printStackTrace();
  }
catch (  IOException e) {
    showAlert("Error","Could not save accounts.");
    e.printStackTrace();
  }
}
 

Example 56

From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.

Source file: DataStorage.java

  17 
vote

public static boolean objectToFile(Context context,String fileName,Object serializableObject){
  boolean bRet=true;
  if (!(serializableObject instanceof java.io.Serializable)) {
    Log.e(TAG,"The object is not serializable: " + fileName);
    return false;
  }
  try {
    FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);
    ObjectOutputStream os=new ObjectOutputStream(fos);
    os.writeObject(serializableObject);
    os.close();
  }
 catch (  Exception e) {
    Log.e(TAG,"An error occured while writing " + fileName + " "+ e.getMessage());
    bRet=false;
  }
  return bRet;
}
 

Example 57

From project android_packages_apps_phone, under directory /src/com/android/phone/.

Source file: CallFeaturesSetting.java

  17 
vote

private void saveBLFile(){
  ObjectOutputStream oos=null;
  try {
    oos=new ObjectOutputStream(PhoneApp.getInstance().openFileOutput(BLFILE,Context.MODE_PRIVATE));
    oos.writeObject(new Integer(BLFILE_VER));
    oos.writeObject(setBlackList);
  }
 catch (  Exception e) {
    log(e.toString());
  }
 finally {
    if (oos != null)     try {
      oos.close();
    }
 catch (    Exception e) {
    }
  }
}
 

Example 58

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/util/.

Source file: SerializationUtil.java

  17 
vote

public static byte[] serializeToByteArray(Serializable o){
  try {
    ByteArrayOutputStream bytes=new ByteArrayOutputStream();
    ObjectOutputStream out=new ObjectOutputStream(bytes);
    try {
      out.writeObject(o);
    }
  finally {
      out.close();
    }
    return bytes.toByteArray();
  }
 catch (  IOException e) {
    throw new RuntimeException("Can't serialize object: " + o,e);
  }
}
 

Example 59

From project Armageddon, under directory /src/main/java/com/iminurnetz/bukkit/plugin/armageddon/.

Source file: ArmageddonPlugin.java

  17 
vote

private void saveCannonsFile(){
  File cache=getCannonsFile();
  File dataDir=cache.getParentFile();
  if (!dataDir.exists()) {
    dataDir.mkdirs();
  }
  try {
    FileOutputStream fos=new FileOutputStream(cache);
    ObjectOutputStream out=new ObjectOutputStream(fos);
    out.writeInt(CANNON_FILE_VERSION);
    out.writeObject(cannons);
    out.writeObject(playerSettings);
    out.close();
    fos.close();
  }
 catch (  Exception e) {
    log(Level.SEVERE,"Cannot cache cannons and settings",e);
  }
}
 

Example 60

From project BART, under directory /src/pro/dbro/bart/.

Source file: LocalPersistence.java

  17 
vote

/** 
 * @param context
 * @param object
 * @param filename
 */
public static void writeObjectToFile(Context context,Object object,String filename){
  ObjectOutputStream objectOut=null;
  try {
    FileOutputStream fileOut=context.openFileOutput(filename,Activity.MODE_PRIVATE);
    objectOut=new ObjectOutputStream(fileOut);
    objectOut.writeObject(object);
    fileOut.getFD().sync();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    if (objectOut != null) {
      try {
        objectOut.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 61

From project baseunits, under directory /src/test/java/jp/xet/baseunits/tests/.

Source file: SerializationTester.java

  17 
vote

/** 
 * ????€?????????????????????
 * @param serializable ????€????????????????
 * @throws AssertionError ????€??????????????
 */
public static void assertCanBeSerialized(Object serializable){
  if (Serializable.class.isInstance(serializable) == false) {
    fail("Object doesn't implement java.io.Serializable interface: " + serializable.getClass());
  }
  ObjectOutputStream out=null;
  ObjectInputStream in=null;
  ByteArrayOutputStream byteArrayOut=new ByteArrayOutputStream();
  ByteArrayInputStream byteArrayIn=null;
  try {
    out=new ObjectOutputStream(byteArrayOut);
    out.writeObject(serializable);
    byteArrayIn=new ByteArrayInputStream(byteArrayOut.toByteArray());
    in=new ObjectInputStream(byteArrayIn);
    Object deserialized=in.readObject();
    if (serializable.equals(deserialized) == false) {
      fail("Reconstituted object is expected to be equal to serialized");
    }
  }
 catch (  IOException e) {
    fail(e.getMessage());
  }
catch (  ClassNotFoundException e) {
    fail(e.getMessage());
  }
 finally {
    IOUtils.closeQuietly(out);
    IOUtils.closeQuietly(in);
  }
}
 

Example 62

From project BeeQueue, under directory /src/org/beequeue/hash/.

Source file: FileCollection.java

  17 
vote

private byte[] ensureEntriesData(){
  if (entriesDataBuffer == null) {
    ByteArrayOutputStream out=null;
    ObjectOutputStream oout=null;
    try {
      out=new ByteArrayOutputStream();
      oout=new ObjectOutputStream(out);
      oout.writeInt(entries.length);
      for (int i=0; i < entries.length; i++) {
        oout.writeUTF(entries[i].toString());
      }
      oout.flush();
      entriesDataBuffer=out.toByteArray();
    }
 catch (    IOException e) {
      throw new BeeException(e);
    }
 finally {
      try {
        out.close();
      }
 catch (      Exception ignore) {
      }
      try {
        oout.close();
      }
 catch (      Exception ignore) {
      }
    }
  }
  return entriesDataBuffer;
}
 

Example 63

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: SDFileManager.java

  17 
vote

public boolean WriteToFile(String fileName,String textToWrite) throws IOException {
  File sdCard=Environment.getExternalStorageDirectory();
  File dir=new File(sdCard.getAbsolutePath() + "/.beintoo");
  dir.mkdirs();
  File file=new File(dir,fileName);
  ObjectOutputStream oos=null;
  boolean success=false;
  try {
    OutputStream os=new FileOutputStream(file);
    oos=new ObjectOutputStream(os);
    oos.writeObject(textToWrite);
    success=true;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    try {
      if (null != oos)       oos.close();
    }
 catch (    IOException ex) {
    }
  }
  return success;
}
 

Example 64

From project BHT-FPA, under directory /patterns-codebeispiele/de.bht.fpa.examples.proxypattern/de.bht.fpa.examples.proxypattern.coffemachine.proxy/src/de/bht/fpa/proxypattern/coffemachine/proxy/.

Source file: CoffeMachineRemoteServiceDecorator.java

  17 
vote

private void handleClient(final Socket client){
  System.out.println(getClass().getName() + " got connection: " + client.getInetAddress());
  new Thread(){
    @Override public void run(){
      try {
        ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
        ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
        while (client.isConnected()) {
          handleCommand(ois,oos);
        }
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
.start();
}
 

Example 65

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/rest/.

Source file: BioportalRestService.java

  17 
vote

/** 
 * Write cache.
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeCache(){
  log.info("Writing cache");
synchronized (cache) {
    if (cache instanceof Serializable) {
      FileOutputStream fos=null;
      ObjectOutputStream oos=null;
      try {
        File file=getCacheFile();
        fos=new FileOutputStream(file);
        oos=new ObjectOutputStream(fos);
        oos.writeObject((Serializable)Collections.synchronizedMap(cache));
      }
 catch (      Exception e) {
        throw new RuntimeException(e);
      }
 finally {
        try {
          if (fos != null) {
            fos.close();
          }
          if (oos != null) {
            oos.close();
          }
        }
 catch (        IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
 else {
      throw new RuntimeException(cache.getClass().getName() + " is not Serializable!");
    }
  }
}
 

Example 66

From project Buildr, under directory /src/me/simplex/buildr/runnable/.

Source file: Buildr_Runnable_InventorySaver.java

  17 
vote

@Override public void run(){
  Buildr_Container_ItemStackSave[] FileContainer=new Buildr_Container_ItemStackSave[inventory.length];
  for (int i=0; i < inventory.length; i++) {
    if (inventory[i] != null) {
      byte savedata=0;
      if (inventory[i].getData() != null) {
        savedata=inventory[i].getData().getData();
      }
      FileContainer[i]=new Buildr_Container_ItemStackSave(inventory[i].getTypeId(),inventory[i].getAmount(),inventory[i].getDurability(),savedata);
    }
  }
  try {
    ObjectOutputStream objctOutStrm=new ObjectOutputStream(new FileOutputStream(path));
    objctOutStrm.writeObject(FileContainer);
    objctOutStrm.flush();
    objctOutStrm.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
    System.out.println("ERROR#############################################################");
  }
}
 

Example 67

From project BusFollower, under directory /src/net/argilo/busfollower/.

Source file: RecentQueryList.java

  17 
vote

public static synchronized void addOrUpdateRecent(Context context,Stop stop,Route route){
  ArrayList<RecentQuery> recents=loadRecents(context);
  RecentQuery query=new RecentQuery(stop,route);
  boolean foundQuery=false;
  for (  RecentQuery recent : recents) {
    if (recent.equals(query)) {
      foundQuery=true;
      recent.queriedAgain();
      break;
    }
  }
  if (!foundQuery) {
    recents.add(query);
    if (recents.size() > MAX_RECENT_QUERIES) {
      Collections.sort(recents,new QueryDateComparator());
      recents.remove(0);
    }
    Collections.sort(recents,new QueryStopRouteComparator());
  }
  try {
    ObjectOutputStream out=new ObjectOutputStream(context.openFileOutput(FILENAME,Context.MODE_PRIVATE));
    out.writeObject(recents);
    out.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 68

From project Cloud9, under directory /src/dist/edu/umd/hooka/.

Source file: CreateMetadata.java

  17 
vote

public static void GenerateMetadata(Path bitextPath,Path resultPath) throws IOException {
  System.out.println(bitextPath.toString());
  JobConf conf=new JobConf(CreateMetadata.class);
  FileSystem fileSys=FileSystem.get(conf);
  SequenceFile.Reader[] x=SequenceFileOutputFormat.getReaders(conf,new Path("/shared/bitexts/ar-en.ldc.10k/ar-en.10k.bitext"));
  WritableComparable key=new IntWritable();
  PhrasePair value=new PhrasePair();
  int sc=0;
  int ec=0;
  int fc=0;
  try {
    for (    SequenceFile.Reader r : x)     while (r.next(key,value)) {
      sc=sc + 1;
      for (      int word : value.getE().getWords())       if (word > ec)       ec=word;
      for (      int word : value.getF().getWords())       if (word > fc)       fc=word;
    }
  }
 catch (  IOException e) {
    throw new RuntimeException("IO exception: " + e.getMessage());
  }
  Metadata theMetadata=new Metadata(sc,ec,fc);
  ObjectOutputStream mdstream=new ObjectOutputStream(new BufferedOutputStream(FileSystem.get(conf).create(resultPath)));
  mdstream.writeObject(theMetadata);
  mdstream.close();
}
 

Example 69

From project com.cedarsoft.serialization, under directory /test/performance/src/test/java/com/cedarsoft/serialization/test/performance/.

Source file: XmlParserPerformance.java

  17 
vote

public void benchSerialization() throws IOException {
  FileType type=new FileType("Canon Raw",new Extension(".","cr2",true),false);
  ByteArrayOutputStream bao=new ByteArrayOutputStream();
  ObjectOutputStream out=new ObjectOutputStream(bao);
  out.writeObject(type);
  out.close();
  final byte[] serialized=bao.toByteArray();
  runBenchmark(new Runnable(){
    @Override public void run(){
      try {
        for (int i=0; i < MEDIUM; i++) {
          assertNotNull(new ObjectInputStream(new ByteArrayInputStream(serialized)).readObject());
        }
      }
 catch (      Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
,4);
}
 

Example 70

From project cometd, under directory /cometd-java/cometd-java-common/src/test/java/org/cometd/common/.

Source file: HashMapMessageTest.java

  17 
vote

@Test public void testSerialization() throws Exception {
  HashMapMessage message=new HashMapMessage();
  message.setChannel("/channel");
  message.setClientId("clientId");
  message.setId("id");
  message.setSuccessful(true);
  message.getDataAsMap(true).put("data1","dataValue1");
  message.getExt(true).put("ext1","extValue1");
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  ObjectOutputStream oos=new ObjectOutputStream(baos);
  oos.writeObject(message);
  oos.close();
  ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
  HashMapMessage deserialized=(HashMapMessage)ois.readObject();
  assertEquals(message,deserialized);
}
 

Example 71

From project commons-fileupload, under directory /src/test/org/apache/commons/fileupload/.

Source file: DiskFileItemSerializeTest.java

  17 
vote

/** 
 * Do serialization and deserialization.
 */
private Object serializeDeserialize(Object target){
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    ObjectOutputStream oos=new ObjectOutputStream(baos);
    oos.writeObject(target);
    oos.flush();
    oos.close();
  }
 catch (  Exception e) {
    fail("Exception during serialization: " + e);
  }
  Object result=null;
  try {
    ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois=new ObjectInputStream(bais);
    result=ois.readObject();
    bais.close();
  }
 catch (  Exception e) {
    fail("Exception during deserialization: " + e);
  }
  return result;
}
 

Example 72

From project core_4, under directory /impl/src/main/java/org/richfaces/util/.

Source file: Util.java

  17 
vote

public static String encodeObjectData(Object data){
  if (data != null) {
    try {
      ByteArrayOutputStream dataStream=new ByteArrayOutputStream(1024);
      ObjectOutputStream objStream=new ObjectOutputStream(dataStream);
      objStream.writeObject(data);
      objStream.flush();
      objStream.close();
      dataStream.close();
      return encodeBytesData(dataStream.toByteArray());
    }
 catch (    Exception e) {
      RESOURCE_LOGGER.error(Messages.getMessage(Messages.QUERY_STRING_BUILDING_ERROR),e);
    }
  }
  return null;
}
 

Example 73

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/database/.

Source file: SerializationUtils.java

  16 
vote

/** 
 * Utility routine to convert a Serializable object to a byte array.
 * @param o		Object to convert
 * @return		Resulting byte array. NULL on failure.
 */
public static byte[] serializeObject(Serializable o){
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  ObjectOutput out;
  try {
    out=new ObjectOutputStream(bos);
    out.writeObject(o);
    out.close();
  }
 catch (  Exception e) {
    out=null;
  }
  byte[] buf;
  if (out != null) {
    buf=bos.toByteArray();
  }
 else {
    buf=null;
  }
  return buf;
}
 

Example 74

From project Clotho-Core, under directory /ClothoProject/ClothoCore/src/org/clothocore/api/data/.

Source file: ObjBase.java

  16 
vote

public void serialize(){
  File serials=new File("serials");
  if (!serials.exists()) {
    serials.mkdir();
  }
  boolean tempchanged=_datum._isChanged;
  boolean tempindb=_inDatabase;
  _datum._isChanged=true;
  _inDatabase=false;
  try {
    String filename="serials\\" + this.getUUID() + "."+ this.getType();
    ObjectOutput out=new ObjectOutputStream(new FileOutputStream(filename));
    out.writeObject(this);
    out.close();
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    out=new ObjectOutputStream(bos);
    out.writeObject(this);
    out.close();
    byte[] buf=bos.toByteArray();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  _datum._isChanged=tempchanged;
}
 

Example 75

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/net/poolable/copy/.

Source file: CursorableLinkedList.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  out.writeInt(_size);
  Listable cur=_head.next();
  while (cur != null) {
    out.writeObject(cur.value());
    cur=cur.next();
  }
}
 

Example 76

From project android-client_1, under directory /src/org/apache/harmony/javax/security/auth/.

Source file: Subject.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  if (permission == _PRIVATE_CREDENTIALS) {
    for (Iterator<SST> it=iterator(); it.hasNext(); ) {
      it.next();
    }
    setType=SET_PrivCred;
  }
 else   if (permission == _PRINCIPALS) {
    setType=SET_Principal;
  }
 else {
    setType=SET_PubCred;
  }
  out.defaultWriteObject();
}
 

Example 77

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: EnumBiMap.java

  15 
vote

/** 
 * @serialData the key class, value class, number of entries, first key, firstvalue, second key, second value, and so on.
 */
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  stream.writeObject(keyType);
  stream.writeObject(valueType);
  Serialization.writeMap(this,stream);
}
 

Example 78

From project AsmackService, under directory /src/org/apache/harmony/javax/security/auth/.

Source file: Subject.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  if (permission == _PRIVATE_CREDENTIALS) {
    for (Iterator<SST> it=iterator(); it.hasNext(); ) {
      it.next();
    }
    setType=SET_PrivCred;
  }
 else   if (permission == _PRINCIPALS) {
    setType=SET_Principal;
  }
 else {
    setType=SET_PubCred;
  }
  out.defaultWriteObject();
}
 

Example 79

From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/domain/.

Source file: Folder.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  if (this.childComparator instanceof Serializable) {
    out.writeObject(this.childComparator);
  }
 else {
    out.writeObject(this.childComparator.getClass());
  }
}
 

Example 80

From project capedwarf-blue, under directory /bytecode/src/main/java/org/jboss/capedwarf/bytecode/.

Source file: CursorTransformer.java

  15 
vote

protected void transform(CtClass clazz) throws Exception {
  if (isAlreadyModified(clazz))   return;
  final ClassPool pool=clazz.getClassPool();
  CtClass intClass=pool.get(int.class.getName());
  CtField indexField=CtField.make("private java.util.concurrent.atomic.AtomicInteger index;",clazz);
  clazz.addField(indexField);
  CtConstructor ctor=new CtConstructor(new CtClass[]{pool.get(AtomicInteger.class.getName())},clazz);
  ctor.setBody("{this.index = $1;}");
  clazz.addConstructor(ctor);
  CtMethod getIndex=new CtMethod(intClass,"getIndex",new CtClass[]{},clazz);
  getIndex.setModifiers(Modifier.PUBLIC);
  getIndex.setBody("{return index.get();}");
  clazz.addMethod(getIndex);
  CtConstructor cloneCtor=clazz.getDeclaredConstructor(new CtClass[]{clazz});
  cloneCtor.setBody("this($1.index);");
  CtMethod writeObject=clazz.getDeclaredMethod("writeObject",new CtClass[]{pool.get(ObjectOutputStream.class.getName())});
  writeObject.setBody("$1.writeInt(getIndex());");
  CtMethod readObject=clazz.getDeclaredMethod("readObject",new CtClass[]{pool.get(ObjectInputStream.class.getName())});
  readObject.setBody("index = new java.util.concurrent.atomic.AtomicInteger($1.readInt());   ");
  CtMethod advance=clazz.getDeclaredMethod("advance",new CtClass[]{intClass,pool.get(PreparedQuery.class.getName())});
  advance.setBody("index.addAndGet($1);");
  CtMethod reverse=clazz.getDeclaredMethod("reverse");
  reverse.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger((-1) * getIndex()));");
  CtMethod toWebSafeString=clazz.getDeclaredMethod("toWebSafeString");
  toWebSafeString.setBody("return index.toString();");
  CtMethod fromWebSafeString=clazz.getDeclaredMethod("fromWebSafeString",new CtClass[]{pool.get(String.class.getName())});
  fromWebSafeString.setBody("return new com.google.appengine.api.datastore.Cursor(new java.util.concurrent.atomic.AtomicInteger($1 != null && $1.length() > 0 ? Integer.parseInt($1) : 0));");
  CtMethod fromByteArray=clazz.getDeclaredMethod("fromByteArray",new CtClass[]{pool.get(byte[].class.getName())});
  fromByteArray.setBody("return fromWebSafeString(new String($1));");
  CtMethod equals=clazz.getDeclaredMethod("equals",new CtClass[]{pool.get(Object.class.getName())});
  equals.setBody("return ($1 instanceof com.google.appengine.api.datastore.Cursor) && ((com.google.appengine.api.datastore.Cursor) $1).getIndex() == getIndex();");
  CtMethod hashCode=clazz.getDeclaredMethod("hashCode");
  hashCode.setBody("return getIndex();");
  CtMethod toString=clazz.getDeclaredMethod("toString");
  toString.setBody("return \"Cursor:\" + index;");
}
 

Example 81

From project CircDesigNA, under directory /src/org/apache/commons/math/linear/.

Source file: MatrixUtils.java

  15 
vote

/** 
 * Serialize a  {@link RealVector}. <p> This method is intended to be called from within a private <code>writeObject</code> method (after a call to <code>oos.defaultWriteObject()</code>) in a class that has a {@link RealVector} field, which should be declared <code>transient</code>.This way, the default handling does not serialize the vector (the  {@link RealVector} interface is not serializable by default) but this method doesserialize it specifically. </p> <p> The following example shows how a simple class with a name and a real vector should be written: <pre><code> public class NamedVector implements Serializable { private final String name; private final transient RealVector coefficients; // omitted constructors, getters ... private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject();  // takes care of name field MatrixUtils.serializeRealVector(coefficients, oos); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject();  // takes care of name field MatrixUtils.deserializeRealVector(this, "coefficients", ois); } } </code></pre> </p>
 * @param vector real vector to serialize
 * @param oos stream where the real vector should be written
 * @exception IOException if object cannot be written to stream
 * @see #deserializeRealVector(Object,String,ObjectInputStream)
 */
public static void serializeRealVector(final RealVector vector,final ObjectOutputStream oos) throws IOException {
  final int n=vector.getDimension();
  oos.writeInt(n);
  for (int i=0; i < n; ++i) {
    oos.writeDouble(vector.getEntry(i));
  }
}
 

Example 82

From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.

Source file: CursorableLinkedList.java

  15 
vote

private void writeObject(ObjectOutputStream out) throws IOException {
  out.defaultWriteObject();
  out.writeInt(_size);
  Listable cur=_head.next();
  while (cur != null) {
    out.writeObject(cur.value());
    cur=cur.next();
  }
}