Example usage for java.io ObjectOutputStream close

List of usage examples for java.io ObjectOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the stream.

Usage

From source file:com.bitranger.parknshop.util.ObjUtils.java

public static byte[] toBytes(Object obj) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream objOut = null;
    byte[] plainObj = null;

    try {/*from  w w  w  .  j av a2  s. c o m*/
        objOut = new ObjectOutputStream(baos);
        objOut.writeObject(obj);
        plainObj = baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage() + "\n\tCAUSE: " + e.getCause(), e);
    } finally {
        try {
            baos.close();
            if (objOut != null) {
                objOut.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage() + "\n\tCAUSE: " + e.getCause(), e);
        }
    }
    return plainObj;
}

From source file:org.bonitasoft.engine.api.HTTPServerAPI.java

private String toXML(final Object options, final XStream xstream) throws IOException {
    final StringWriter stringWriter = new StringWriter();
    final ObjectOutputStream out = xstream.createObjectOutputStream(stringWriter);
    out.writeObject(options);//from w w w.ja va2  s  .com
    out.close();
    return stringWriter.toString();
}

From source file:org.vietspider.server.handler.DataContentHandler.java

@SuppressWarnings("unused")
public void execute(final HttpRequest request, final HttpResponse response, final HttpContext context,
        OutputStream output) throws Exception {
    Header header = request.getFirstHeader("action");
    String action = header.getValue();

    byte[] bytes = getRequestData(request);

    String value = new String(bytes, Application.CHARSET).trim();

    if ("load.new.list.metas".equals(action)) {
        String alert = SystemProperties.getInstance().getValue("alert.new.articles");
        if ("false".equals(alert) || (Application.LICENSE == Install.SEARCH_SYSTEM
                && (alert == null || alert.trim().isEmpty()))) {
            ArticleCollection collection = new ArticleCollection();
            String text = Object2XML.getInstance().toXMLDocument(collection).getTextValue();
            output.write(text.getBytes(Application.CHARSET));
            return;
        }//from   w w w. j a va2 s . c o m

        /* MetaList metas = new MetaList("vietspider");
         metas.setPageSize(10);
         metas.setCurrentPage(1);
                 
         Calendar calendar = Calendar.getInstance();
         String date = CalendarUtils.getDateFormat().format(calendar.getTime());
                
         //working with entry
         EntryReader entryReader = new EntryReader();
         IEntryDomain entryDomain = null;
         entryDomain = new SimpleEntryDomain(date, null, null);
         entryReader.read(entryDomain, metas, -1);*/

        ArticleCollection collection = new ArticleCollection();
        AlertQueue.createInstance().get(collection);

        //      List<Article> articles = metas.getData();
        //      collection.get().addAll(articles);

        String text = Object2XML.getInstance().toXMLDocument(collection).getTextValue();
        output.write(text.getBytes(Application.CHARSET));

        return;
    }

    if ("load.article".equals(action)) {
        Article article = null;
        try {
            article = DatabaseService.getLoader().loadArticle(value);
            StringBuilder builder = new StringBuilder(article.getMeta().getTitle());
            builder.append('\n').append(article.getMeta().getDesc());
            output.write(builder.toString().getBytes(Application.CHARSET));
        } catch (SQLException e) {
            output.write(("error\n" + e.toString()).getBytes());
        } catch (Exception e) {
            output.write(("error\n" + e.toString()).getBytes());
        }
        return;
    }

    if ("load.article.by.url".equals(action)) {
        //      if(!DataGetter.class.isInstance(DatabaseService.getLoader())) {
        if (DatabaseService.isMode(DatabaseService.RDBMS)) {
            output.write(new byte[0]);
            return;
        }

        TextSpliter spliter = new TextSpliter();
        String[] elements = spliter.toArray(value, '\n');
        if (elements.length != 2) {
            output.write(new byte[0]);
            return;
        }

        String articleId = DatabaseService.getLoader().loadIdByURL(elements[1]);
        if (articleId == null) {
            output.write(new byte[0]);
            return;
        }

        Article article = null;
        try {
            article = DatabaseService.getLoader().loadArticle(articleId);
            if (article == null) {
                output.write(new byte[0]);
                return;
            }

            if (!article.getDomain().getGroup().equals(elements[0])) {
                output.write(new byte[0]);
                return;
            }

            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOutputStream);
            out.writeObject(article);
            out.flush();
            out.close();

            bytes = byteOutputStream.toByteArray();
            bytes = new GZipIO().zip(bytes);

            output.write(bytes);
        } catch (SQLException e) {
            output.write(new byte[0]);
        } catch (Exception e) {
            output.write(new byte[0]);
        }
        return;
    }
}

From source file:com.ssn.ws.rest.service.LoginWithInstagram.java

private void storeAccessToken(AccessGrant accessGrant) {
    try {//from ww  w .j a  va  2 s .  c  o  m
        String rootPath = SSNHelper.getSsnWorkSpaceDirPath();
        String RememberMePath = rootPath + File.separator + SSNConstants.SSN_REMMEBER_ME_DIRECTORY;
        File file = new File(RememberMePath);

        if (!file.exists()) {
            file.mkdir();
        }

        String serializationFilePath = RememberMePath + File.separator + SSNConstants.SSN_INSTAGRAM_TOKEN
                + ".ser";
        File serializationFile = new File(serializationFilePath);
        serializationFile.setReadOnly();
        FileOutputStream fout = new FileOutputStream(serializationFile);
        ObjectOutputStream oos = new ObjectOutputStream(fout);

        oos.writeObject(accessGrant);
        oos.close();
        fout.close();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
}

From source file:net.fizzl.redditengine.impl.PersistentCookieStore.java

/**
 * Save cookies to a file/*from  ww w . j a v a 2 s  .  c  o m*/
 */
private void save() {
    RedditApi api = DefaultRedditApi.getInstance();
    Context ctx = api.getContext();
    try {
        FileOutputStream fos = ctx.openFileOutput(cookiestore, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        SerializableCookieStore tempStore = new SerializableCookieStore();
        for (Cookie c : getCookies()) {
            tempStore.addCookie(c);
        }
        oos.writeObject(tempStore);
        oos.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
    String languageValue = this.getStringFromField(this.language, execution);
    String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
    String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
    String usernameValue = this.getStringFromField(this.username, execution);
    String passwordValue = this.getStringFromField(this.password, execution);

    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
    Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);

    if (endpointUrlValue.startsWith("vm:")) {
        LocalWebServiceClient client = this.getWebServiceContext().getClient();
        WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext());
        WebServiceMessage resultMessage = client.send(endpointUrlValue, message);
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }//from w  w w.  j  av a2  s .  c  o m

    } else {

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        if (usernameValue != null && passwordValue != null) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue,
                    passwordValue);
            provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials);
            clientBuilder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = clientBuilder.build();

        HttpPost request = new HttpPost(endpointUrlValue);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(payload);
            oos.flush();
            oos.close();

            request.setEntity(new ByteArrayEntity(baos.toByteArray()));

        } catch (Exception e) {
            throw new ActivitiException("Error setting message payload", e);
        }

        byte[] responseBytes = null;
        try {
            // execute the POST request
            HttpResponse response = client.execute(request);
            responseBytes = IOUtils.toByteArray(response.getEntity().getContent());

        } finally {
            // release any connection resources used by the method
            request.releaseConnection();
        }

        if (responseBytes != null) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
                ObjectInputStream is = new ObjectInputStream(in);
                Object result = is.readObject();
                if (resultVariableValue != null) {
                    execution.setVariable(resultVariableValue, result);
                }
            } catch (Exception e) {
                throw new ActivitiException("Failed to read response value", e);
            }
        }
    }

    this.leave(execution);
}

From source file:com.twelvemonkeys.util.ObjectAbstractTestCase.java

public void testSerializeDeserializeThenCompare() throws Exception {
    Object obj = makeObject();//ww w  .j a  v a  2s.c o m
    if (obj instanceof Serializable && isTestSerialization()) {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buffer);
        out.writeObject(obj);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        Object dest = in.readObject();
        in.close();
        if (isEqualsCheckable()) {
            assertEquals("obj != deserialize(serialize(obj))", obj, dest);
        }
    }
}

From source file:net.sf.ehcache.jcache.JCacheStatisticsTest.java

/**
 * We want to be able to use Statistics as a value object.
 * We need to do some magic with the reference held to Cache
 *//*from w ww.  ja  va 2s.c om*/
public void testSerialization() throws IOException, ClassNotFoundException {

    Ehcache ehcache = new net.sf.ehcache.Cache("test", 1, true, false, 5, 2);
    manager.addCache(ehcache);
    Cache cache = new JCache(ehcache, null);
    cache.put("key1", "value1");
    cache.put("key2", "value1");
    cache.get("key1");
    cache.get("key1");

    CacheStatistics statistics = cache.getCacheStatistics();
    assertEquals(2, statistics.getCacheHits());
    assertEquals(0, statistics.getCacheMisses());
    assertEquals(CacheStatistics.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy());
    statistics.clearStatistics();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bout);
    oos.writeObject(statistics);
    byte[] serializedValue = bout.toByteArray();
    oos.close();
    CacheStatistics afterDeserializationStatistics = null;
    ByteArrayInputStream bin = new ByteArrayInputStream(serializedValue);
    ObjectInputStream ois = new ObjectInputStream(bin);
    afterDeserializationStatistics = (CacheStatistics) ois.readObject();
    ois.close();

    //Check after Serialization
    assertEquals(2, afterDeserializationStatistics.getCacheHits());
    assertEquals(0, afterDeserializationStatistics.getCacheMisses());
    assertEquals(CacheStatistics.STATISTICS_ACCURACY_BEST_EFFORT, statistics.getStatisticsAccuracy());
    statistics.clearStatistics();

}

From source file:BckgrndServiceThreads.fileListingTH.java

void saveSerializedObject(String Objectname, Object serialisableObject) throws Exception {
    FileOutputStream outputFile = new FileOutputStream(Objectname);
    ObjectOutputStream outputObject = new ObjectOutputStream(outputFile);
    outputObject.writeObject(serialisableObject);
    outputObject.close();
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Do serialization//from  ww w .ja v  a 2  s. com
 */
private ByteArrayOutputStream serialize(Object target) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(target);
    oos.flush();
    oos.close();
    return baos;
}