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:de.alpharogroup.io.SerializedObjectExtensions.java

/**
 * Copys the given Object and returns the copy from the object or null if the object can't be
 * serialized.//from w  w w. j  av a  2s . c  om
 *
 * @param <T>
 *            the generic type of the given object
 * @param orig
 *            The object to copy.
 * @return Returns a copy from the original object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException
 *             is thrown when a class is not found in the classloader or no definition for the
 *             class with the specified name could be found.
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copySerializedObject(final T orig)
        throws IOException, ClassNotFoundException {
    T object = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(orig);
        objectOutputStream.flush();
        objectOutputStream.close();
        final ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final ObjectInputStream ois = new ObjectInputStream(bis);
        object = (T) ois.readObject();
    } finally {
        StreamExtensions.closeOutputStream(byteArrayOutputStream);
        StreamExtensions.closeOutputStream(objectOutputStream);
    }
    return object;
}

From source file:de.alpharogroup.io.SerializedObjectUtils.java

/**
 * Copys the given Object and returns the copy from the object or null if the object can't be
 * serialized.//from   w  w w  .j a  v a  2 s .c o m
 *
 * @param <T>
 *            the generic type of the given object
 * @param orig
 *            The object to copy.
 * @return Returns a copy from the original object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException
 *             is thrown when a class is not found in the classloader or no definition for the
 *             class with the specified name could be found.
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copySerializedObject(final T orig)
        throws IOException, ClassNotFoundException {
    T object = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(orig);
        objectOutputStream.flush();
        objectOutputStream.close();
        final ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final ObjectInputStream ois = new ObjectInputStream(bis);
        object = (T) ois.readObject();
    } finally {
        StreamUtils.closeOutputStream(byteArrayOutputStream);
        StreamUtils.closeOutputStream(objectOutputStream);
    }
    return object;
}

From source file:org.activiti.designer.eclipse.navigator.cloudrepo.ActivitiCloudEditorUtil.java

public static CloseableHttpClient getAuthenticatedClient() {

    // Get settings from preferences
    String url = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_URL);
    String userName = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_USERNAME);
    String password = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_PASSWORD);
    String cookieString = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE);

    Cookie cookie = null;/*  w  w w  .  j  a v a  2  s  .  c  o m*/
    if (StringUtils.isNotEmpty(cookieString)) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                hexStringToByteArray(cookieString));
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = (BasicClientCookie) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Build session
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    if (cookie == null) {
        try {
            HttpUriRequest login = RequestBuilder.post().setUri(new URI(url + "/rest/app/authentication"))
                    .addParameter("j_username", userName).addParameter("j_password", password)
                    .addParameter("_spring_security_remember_me", "true").build();

            CloseableHttpResponse response = httpClient.execute(login);

            try {
                EntityUtils.consume(response.getEntity());
                List<Cookie> cookies = cookieStore.getCookies();
                if (cookies.isEmpty()) {
                    // nothing to do
                } else {
                    Cookie reponseCookie = cookies.get(0);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ObjectOutputStream outputStream = new ObjectOutputStream(os);
                    outputStream.writeObject(reponseCookie);
                    PreferencesUtil.getActivitiDesignerPreferenceStore().setValue(
                            Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE.getPreferenceId(),
                            byteArrayToHexString(os.toByteArray()));
                    InstanceScope.INSTANCE.getNode(ActivitiPlugin.PLUGIN_ID).flush();
                }

            } finally {
                response.close();
            }

        } catch (Exception e) {
            Logger.logError("Error authenticating " + userName, e);
        }

    } else {
        // setting cookie from cache
        cookieStore.addCookie(cookie);
    }

    return httpClient;
}

From source file:io.bitsquare.common.util.Utilities.java

public static Object copy(Serializable orig) throws IOException, ClassNotFoundException {
    try {//from   w w  w  .j  a va2 s . c  om
        // Write the object out to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(orig);
        out.flush();
        out.close();

        // Make an input stream from the byte array and read
        // a copy of the object back in.
        ObjectInputStream in = new LookAheadObjectInputStream(new ByteArrayInputStream(bos.toByteArray()),
                true);
        Object obj = in.readObject();
        return obj;
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

/**
 * Saves the current game state to disk/* www. j  av a2 s . c om*/
 */
private static void saveGalaxy() {
    File galaxyFile = new File(galaxyFileName);
    ObjectOutputStream oos;
    try {
        long time = System.currentTimeMillis();
        oos = new ObjectOutputStream(new FileOutputStream(galaxyFile));
        oos.writeObject(galaxy);
        time = System.currentTimeMillis() - time;
        LOG.log(Level.INFO, "Galaxy written to file in {0} ms", time);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, "Unable to write galaxy file to disk:");
        LOG.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:com.breadwallet.tools.manager.SharedPreferencesManager.java

public static void putExchangeRates(Activity activity, Set<CurrencyEntity> rates) {
    SharedPreferences prefs = activity.getSharedPreferences(BRConstants.PREFS_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.remove(BRConstants.EXCHANGE_RATES);
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    ObjectOutputStream objectOutput;
    try {/*from   ww w . j a v a2s  .c om*/
        objectOutput = new ObjectOutputStream(arrayOutputStream);
        objectOutput.writeObject(rates);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.NO_WRAP);
        b64.write(data);
        b64.close();
        out.close();
        editor.putString(BRConstants.EXCHANGE_RATES, new String(out.toByteArray()));

        editor.apply();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:Main.java

/**
 * Serialises a <code>Stroke</code> object.  This code handles the
 * <code>BasicStroke</code> class which is the only <code>Stroke</code>
 * implementation provided by the JDK (and isn't directly
 * <code>Serializable</code>).
 *
 * @param stroke  the stroke object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 *//*from  ww w.  j a  v  a2  s  .c  o m*/
public static void writeStroke(final Stroke stroke, final ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (stroke != null) {
        stream.writeBoolean(false);
        if (stroke instanceof BasicStroke) {
            final BasicStroke s = (BasicStroke) stroke;
            stream.writeObject(BasicStroke.class);
            stream.writeFloat(s.getLineWidth());
            stream.writeInt(s.getEndCap());
            stream.writeInt(s.getLineJoin());
            stream.writeFloat(s.getMiterLimit());
            stream.writeObject(s.getDashArray());
            stream.writeFloat(s.getDashPhase());
        } else {
            stream.writeObject(stroke.getClass());
            stream.writeObject(stroke);
        }
    } else {
        stream.writeBoolean(true);
    }
}

From source file:org.glom.web.server.Utils.java

static public Object deepCopy(final Object oldObj) {
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;

    try {//from www. j  a  va2s  .  c om
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        // serialize and pass the object
        oos.writeObject(oldObj);
        oos.flush();
        final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
        ois = new ObjectInputStream(bin);

        // return the new object
        return ois.readObject();
    } catch (final Exception e) {
        System.out.println("Exception in deepCopy:" + e);
        return null;
    } finally {
        try {
            oos.close();
            ois.close();
        } catch (final IOException e) {
            System.out.println("Exception in deepCopy during finally: " + e);
            return null;
        }
    }
}

From source file:com.kellerkindt.scs.utilities.Utilities.java

/**
 * Serializes the MetaData of an ItemStack
 * and marshals it then in a String//  w w  w .  j  a va  2s .co m
 * @param itemMeta The MetaData so save
 * @return The marshaled ItemStack as String
 * @throws IOException On any internal Exception
 */
public static String toHexString(ItemMeta itemMeta) throws IOException {

    // create streams
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);

    // write map
    oos.writeObject(itemMeta.serialize());
    oos.flush();

    // toHexString
    return new HexBinaryAdapter().marshal(baos.toByteArray());
}

From source file:edu.iu.daal_qr.QRDaalCollectiveMapper.java

private static ByteArray serializePartialResult(DataCollection 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();//ww w.jav a  2s .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;
}