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.joliciel.talismane.machineLearning.perceptron.PerceptronClassificationModel.java

@Override
public void writeModelToStream(OutputStream outputStream) {
    try {/*from w ww . j  a  v  a 2  s.  c  o m*/
        ObjectOutputStream out = new ObjectOutputStream(outputStream);

        out.writeObject(params);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:net.javacoding.jspider.core.task.work.SerializableSpiderHttpURLTask.java

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();//  ww  w  .j av a  2 s  .  c  o m
    out.writeObject(this.foundURL);
    out.writeObject(this.contextToString);
}

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

/**
 * Execute the JSONRPCFunction.//from  w  w  w  . j a  v a  2s  . com
 *
 * @param params    JSONRPC Method Parameters.
 *
 * @return          JSONRPC result object
 *
 * @throws JSONRPCException implementors can throw JSONRPCExceptions containing the error.
 */
public JSONObject execute(final JSONObject params) throws JSONRPCException {
    JSONObject result = new JSONObject();
    JSONArray tickets = new JSONArray();

    String ticketId = null;

    if (params.length() != 0) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }

    for (Ticket ticket : this.map.values()) {

        byte[] serializedTicketArray = { 0 };

        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream so = new ObjectOutputStream(bo);
            so.writeObject(ticket);
            so.flush();
            serializedTicketArray = bo.toByteArray();
        } catch (final Exception e) {
            logger.debug(e.getMessage());
            throw new JSONRPCException(-32500, "Error extracting Ticket");
        }

        tickets.put(DatatypeConverter.printBase64Binary(serializedTicketArray));
    }

    logger.debug("GetTickets: " + tickets.length());

    result.put("tickets", tickets);

    return result;
}

From source file:com.googlecode.DownloadCache.java

private void saveIndex() throws Exception {
    if (this.basedir.exists() && !this.basedir.isDirectory()) {
        throw new Exception("Cannot use " + this.basedir + " as cache directory: file exists");
    }/*from  w  w w .  j av a  2  s  . c o m*/
    if (!this.basedir.exists()) {
        this.basedir.mkdirs();
    }
    if (!this.indexFile.exists()) {
        this.indexFile.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(this.indexFile);
    ObjectOutputStream res = new ObjectOutputStream(out);
    res.writeObject(index);
    res.close();
}

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));
    }// ww  w.j a  v  a2 s  .co 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:org.sakaiproject.orm.ibatis.support.BlobSerializableTypeHandler.java

protected void setParameterInternal(PreparedStatement ps, int index, Object value, String jdbcType,
        LobCreator lobCreator) throws SQLException, IOException {

    if (value != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        try {/*  ww w.  j  a  va2 s .  c  o  m*/
            oos.writeObject(value);
            oos.flush();
            lobCreator.setBlobAsBytes(ps, index, baos.toByteArray());
        } finally {
            oos.close();
        }
    } else {
        lobCreator.setBlobAsBytes(ps, index, null);
    }
}

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

/**
 * Execute the JSONRPCFunction./*  w  ww . ja va2  s  . c  o  m*/
 *
 * @param params    JSONRPC Method Parameters.
 *
 * @return          JSONRPC result object
 *
 * @throws JSONRPCException implementors can throw JSONRPCExceptions containing the error.
 */
public JSONObject execute(final JSONObject params) throws JSONRPCException {
    JSONObject result = new JSONObject();
    Ticket ticket;

    logger.debug("GET");

    String ticketId = null;

    if (params.length() != 1) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }
    if (!(params.has("ticket-id"))) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }

    ticketId = params.getString("ticket-id");

    ticket = this.map.get(ticketId.hashCode());

    if (ticket == null) {
        throw new JSONRPCException(-32503, "Missing Ticket");
    }

    byte[] serializedTicketArray = { 0 };

    try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(bo);
        so.writeObject(ticket);
        so.flush();
        serializedTicketArray = bo.toByteArray();
    } catch (final Exception e) {
        logger.debug(e.getMessage());
        throw new JSONRPCException(-32500, "Error extracting Ticket");
    }

    result.put("ticket-id", ticketId);
    result.put("ticket", DatatypeConverter.printBase64Binary(serializedTicketArray));
    return result;
}

From source file:com.fuzhepan.arpc.client.ProxyHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    log.debug("invoke was called!");

    if (method.getName().equals("toString")) {
        return "toString method was called";
    }/*  w w  w .j  a  v  a 2 s  . co  m*/

    RpcContext rpcContext = new RpcContext(interfaceName, method.getName(), method.getParameterTypes(), args);

    //get service info and load balance
    List<HostPortPair> serviceList = RpcConfig.getServiceList(serviceName);
    if (serviceList == null || serviceList.size() == 0)
        throw new ClassNotFoundException("not find service : " + serviceName);
    int index = requestCount.get() % serviceList.size();
    if (requestCount.get() > 100)
        requestCount.set(0);
    else
        requestCount.getAndIncrement();
    HostPortPair hostPort = serviceList.get(index);

    Socket socket = new Socket(hostPort.host, hostPort.port);
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
    objectOutputStream.writeObject(rpcContext);
    objectOutputStream.flush();

    ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
    Object response = objectInputStream.readObject();

    objectInputStream.close();
    objectOutputStream.close();
    socket.close();

    Class methodReturnType = method.getReturnType();
    return methodReturnType.cast(response);
}

From source file:org.commonjava.maven.atlas.graph.spi.neo4j.io.Conversions.java

public static void storeView(final ViewParams params, final Node viewNode) {
    viewNode.setProperty(Conversions.VIEW_SHORT_ID, params.getShortId());

    ObjectOutputStream oos = null;
    try {/*from   w w w.j  a  v a2 s  .c  o m*/
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        oos = new ObjectOutputStream(baos);
        oos.writeObject(params);

        viewNode.setProperty(VIEW_DATA, baos.toByteArray());
    } catch (final IOException e) {
        throw new IllegalStateException("Cannot construct ObjectOutputStream to wrap ByteArrayOutputStream!",
                e);
    } finally {
        IOUtils.closeQuietly(oos);
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.report.ReportBrowseSaveCollectedRunsController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Session session = Session.create(request);
    String name = request.getParameter("saveName");
    String redirect = request.getParameter("redirect");
    if (redirect == null) {
        redirect = "";
    }/*  w  w w  . j a va 2 s  .c  o m*/
    User user = Auth.getAuthorizedUser(request);
    if (user == null)
        throw new NotAuthorizedException();

    List<TestRunSearchData> collectedTestRuns = session.getCollectedTestRuns();

    SavedRun savedRun = new SavedRun();
    savedRun.setDate(new Date());
    savedRun.setName(name);
    savedRun.setUserId(user.getId());

    Long id = testRunDAO.saveRun(savedRun);

    savedRun.setId(id);
    FileUtils.mkdirs(config.getDataFolder() + File.separator + savedRun.generateDirUrl());

    File file = new File(config.getDataFolder() + File.separator + savedRun.generateFileUrl());

    file.createNewFile();

    FileOutputStream fos = new FileOutputStream(file);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(collectedTestRuns);
    oos.flush();
    oos.close();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strDate = sdf.format(savedRun.getDate());

    String convertedName = savedRun.getName().replaceAll("[^a-zA-Z0-9]", "_");

    String url = "../report/saved-" + user.getLogin() + "-" + strDate + "-" + convertedName + "-" + id;
    session.setTemporaryMessage("Your collected test runs were successfully saved."
            + " You can use them with the following url:<br/>" + "HTML: <a href=\"" + url
            + ".html\">Html version</a>" + "<br/>" + "Excel: <a href=\"" + url + ".xls\">Excel version</>");
    return new ModelAndView(new RedirectView(redirect));
}