Example usage for java.io ObjectOutputStream ObjectOutputStream

List of usage examples for java.io ObjectOutputStream ObjectOutputStream

Introduction

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

Prototype

public ObjectOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates an ObjectOutputStream that writes to the specified OutputStream.

Usage

From source file:edu.mit.ll.graphulo.util.SerializationUtil.java

/**
 * <p>Serializes an {@code Object} to the specified stream.</p>
 * <p/>/*from  www.  jav a  2  s  .c  o m*/
 * <p>The stream will be closed once the object is written.
 * This avoids the need for a finally clause, and maybe also exception
 * handling, in the application code.</p>
 * <p/>
 * <p>The stream passed in is not buffered internally within this method.
 * This is the responsibility of your application if desired.</p>
 *
 * @param obj          the object to serialize to bytes, may be null
 * @param outputStream the stream to write to, must not be null
 * @throws IllegalArgumentException if {@code outputStream} is {@code null}
 */
public static void serialize(Serializable obj, OutputStream outputStream) {
    Preconditions.checkNotNull(outputStream);
    try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
        out.writeObject(obj);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

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.ja v  a  2 s.co  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:com.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }//from   w w  w .  j  a va2 s  .c o  m

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:com.clustercontrol.plugin.impl.AsyncTask.java

/**
 * SerializableBinary???/*from w  w w . j ava2 s  . co  m*/
 * @param obj Serializable
 * @return ??Binary
 * @throws IOException
 */
public static byte[] encodeBinary(Serializable obj) throws IOException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    byte[] bytes = null;

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        bytes = baos.toByteArray();
    } finally {
        if (oos != null) {
            oos.close();
        }
        if (baos != null) {
            baos.close();
        }
    }

    return bytes;
}

From source file:com.dragome.callbackevictor.serverside.utils.ReflectionUtils.java

public static Object cast(Object o) throws IOException, ClassNotFoundException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(buffer);
    oos.writeObject(o);/*from  ww w  .  j a  v a  2s. c  o  m*/
    oos.flush();
    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
    return ois.readObject();
}

From source file:common.services.generic.GenericCacheService.java

@Override
public boolean saveToFile() {
    if (cached_object == null)
        return false;
    try {/*from ww w.jav a2  s.  c  o m*/
        File f = new File(path, "cache.tmp");
        if (f.exists())
            f.delete();
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        ObjectOutputStream so = new ObjectOutputStream(fo);
        so.writeObject(cached_object);
        so.flush();
        so.close();
        fo.close();
        return true;
    } catch (IOException ex) {
        logger.error("failed to save cache path = " + path, ex);
        return false;
    }
}

From source file:edu.harvard.i2b2.Icd9ToSnomedCT.BinResourceFromIcd9ToSnomedCTMap.java

public void serializeIcd9CodeToNameMap() throws IOException {

    FileOutputStream fos = null;/*w  w w  . ja  va2 s .  c o m*/
    ObjectOutputStream oos = null;

    try {
        fos = new FileOutputStream(binFileName);

        oos = new ObjectOutputStream(fos);
        oos.writeObject(Icd9ToSnomedCTMap);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        fos.close();
        oos.close();
    }
}

From source file:com.conwet.silbops.model.JSONvsRMIPerfT.java

public static void sizeExternalizeSeveralWithoutTypes(Externalizable[] objects) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {/*from   ww  w . ja va 2s .c om*/
        ObjectOutputStream out = new ObjectOutputStream(baos);

        for (Externalizable object : objects) {
            object.writeExternal(out);
        }

        out.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    int size = baos.size();
    int sizePerMessage = size / objects.length;
    System.out.println("   Size no indicating types " + objects.length + " messages - RMI: " + size + " bytes ("
            + sizePerMessage + " bytes/msg)");
}

From source file:com.hs.mail.imap.processor.fetch.BodyStructureBuilder.java

public void writeBodyStructure(File file, MimeDescriptor descriptor) {
    if (descriptor != null) {
        ObjectOutputStream os = null;
        try {//from w  w w .  j a v a  2s. c o  m
            OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            os = new ObjectOutputStream(out);
            os.writeObject(descriptor);
            os.flush();
        } catch (Exception e) {
            //
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
}