Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.sonicle.webtop.contacts.ContactsManager.java

private void doContactPictureInsert(Connection con, int contactId, ContactPictureWithBytesOld picture)
        throws DAOException {
    ContactPictureDAO cpicDao = ContactPictureDAO.getInstance();

    OContactPicture ocpic = new OContactPicture();
    ocpic.setContactId(contactId);/*from w  w w  .  j  av  a 2s .c o m*/
    ocpic.setMediaType(picture.getMediaType());

    try {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(picture.getBytes()));
        if ((bi.getWidth() > 720) || (bi.getHeight() > 720)) {
            bi = Scalr.resize(bi, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, 720);
            ocpic.setWidth(bi.getWidth());
            ocpic.setHeight(bi.getHeight());
            String formatName = new MimeType(picture.getMediaType()).getSubType();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(bi, formatName, baos);
                baos.flush();
                ocpic.setBytes(baos.toByteArray());
            } catch (IOException ex1) {
                logger.warn("Error resizing image", ex1);
            } finally {
                IOUtils.closeQuietly(baos);
            }
        } else {
            ocpic.setWidth(bi.getWidth());
            ocpic.setHeight(bi.getHeight());
            ocpic.setBytes(picture.getBytes());
        }
    } catch (IOException ex) {
        throw new WTRuntimeException(ex, "Error handling picture");
    }
    cpicDao.insert(con, ocpic);
}

From source file:com.sonicle.webtop.contacts.ContactsManager.java

private OContactPicture doContactPictureInsert(Connection con, int contactId, ContactPictureWithBytes picture)
        throws DAOException {
    ContactPictureDAO cpicDao = ContactPictureDAO.getInstance();

    OContactPicture ocpic = new OContactPicture();
    ocpic.setContactId(contactId);/*from  w ww.  ja  v  a2  s.com*/
    ocpic.setMediaType(picture.getMediaType());

    try {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(picture.getBytes()));
        if ((bi.getWidth() > 720) || (bi.getHeight() > 720)) {
            bi = Scalr.resize(bi, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, 720);
            ocpic.setWidth(bi.getWidth());
            ocpic.setHeight(bi.getHeight());
            String formatName = new MimeType(picture.getMediaType()).getSubType();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(bi, formatName, baos);
                baos.flush();
                ocpic.setBytes(baos.toByteArray());
            } catch (IOException ex1) {
                logger.warn("Error resizing image", ex1);
            } finally {
                IOUtils.closeQuietly(baos);
            }
        } else {
            ocpic.setWidth(bi.getWidth());
            ocpic.setHeight(bi.getHeight());
            ocpic.setBytes(picture.getBytes());
        }
    } catch (IOException ex) {
        throw new WTRuntimeException(ex, "Error handling picture");
    }
    cpicDao.insert(con, ocpic);
    return ocpic;
}

From source file:bftsmart.tom.core.Synchronizer.java

/**
 * This method is called when there is a timeout and the request has already
 * been forwarded to the leader//from   ww  w .  j a v a2 s . co m
 *
 * @param requestList List of requests that the replica wanted to order but
 * didn't manage to
 */
public void triggerTimeout(List<TOMMessage> requestList) {

    ObjectOutputStream out = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    int regency = lcManager.getNextReg();

    requestsTimer.stopTimer();
    requestsTimer.Enabled(false);

    // still not in the leader change phase?
    if (lcManager.getNextReg() == lcManager.getLastReg()) {

        lcManager.setNextReg(lcManager.getLastReg() + 1); // define next timestamp

        regency = lcManager.getNextReg(); // update variable 

        // store messages to be ordered
        lcManager.setCurrentRequestTimedOut(requestList);

        // store information about messages that I'm going to send
        lcManager.addStop(regency, this.controller.getStaticConf().getProcessId());

        //execManager.stop(); // stop consensus execution

        //Get requests that timed out and the requests received in STOP messages
        //and add those STOPed requests to the client manager
        addSTOPedRequestsToClientManager();
        List<TOMMessage> messages = getRequestsToRelay();

        try { // serialize content to send in STOP message
            out = new ObjectOutputStream(bos);

            if (messages != null && messages.size() > 0) {

                //TODO: If this is null, then there was no timeout nor STOP messages.
                //What to do?
                byte[] serialized = bb.makeBatch(messages, 0, 0, controller);
                out.writeBoolean(true);
                out.writeObject(serialized);
            } else {
                out.writeBoolean(false);
                System.out.println(
                        "(Synchronizer.triggerTimeout) Strange... did not include any request in my STOP message for regency "
                                + regency);
            }

            byte[] payload = bos.toByteArray();

            out.flush();
            bos.flush();

            out.close();
            bos.close();

            // send STOP-message                
            System.out.println("(Synchronizer.triggerTimeout) sending STOP message to install regency "
                    + regency + " with " + (messages != null ? messages.size() : 0) + " request(s) to relay");

            LCMessage stop = new LCMessage(this.controller.getStaticConf().getProcessId(), TOMUtil.STOP,
                    regency, payload);
            requestsTimer.setSTOP(regency, stop); // make replica re-transmit the stop message until a new regency is installed
            communication.send(this.controller.getCurrentViewOtherAcceptors(), stop);

        } catch (IOException ex) {
            ex.printStackTrace();
            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
                bos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    processOutOfContextSTOPs(regency); // the replica might have received STOPs
                                       // that were out of context at the time they
                                       // were received, but now can be processed

    startSynchronization(regency); // evaluate STOP messages

}

From source file:bftsmart.tom.core.Synchronizer.java

private void startSynchronization(int nextReg) {

    boolean condition;
    ObjectOutputStream out = null;
    ByteArrayOutputStream bos = null;

    if (this.controller.getStaticConf().isBFT()) {
        condition = lcManager.getStopsSize(nextReg) > this.controller.getCurrentViewF();
    } else {/* w  w w  .  j  a  v  a2s . co m*/
        condition = lcManager.getStopsSize(nextReg) > 0;
    }

    // Ask to start the synchronizations phase if enough messages have been received already
    if (condition && lcManager.getNextReg() == lcManager.getLastReg()) {

        Logger.println("(Synchronizer.startSynchronization) initialize synch phase");
        requestsTimer.Enabled(false);
        requestsTimer.stopTimer();

        lcManager.setNextReg(lcManager.getLastReg() + 1); // define next timestamp

        int regency = lcManager.getNextReg();

        // store information about message I am going to send
        lcManager.addStop(regency, this.controller.getStaticConf().getProcessId());

        //execManager.stop(); // stop execution of consensus

        //Get requests that timed out and the requests received in STOP messages
        //and add those STOPed requests to the client manager
        addSTOPedRequestsToClientManager();
        List<TOMMessage> messages = getRequestsToRelay();

        try { // serialize conent to send in the STOP message
            bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bos);

            // Do I have messages to send in the STOP message?
            if (messages != null && messages.size() > 0) {

                //TODO: If this is null, there was no timeout nor STOP messages.
                //What shall be done then?
                out.writeBoolean(true);
                byte[] serialized = bb.makeBatch(messages, 0, 0, controller);
                out.writeObject(serialized);
            } else {
                out.writeBoolean(false);
                System.out.println(
                        "(Synchronizer.startSynchronization) Strange... did not include any request in my STOP message for regency "
                                + regency);
            }

            out.flush();
            bos.flush();

            byte[] payload = bos.toByteArray();
            out.close();
            bos.close();

            // send message STOP
            System.out.println("(Synchronizer.startSynchronization) sending STOP message to install regency "
                    + regency + " with " + (messages != null ? messages.size() : 0) + " request(s) to relay");

            LCMessage stop = new LCMessage(this.controller.getStaticConf().getProcessId(), TOMUtil.STOP,
                    regency, payload);
            requestsTimer.setSTOP(regency, stop); // make replica re-transmit the stop message until a new regency is installed
            communication.send(this.controller.getCurrentViewOtherAcceptors(), stop);

        } catch (IOException ex) {
            ex.printStackTrace();
            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
                bos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    if (this.controller.getStaticConf().isBFT()) {
        condition = lcManager.getStopsSize(nextReg) > (2 * this.controller.getCurrentViewF());
    } else {
        condition = lcManager.getStopsSize(nextReg) > this.controller.getCurrentViewF();
    }

    // Did the synchronization phase really started?
    //if (lcManager.getStopsSize(nextReg) > this.reconfManager.getQuorum2F() && lcManager.getNextReg() > lcManager.getLastReg()) {
    if (condition && lcManager.getNextReg() > lcManager.getLastReg()) {

        if (!execManager.stopped())
            execManager.stop(); // stop consensus execution if more than f replicas sent a STOP message

        Logger.println("(Synchronizer.startSynchronization) installing regency " + lcManager.getNextReg());
        lcManager.setLastReg(lcManager.getNextReg()); // define last timestamp

        int regency = lcManager.getLastReg();

        // avoid memory leaks
        lcManager.removeStops(nextReg);
        lcManager.clearCurrentRequestTimedOut();
        lcManager.clearRequestsFromSTOP();

        requestsTimer.Enabled(true);
        requestsTimer.setShortTimeout(-1);
        requestsTimer.startTimer();

        //int leader = regency % this.reconfManager.getCurrentViewN(); // new leader
        int leader = lcManager.getNewLeader();
        int in = tom.getInExec(); // cid to execute
        int last = tom.getLastExec(); // last cid decided

        execManager.setNewLeader(leader);

        // If I am not the leader, I have to send a STOPDATA message to the elected leader
        if (leader != this.controller.getStaticConf().getProcessId()) {

            try { // serialize content of the STOPDATA message

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

                Consensus cons = null;

                // content of the last decided CID
                if (last > -1)
                    cons = execManager.getConsensus(last);

                //Do I have info on my last executed consensus?
                if (cons != null && cons.getDecisionEpoch() != null
                        && cons.getDecisionEpoch().propValue != null) {

                    out.writeBoolean(true);
                    out.writeInt(last);
                    //byte[] decision = exec.getLearner().getDecision();

                    byte[] decision = cons.getDecisionEpoch().propValue;
                    Set<ConsensusMessage> proof = cons.getDecisionEpoch().getProof();

                    out.writeObject(decision);
                    out.writeObject(proof);
                    // TODO: WILL BE NECESSARY TO ADD A PROOF!!!

                } else {
                    out.writeBoolean(false);

                    ////// THIS IS TO CATCH A BUG!!!!!
                    if (last > -1) {
                        System.out.println("[DEBUG INFO FOR LAST CID #1]");

                        if (cons == null) {
                            if (last > -1)
                                System.out.println("No consensus instance for cid " + last);

                        } else if (cons.getDecisionEpoch() == null) {
                            System.out.println("No decision epoch for cid " + last);
                        } else {
                            System.out.println(
                                    "epoch for cid: " + last + ": " + cons.getDecisionEpoch().toString());

                            if (cons.getDecisionEpoch().propValue == null) {
                                System.out.println("No propose for cid " + last);
                            } else {
                                System.out.println(
                                        "Propose hash for cid " + last + ": " + Base64.encodeBase64String(
                                                tom.computeHash(cons.getDecisionEpoch().propValue)));
                            }
                        }
                    }

                }

                if (in > -1) { // content of cid in execution

                    cons = execManager.getConsensus(in);

                    //cons.incEts(); // make the consensus advance to the next epoch
                    cons.setETS(regency); // make the consensus advance to the next epoch

                    //int ets = cons.getEts();
                    //cons.createEpoch(ets, controller);
                    cons.createEpoch(regency, controller);
                    //Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus " + cons.getId() + " to " + ets);
                    Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus "
                            + cons.getId() + " to " + regency);

                    TimestampValuePair quorumWrites;
                    if (cons.getQuorumWrites() != null) {

                        quorumWrites = cons.getQuorumWrites();

                    } else {

                        quorumWrites = new TimestampValuePair(0, new byte[0]);
                    }

                    HashSet<TimestampValuePair> writeSet = cons.getWriteSet();

                    //CollectData collect = new CollectData(this.controller.getStaticConf().getProcessId(), in, ets, quorumWrites, writeSet);
                    CollectData collect = new CollectData(this.controller.getStaticConf().getProcessId(), in,
                            regency, quorumWrites, writeSet);

                    SignedObject signedCollect = tom.sign(collect);

                    out.writeObject(signedCollect);

                } else {

                    cons = execManager.getConsensus(last + 1);

                    //cons.incEts(); // make the consensus advance to the next epoch
                    cons.setETS(regency); // make the consensus advance to the next epoch

                    //int ets = cons.getEts();
                    //cons.createEpoch(ets, controller);
                    cons.createEpoch(regency, controller);
                    //Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus " + cons.getId() + " to " + ets);
                    Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus "
                            + cons.getId() + " to " + regency);

                    //CollectData collect = new CollectData(this.controller.getStaticConf().getProcessId(), last + 1, ets, new TimestampValuePair(0, new byte[0]), new HashSet<TimestampValuePair>());
                    CollectData collect = new CollectData(this.controller.getStaticConf().getProcessId(),
                            last + 1, regency, new TimestampValuePair(0, new byte[0]),
                            new HashSet<TimestampValuePair>());

                    SignedObject signedCollect = tom.sign(collect);

                    out.writeObject(signedCollect);

                }

                out.flush();
                bos.flush();

                byte[] payload = bos.toByteArray();
                out.close();
                bos.close();

                int[] b = new int[1];
                b[0] = leader;

                System.out
                        .println("(Synchronizer.startSynchronization) sending STOPDATA of regency " + regency);
                // send message SYNC to the new leader
                communication.send(b, new LCMessage(this.controller.getStaticConf().getProcessId(),
                        TOMUtil.STOPDATA, regency, payload));

                //TODO: Turn on timeout again?
            } catch (IOException ex) {
                ex.printStackTrace();
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    out.close();
                    bos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            // the replica might have received a SYNC that was out of context at the time it was received, but now can be processed
            Set<LCMessage> sync = getOutOfContextLC(TOMUtil.SYNC, regency);

            Logger.println(
                    "(Synchronizer.startSynchronization) Checking if there are out of context SYNC for regency "
                            + regency);

            if (sync.size() > 0) {
                System.out.println(
                        "(Synchronizer.startSynchronization) Processing out of context SYNC for regency "
                                + regency);
            } else {
                Logger.println(
                        "(Synchronizer.startSynchronization) No out of context SYNC for regency " + regency);
            }

            for (LCMessage m : sync) {
                if (m.getSender() == execManager.getCurrentLeader()) {
                    processSYNC(m.getPayload(), regency);
                    return; // makes no sense to continue, since there is only one SYNC message
                }
            }

        } else { // If leader, I will store information that I would send in a SYNC message

            Logger.println("(Synchronizer.startSynchronization) I'm the leader for this new regency");
            CertifiedDecision lastDec = null;
            CollectData collect = null;

            Consensus cons = null;

            //Content of the last decided CID
            if (last > -1)
                cons = execManager.getConsensus(last);

            //Do I have info on my last executed consensus?
            if (cons != null && cons.getDecisionEpoch() != null && cons.getDecisionEpoch().propValue != null) {
                //byte[] decision = exec.getLearner().getDecision();

                byte[] decision = cons.getDecisionEpoch().propValue;
                Set<ConsensusMessage> proof = cons.getDecisionEpoch().getProof();

                lastDec = new CertifiedDecision(this.controller.getStaticConf().getProcessId(), last, decision,
                        proof);
                // TODO: WILL BE NECESSARY TO ADD A PROOF!!!??

            } else {
                lastDec = new CertifiedDecision(this.controller.getStaticConf().getProcessId(), last, null,
                        null);

                ////// THIS IS TO CATCH A BUG!!!!!
                if (last > -1) {
                    System.out.println("[DEBUG INFO FOR LAST CID #2]");

                    if (cons == null) {
                        if (last > -1)
                            System.out.println("No consensus instance for cid " + last);

                    } else if (cons.getDecisionEpoch() == null) {
                        System.out.println("No decision epoch for cid " + last);
                    } else {
                        System.out
                                .println("epoch for cid: " + last + ": " + cons.getDecisionEpoch().toString());
                    }
                    if (cons.getDecisionEpoch().propValue == null) {
                        System.out.println("No propose for cid " + last);
                    } else {
                        System.out.println("Propose hash for cid " + last + ": " + Base64
                                .encodeBase64String(tom.computeHash(cons.getDecisionEpoch().propValue)));
                    }
                }

            }
            lcManager.addLastCID(regency, lastDec);

            if (in > -1) { // content of cid being executed
                cons = execManager.getConsensus(in);

                //cons.incEts(); // make the consensus advance to the next epoch
                cons.setETS(regency); // make the consensus advance to the next epoch

                //int ets = cons.getEts();
                //cons.createEpoch(ets, controller);
                cons.createEpoch(regency, controller);
                //Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus " + cons.getId() + " to " + ets);
                Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus "
                        + cons.getId() + " to " + regency);

                TimestampValuePair quorumWrites;

                if (cons.getQuorumWrites() != null) {

                    quorumWrites = cons.getQuorumWrites();
                } else {
                    quorumWrites = new TimestampValuePair(0, new byte[0]);
                }

                HashSet<TimestampValuePair> writeSet = cons.getWriteSet();

                //collect = new CollectData(this.controller.getStaticConf().getProcessId(), in, ets, quorumWrites, writeSet);
                collect = new CollectData(this.controller.getStaticConf().getProcessId(), in, regency,
                        quorumWrites, writeSet);

            } else {

                cons = execManager.getConsensus(last + 1);

                //cons.incEts(); // make the consensus advance to the next epoch
                cons.setETS(regency); // make the consensus advance to the next epoch

                //int ets = cons.getEts();
                //cons.createEpoch(ets, controller);
                cons.createEpoch(regency, controller);
                //Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus " + cons.getId() + " to " + ets);
                Logger.println("(Synchronizer.startSynchronization) incrementing ets of consensus "
                        + cons.getId() + " to " + regency);

                //collect = new CollectData(this.controller.getStaticConf().getProcessId(), last + 1, ets, new TimestampValuePair(0, new byte[0]), new HashSet<TimestampValuePair>());
                collect = new CollectData(this.controller.getStaticConf().getProcessId(), last + 1, regency,
                        new TimestampValuePair(0, new byte[0]), new HashSet<TimestampValuePair>());
            }

            SignedObject signedCollect = tom.sign(collect);

            lcManager.addCollect(regency, signedCollect);

            // the replica might have received STOPDATAs that were out of context at the time they were received, but now can be processed
            Set<LCMessage> stopdatas = getOutOfContextLC(TOMUtil.STOPDATA, regency);

            Logger.println(
                    "(Synchronizer.startSynchronization) Checking if there are out of context STOPDATAs for regency "
                            + regency);
            if (stopdatas.size() > 0) {
                System.out.println("(Synchronizer.startSynchronization) Processing " + stopdatas.size()
                        + " out of context STOPDATAs for regency " + regency);
            } else {
                Logger.println("(Synchronizer.startSynchronization) No out of context STOPDATAs for regency "
                        + regency);
            }

            for (LCMessage m : stopdatas) {
                processSTOPDATA(m, regency);
            }

        }

    }
}

From source file:graphene.rest.ws.impl.UDSessionRSImpl.java

private String saveSessionToFile(final String rootName, final String sessionData) {

    String response = "{ id: \"TBD\", error:\"no error\" }";
    String errormsg = null;/*from w ww .j  a va  2  s .  com*/

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    // DEBUG
    logger.debug("saveSessionToFile: sessionData received =");
    logger.debug(sessionData);

    // Create the file on the Web Server
    File filedir = null;
    File file = null;

    // sessionId has this format:
    // userId + "_" + sessionname + "_" + new Date().getTime()).toString()

    String basepath = null;

    // sessionData should contain the following at the beginning
    // {
    // name: "xxx", - Name of the session
    // userId: "yyy", - unique user id for the associated user
    // lastUpdated: "zzz", - Date and timestamp (in milliseconds) when the
    // session was saved by the user
    // sessionActions: ....

    final int indxName = sessionData.indexOf("name");
    final int indxuserId = sessionData.indexOf("userId");
    final int indxDate = sessionData.indexOf("lastUpdated");
    final int indxAfterDate = sessionData.indexOf("sessionActions");
    if ((indxName < 0) || (indxuserId < 0) || (indxDate < 0) || (indxAfterDate < 0)) {
        errormsg = "saveSessionToFile: Invalid session data was received, unable to save it.";
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    String sessionName = sessionData.substring(indxName + 5, indxuserId - 1);
    sessionName = sessionName.replace("\"", "");
    sessionName = sessionName.replace(",", "");
    sessionName = sessionName.trim();

    String userId = sessionData.substring(indxuserId + 7, indxDate - 1);
    userId = userId.replace("\"", "");
    userId = userId.replace(",", "");
    userId = userId.trim();

    String lastUpdated = sessionData.substring(indxDate + 12, indxAfterDate - 1);
    lastUpdated = lastUpdated.replace("\"", "");
    lastUpdated = lastUpdated.replace(",", "");
    lastUpdated = lastUpdated.trim();

    if (servletContext != null) {
        basepath = servletContext.getRealPath("/");
    }

    // TODO the file should be placed under the webserver's dir
    if (basepath == null) {
        // TODO - handle case if the Server is Linux instead of Windows
        basepath = "C:/Windows/Temp"; // Temp hack
    }

    try {
        writer.write(sessionData);
    } catch (final IOException e) {
        errormsg = "saveSessionToFile: Server Exception writing session JSON data";
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    try {
        writer.close();
        outputStream.flush();
        outputStream.close();
    } catch (final java.io.IOException e) {
        errormsg = "saveSessionToFile: I/O Exception when attempting to close output after write. Details "
                + e.getMessage();
        logger.error(errormsg);
        logger.error(e.getMessage());
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // Files are written as:
    // <basepath>/UDS/<userId>/<sessionname>_<date>
    final String serverPathName = basepath + "/" + rootName + "/" + userId;
    final String serverfileName = sessionName + "_" + lastUpdated + ".txt";

    // DEBUG
    logger.debug(
            "saveSessionToFile: serverPathName = " + serverPathName + ", serverfileName = " + serverfileName);

    try {
        filedir = new File(serverPathName);
        filedir.setWritable(true);
        filedir.mkdirs();

        file = new File(serverPathName + "/" + serverfileName);
        final FileOutputStream fout = new FileOutputStream(file);
        fout.write(outputStream.toByteArray());
        fout.close();
        // String finalPath = file.toURI().toString();
        // finalPath = finalPath.replace("file:/", ""); // remove leading

    } catch (final Exception fe) {
        errormsg = "saveSessionToFile: Failed to create file for session data. Details: "
                + fe.getLocalizedMessage();
        logger.error(errormsg);
        response = "{ id: \"-1\", error:\"" + errormsg + "\" }";
        return response;
    }

    // set the unique id of the response
    final String sessionId = createSessionId(userId, sessionName, lastUpdated);

    response = "{ id: \"" + sessionId + "\", error:\"no error\" }";
    return response;
}

From source file:microsoft.exchange.webservices.data.AutodiscoverService.java

/**
 * Calls the Autodiscover service to get configuration settings at the
 * specified URL./* www  . j ava 2s  .  co m*/
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls
 * @param emailAddress the email address
 * @param url          the url
 * @return The requested configuration settings. (TSettings The type of the
 * settings to retrieve)
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings getLegacyUserSettingsAtUrl(Class<TSettings> cls,
        String emailAddress, URI url) throws Exception {
    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
            String.format("Trying to call Autodiscover for %s on %s.", emailAddress, url));

    TSettings settings = cls.newInstance();

    HttpWebRequest request = null;
    try {
        request = this.prepareHttpWebRequestForUrl(url);

        this.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);
        // OutputStreamWriter out = new
        // OutputStreamWriter(request.getOutputStream());
        OutputStream urlOutStream = request.getOutputStream();

        // If tracing is enabled, we generate the request in-memory so that we
        // can pass it along to the ITraceListener. Then we copy the stream to
        // the request stream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverRequest)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            PrintWriter writer = new PrintWriter(memoryStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);
            writer.flush();

            this.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
            // out.write(memoryStream.toString());
            // out.close();
            memoryStream.writeTo(urlOutStream);
            urlOutStream.flush();
            urlOutStream.close();
            memoryStream.close();
        } else {
            PrintWriter writer = new PrintWriter(urlOutStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);

            /*  Flush Start */
            writer.flush();
            urlOutStream.flush();
            urlOutStream.close();
            /* Flush End */
        }
        request.executeRequest();
        request.getResponseCode();
        URI redirectUrl;
        OutParam<URI> outParam = new OutParam<URI>();
        if (this.tryGetRedirectionResponse(request, outParam)) {
            redirectUrl = outParam.getParam();
            settings.makeRedirectionResponse(redirectUrl);
            return settings;
        }
        InputStream serviceResponseStream = request.getInputStream();
        // If tracing is enabled, we read the entire response into a
        // MemoryStream so that we
        // can pass it along to the ITraceListener. Then we parse the response
        // from the
        // MemoryStream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverResponse)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            while (true) {
                int data = serviceResponseStream.read();
                if (-1 == data) {
                    break;
                } else {
                    memoryStream.write(data);
                }
            }
            memoryStream.flush();

            this.traceResponse(request, memoryStream);
            ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
            EwsXmlReader reader = new EwsXmlReader(memoryStreamIn);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);

        } else {
            EwsXmlReader reader = new EwsXmlReader(serviceResponseStream);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);
        }

        serviceResponseStream.close();
    } finally {
        if (request != null) {
            try {
                request.close();
            } catch (Exception e2) {
                // Ignore exceptions while closing the request.
            }
        }
    }

    return settings;
}

From source file:com.jredrain.startup.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*from w  ww .  j a v a 2s .c  om*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[redrain]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = RedRain.StatusCode.ERROR_EXEC.getValue();
        }
        if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[redrain]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[redrain]:error:{}", e);
            }
        }

        if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[redrain]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:microsoft.exchange.webservices.data.autodiscover.AutodiscoverService.java

/**
 * Calls the Autodiscover service to get configuration settings at the
 * specified URL.//from w ww.  j av a 2 s .  c o  m
 *
 * @param <TSettings>  the generic type
 * @param cls          the cls
 * @param emailAddress the email address
 * @param url          the url
 * @return The requested configuration settings. (TSettings The type of the
 * settings to retrieve)
 * @throws Exception the exception
 */
private <TSettings extends ConfigurationSettingsBase> TSettings getLegacyUserSettingsAtUrl(Class<TSettings> cls,
        String emailAddress, URI url) throws Exception {
    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
            String.format("Trying to call Autodiscover for %s on %s.", emailAddress, url));

    TSettings settings = cls.newInstance();

    HttpWebRequest request = null;
    try {
        request = this.prepareHttpWebRequestForUrl(url);

        this.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request);
        // OutputStreamWriter out = new
        // OutputStreamWriter(request.getOutputStream());
        OutputStream urlOutStream = request.getOutputStream();

        // If tracing is enabled, we generate the request in-memory so that we
        // can pass it along to the ITraceListener. Then we copy the stream to
        // the request stream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverRequest)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            PrintWriter writer = new PrintWriter(memoryStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);
            writer.flush();

            this.traceXml(TraceFlags.AutodiscoverRequest, memoryStream);
            // out.write(memoryStream.toString());
            // out.close();
            memoryStream.writeTo(urlOutStream);
            urlOutStream.flush();
            urlOutStream.close();
            memoryStream.close();
        } else {
            PrintWriter writer = new PrintWriter(urlOutStream);
            this.writeLegacyAutodiscoverRequest(emailAddress, settings, writer);

            /*  Flush Start */
            writer.flush();
            urlOutStream.flush();
            urlOutStream.close();
            /* Flush End */
        }
        request.executeRequest();
        request.getResponseCode();
        URI redirectUrl;
        OutParam<URI> outParam = new OutParam<URI>();
        if (this.tryGetRedirectionResponse(request, outParam)) {
            redirectUrl = outParam.getParam();
            settings.makeRedirectionResponse(redirectUrl);
            return settings;
        }
        InputStream serviceResponseStream = request.getInputStream();
        // If tracing is enabled, we read the entire response into a
        // MemoryStream so that we
        // can pass it along to the ITraceListener. Then we parse the response
        // from the
        // MemoryStream.
        if (this.isTraceEnabledFor(TraceFlags.AutodiscoverResponse)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

            while (true) {
                int data = serviceResponseStream.read();
                if (-1 == data) {
                    break;
                } else {
                    memoryStream.write(data);
                }
            }
            memoryStream.flush();

            this.traceResponse(request, memoryStream);
            ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
            EwsXmlReader reader = new EwsXmlReader(memoryStreamIn);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);

        } else {
            EwsXmlReader reader = new EwsXmlReader(serviceResponseStream);
            reader.read(new XmlNodeType(XmlNodeType.START_DOCUMENT));
            settings.loadFromXml(reader);
        }

        serviceResponseStream.close();
    } finally {
        if (request != null) {
            try {
                request.close();
            } catch (Exception e2) {
                // Ignore exception while closing the request.
            }
        }
    }

    return settings;
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static ByteArrayOutputStream ConvertHTMLtoPDF(String htmlin, String uri) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CYaHPConverter converter = new CYaHPConverter();

    try {//w w w.j  a v  a2  s  .  c  om
        List headerFooterList = new ArrayList();
        System.out.println("before conversion");
        Map properties = new HashMap();
        headerFooterList.add(new IHtmlToPdfTransformer.CHeaderFooter(
                "<table width=\"100%\"><tbody><tr><td align=\"left\">Generated with Gi9 Portal.</td><td align=\"right\">Page <pagenumber>/<pagecount></td></tr></tbody></table>",
                IHtmlToPdfTransformer.CHeaderFooter.HEADER));
        headerFooterList.add(new IHtmlToPdfTransformer.CHeaderFooter(
                " 2011 Produced by Gnomon Portal Solution", IHtmlToPdfTransformer.CHeaderFooter.FOOTER));

        properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
                IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
        converter.convertToPdf(htmlin, IHtmlToPdfTransformer.A4P, headerFooterList, uri, out, properties);
        System.out.println("after conversion");
        out.flush();
        out.close();
    } catch (Exception e) {
        _log.error("Error converting html to pdf");
        e.printStackTrace();
    }
    return out;
}