Example usage for java.io ObjectOutputStream writeObject

List of usage examples for java.io ObjectOutputStream writeObject

Introduction

In this page you can find the example usage for java.io ObjectOutputStream writeObject.

Prototype

public final void writeObject(Object obj) throws IOException 

Source Link

Document

Write the specified object to the ObjectOutputStream.

Usage

From source file:com.glaf.core.security.RSAUtils.java

/**
 * RSA??//from   w w w  .j a v a2s . c  om
 * 
 * @param keyPair
 *            ??
 */
private static void saveKeyPair(KeyPair keyPair) {
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try {
        fos = FileUtils.openOutputStream(rsaPairFile);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(keyPair);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.closeQuietly(oos);
        IOUtils.closeQuietly(fos);
    }
    FileInputStream fin = null;
    try {
        fin = FileUtils.openInputStream(rsaPairFile);
        SysKey sysKey = new SysKey();
        sysKey.setId("RSAKey");
        sysKey.setCreateBy("system");
        sysKey.setName("RSAKey");
        sysKey.setType("RSA");
        sysKey.setTitle("RSA?");
        sysKey.setPath(rsaPairFile.getName());
        sysKey.setData(IOUtils.toByteArray(fin));
        SysKeyService sysKeyService = ContextFactory.getBean("sysKeyService");
        sysKeyService.save(sysKey);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.TaskUtils.java

/**
 * Saves a serializable object of type <T> to disk. Output file may be uncompressed, gzipped or
 * bz2-compressed. Compressed files must have a .gz or .bz2 suffix.
 *
 * @param serializedFile/*from ww w. jav a  2s.  c  om*/
 *            model output file
 * @param serializableObject
 *            the object to serialize
 * @throws IOException
 */
public static void serialize(File serializedFile, Object serializableObject) throws IOException {

    FileOutputStream fos = new FileOutputStream(serializedFile);
    BufferedOutputStream bufStr = new BufferedOutputStream(fos);

    OutputStream underlyingStream = null;
    if (serializedFile.getName().endsWith(".gz")) {
        underlyingStream = new GZIPOutputStream(bufStr);
    } else if (serializedFile.getName().endsWith(".bz2")) {
        underlyingStream = new CBZip2OutputStream(bufStr);
        // manually add bz2 prefix to make it compatible to normal bz2 tools
        // prefix has to be skipped when reading the stream with CBZip2
        fos.write("BZ".getBytes("UTF-8"));
    } else {
        underlyingStream = bufStr;
    }
    ObjectOutputStream serializer = new ObjectOutputStream(underlyingStream);
    try {
        serializer.writeObject(serializableObject);

    } finally {
        serializer.flush();
        serializer.close();
    }
}

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * Serializer used for storing data into zookeeper. We use the default
 * java serializer (since the amount of data to be serialized is usually
 * very small).//from  ww w.j  a  v a  2s  .c om
 * NOTE: THIS IS DIFFERENT FROM THE SERIALIZER USED DURING COMMUNICATION
 * BETWEEN DIFFERENT FLAKES. THAT ONE IS PLUGABBLE, THIS IS NOT.
 *
 * @param obj Object to be serialized
 * @return serialized byte array.
 */
public static byte[] serialize(final Object obj) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.close();
        return bos.toByteArray();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ??/*from  ww  w  .  j ava 2  s . c  o  m*/
 * 
 * @param obj
 * @return
 */
public final static byte[] objToBytes(Object obj) {
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        return bao.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ???//  w ww . j  a  v  a2 s .c  o  m
 * 
 * @param obj
 * @return
 */
public final static int sizeOf(Object obj) {
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        return bao.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:net.sf.taverna.t2.activities.wsdlsir.views.WSDLActivityConfigurationView.java

/**
 * Write the object to a Base64 string//from   w ww.j av  a 2  s. c  o  m
 * TODO: mover a algun sitio comun?
 * @param o
 * @return
 * @throws IOException
 */
private static String serializetoString(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();
    return new String(Base64.encode(baos.toByteArray()));
}

From source file:edu.iu.daal_naive.NaiveDaalCollectiveMapper.java

private static ByteArray serializePartialResult(TrainingPartialResult partialResult) throws IOException {
    /* Create an output stream to serialize the numeric table */
    ByteArrayOutputStream outputByteStream = new ByteArrayOutputStream();
    ObjectOutputStream outputStream = new ObjectOutputStream(outputByteStream);

    /* Serialize the numeric table into the output stream */
    partialResult.pack();/*from ww  w  .  ja  v  a2s. c o m*/
    outputStream.writeObject(partialResult);

    /* Store the serialized data in an array */
    byte[] serializedPartialResult = outputByteStream.toByteArray();

    ByteArray partialResultHarp = new ByteArray(serializedPartialResult, 0, serializedPartialResult.length);
    return partialResultHarp;
}

From source file:com.google.android.gcm.demo.server.Datastore.java

public static JSONArray getAllAlerts(int offset, int limit) {
    Cache cache;//from   www . jav a2 s  .c  om
    String cacheKey = "offset_" + offset + "_limit_" + limit;
    byte[] cacheValue = null;

    JSONArray alerts = null;
    try {
        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
        cache = cacheFactory.createCache(Collections.emptyMap());
        cacheValue = (byte[]) cache.get(cacheKey);
        if (cacheValue == null) {
            alerts = getAllAlertsFromDataStore(offset, limit);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(baos);
            } catch (Exception e) {
                e.printStackTrace();
            }
            oos.writeObject(alerts);
            byte cval[] = baos.toByteArray();
            if (cval.length < 1024 * 1024) {
                Logger.getLogger(Datastore.class.getName()).log(Level.SEVERE,
                        "Alerts Size is in limits:" + cval.length);
                cache.put(cacheKey, cval);
            } else {
                Logger.getLogger(Datastore.class.getName()).log(Level.SEVERE,
                        "Length Size has exceeded:" + cval.length);
            }

        } else {
            ByteArrayInputStream bais = new ByteArrayInputStream(cacheValue);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
            } catch (Exception e) {
                e.printStackTrace();
            }
            alerts = (JSONArray) ois.readObject();
            Logger.getLogger(Datastore.class.getName()).log(Level.WARNING, "From the Cache");
        }
    } catch (CacheException e) {

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return alerts;
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Returns a <code>ByteBuffer</code> containing the byte representation
 * of the serializable object <code>obj</code>.
 * //from w w  w .  j  a va 2s . c o  m
 * @param obj the <code>Object</code> to convert to its byte representation
 * @param buf an existing buffer to use for storage or <code>null</code> to create new buffer.
 *        If <code>buf</code> is not large enough it will be expanded using {@link #growBuffer(ByteBuffer, int)}
 * @return <code>ByteBuffer</code> containing the byte representation
 * of <code>obj</code>.
 * 
 * @throws IOException if <code>obj</code> is not serializable or error occurs while writing the bytes
 */
public static ByteBuffer getObjectBytes(Object obj, ByteBuffer buf) throws IOException {
    if (buf == null)
        buf = ByteBuffer.allocate(READ_BUFFER_SIZE);

    // note the input position
    int startPos = buf.position();
    ByteBufferChannel channel = new ByteBufferChannel(buf);
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(Channels.newOutputStream(channel));
        out.writeObject(obj);
        out.flush();
    } finally {
        MiscUtils.closeStream(out);
    }

    ByteBuffer returnBuf = channel.getByteBuffer();
    returnBuf.flip();
    // reset starting position to be that of input buffer
    returnBuf.position(startPos);
    return returnBuf;
}

From source file:org.pgptool.gui.config.impl.ConfigRepositoryImpl.java

public static void writeObject(Object o, String destinationFile) {
    ObjectOutputStream oos = null;
    try {//from  w  w w  . j  av a2 s  .  c o m
        log.trace(String.format("Persisting %s to %s", o, destinationFile));

        File file = new File(destinationFile);
        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
            throw new RuntimeException("Failed to create all parent directories");
        }

        FileOutputStream fout = new FileOutputStream(file);
        oos = new ObjectOutputStream(fout);
        oos.writeObject(o);
        oos.flush();
        oos.close();
        fout.close();
    } catch (Throwable t) {
        throw new RuntimeException("Failed to write config: " + destinationFile, t);
    } finally {
        safeClose(oos);
    }
}