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.nextgis.maplib.datasource.GeoGeometry.java

public byte[] toBlob() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(this);
    return out.toByteArray();
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.si.dictionary.GoogleDictionaryTest.java

@Test
public void testGoogleDictionary() throws Exception {

    FileUtils.deleteQuietly(new File(output));

    GoogleDictionary dictionary = new GoogleDictionary(path, needed_mentions);
    Assert.assertNotNull(dictionary);// w ww  .j  a  v  a 2s  .  c o  m

    ObjectOutputStream dictionaryWriter = new ObjectOutputStream(
            new BZip2CompressorOutputStream(new FileOutputStream(output)));
    dictionaryWriter.writeObject(dictionary);
    dictionaryWriter.close();

    Assert.assertTrue(new File(output).exists());

    ObjectInputStream dictionaryReader = new ObjectInputStream(
            new BZip2CompressorInputStream(new FileInputStream(output)));

    dictionary = null;
    dictionary = (GoogleDictionary) dictionaryReader.readObject();

    Assert.assertNotNull(dictionary);
    System.out.println(dictionary.getNumberOfMentionEntityPairs());
    System.out.println(dictionary.getTargetSize());
    Assert.assertEquals(3, dictionary.getTargetValuePairs("claude_monet").size());

    dictionaryReader.close();

}

From source file:edu.stanford.muse.lens.LensPrefs.java

private void savePrefs() {
    try {/*  w ww  .  j a  va  2  s .  co  m*/
        FileOutputStream fos = new FileOutputStream(pathToPrefsFile);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(prefs);
        oos.flush();
        oos.close();

        PrintStream ps = new PrintStream(new FileOutputStream(pathToPrefsFile + ".txt"));
        for (String term : prefs.keySet()) {
            Map<String, Float> map = prefs.get(term);
            for (String url : map.keySet())
                ps.println(term + "\t" + url + "\t" + map.get(url));
        }
        ps.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sf.dynamicreports.googlecharts.test.AbstractJasperTest.java

private JasperReportBuilder serializableTest(JasperReportBuilder report)
        throws IOException, ClassNotFoundException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(report);
    oos.flush();//  w w w.  j  a v  a  2s .c o  m
    oos.close();

    InputStream stream = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(stream);
    return (JasperReportBuilder) ois.readObject();
}

From source file:org.blanco.techmun.android.cproviders.EventosFetcher.java

private void saveOnCache(Context context, Eventos eventos, long mesaId) {
    try {//w  w  w  .j a  va  2 s .c o m
        FileOutputStream mesasFOS = context.openFileOutput("eventos_" + mesaId + ".df", Context.MODE_PRIVATE);
        ObjectOutputStream mesasOOS = new ObjectOutputStream(mesasFOS);
        mesasOOS.writeObject(eventos);
        mesasOOS.close();
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putLong("eventos_last_refresh", System.currentTimeMillis()).commit();
        //We just cached the events set the preference to not force the refresh again until expiration time
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putBoolean("force_eventos_refresh_" + mesaId, false).commit();
    } catch (IOException e) {
        Log.e("tachmun", "Error opening cache file for mesas in content provider. " + "No cache will be saved",
                e);
    }
}

From source file:com.backbase.expert.extensions.sushi.util.Base64Serializer.java

@Override
public String writeObject(Serializable serializable) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    String str = null;//from   w ww . j  a  v  a 2s.co m
    try {
        oos = new ObjectOutputStream(baos);
        oos.writeObject(serializable);
        byte[] data = baos.toByteArray();
        str = new String(Base64.encodeBase64(data), "UTF-8");
    } catch (IOException e) {
        LOG.error("Could not encode the object to a base64 string.", e);
    } finally {
        IOUtils.closeQuietly(oos);
    }
    return str;
}

From source file:com.taobao.metamorphosis.utils.codec.impl.JavaSerializer.java

/**
 * @see com.taobao.notify.codec.Serializer#encodeObject(Object)
 *//*from  www  .  j a  v a  2s .c  o m*/
@Override
public byte[] encodeObject(final Object objContent) throws IOException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream output = null;
    try {
        baos = new ByteArrayOutputStream(1024);
        output = new ObjectOutputStream(baos);
        output.writeObject(objContent);
    } catch (final IOException ex) {
        throw ex;

    } finally {
        if (output != null) {
            try {
                output.close();
                if (baos != null) {
                    baos.close();
                }
            } catch (final IOException ex) {
                this.logger.error("Failed to close stream.", ex);
            }
        }
    }
    return baos != null ? baos.toByteArray() : null;
}

From source file:com.github.stephanarts.cas.ticket.registry.provider.UpdateMethodTest.java

@Test
public void testValidInput() throws Exception {
    final byte[] serializedTicket;
    final HashMap<Integer, Ticket> map = new HashMap<Integer, Ticket>();
    final JSONObject params = new JSONObject();
    final IMethod method = new UpdateMethod(map);

    final String ticketId = "ST-1234567890ABCDEFGHIJKL-crud";
    final ServiceTicket ticket = mock(ServiceTicket.class, withSettings().serializable());
    when(ticket.getId()).thenReturn(ticketId);

    map.put(ticketId.hashCode(), ticket);

    try {/*w  ww. ja v  a  2  s  .  com*/
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bo);
        so.writeObject(ticket);
        so.flush();
        serializedTicket = bo.toByteArray();

        params.put("ticket-id", ticketId);
        params.put("ticket", DatatypeConverter.printBase64Binary(serializedTicket));
        method.execute(params);

    } catch (final JSONRPCException e) {
        Assert.fail(e.getMessage());
    } catch (final Exception e) {
        throw new Exception(e);
    }
}

From source file:com.lurencun.cfuture09.androidkit.http.async.PersistentCookieStore.java

protected String encodeCookie(SerializableCookie cookie) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {/* w ww  . j a  v a2 s . co  m*/
        ObjectOutputStream outputStream = new ObjectOutputStream(os);
        outputStream.writeObject(cookie);
    } catch (Exception e) {
        return null;
    }

    return StringUtil.byteArrayToHexString(os.toByteArray());
}

From source file:edu.umd.cs.buildServer.util.ServletAppender.java

@Override
protected void append(LoggingEvent event) {
    if (!APPEND_TO_SUBMIT_SERVER)
        return;//from  w w w . j  ava 2s.com
    try {
        Throwable throwable = null;
        if (event.getThrowableInformation() != null) {
            String[] throwableStringRep = event.getThrowableStrRep();
            StringBuffer stackTrace = new StringBuffer();
            for (String stackTraceString : throwableStringRep) {
                stackTrace.append(stackTraceString);
            }
            throwable = new Throwable(stackTrace.toString());
        }

        LoggingEvent newLoggingEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
                event.getLevel(), getConfig().getHostname() + ": " + event.getMessage(), throwable);

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);

        String logURL = config.getServletURL(SUBMIT_SERVER_HANDLEBUILDSERVERLOGMESSAGE_PATH);

        MultipartPostMethod post = new MultipartPostMethod(logURL);
        // add password

        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(sink);

        out.writeObject(newLoggingEvent);
        out.flush();
        // add serialized logging event object
        post.addPart(new FilePart("event", new ByteArrayPartSource("event.out", sink.toByteArray())));

        int status = client.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("Couldn't contact server: " + status);
        }
    } catch (IOException e) {
        // TODO any way to log these without an infinite loop?
        System.err.println(e.getMessage());
        e.printStackTrace(System.err);
    }
}