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:bftsmart.tom.core.Synchronizer.java

private void catch_up(int regency) {

    Logger.println("(Synchronizer.catch_up) verify STOPDATA info");
    ObjectOutputStream out = null;
    ByteArrayOutputStream bos = null;

    CertifiedDecision lastHighestCID = lcManager.getHighestLastCID(regency);

    int currentCID = lastHighestCID.getCID() + 1;
    HashSet<SignedObject> signedCollects = null;
    byte[] propose = null;
    int batchSize = -1;

    // normalize the collects and apply to them the predicate "sound"
    if (lcManager.sound(lcManager.selectCollects(regency, currentCID))) {

        Logger.println("(Synchronizer.catch_up) sound predicate is true");

        signedCollects = lcManager.getCollects(regency); // all original collects that the replica has received

        Decision dec = new Decision(-1); // the only purpose of this object is to obtain the batchsize,
                                         // using code inside of createPropose()

        propose = tom.createPropose(dec);
        batchSize = dec.batchSize;/*from  www.  jav a 2  s  .co m*/

        try { // serialization of the CATCH-UP message
            bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bos);

            out.writeObject(lastHighestCID);

            //TODO: Missing: serialization of the proof?
            out.writeObject(signedCollects);
            out.writeObject(propose);
            out.writeInt(batchSize);

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

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

            System.out.println("(Synchronizer.catch_up) sending SYNC message for regency " + regency);

            // send the CATCH-UP message
            communication.send(this.controller.getCurrentViewOtherAcceptors(), new LCMessage(
                    this.controller.getStaticConf().getProcessId(), TOMUtil.SYNC, regency, payload));

            finalise(regency, lastHighestCID, signedCollects, propose, batchSize, true);

        } 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);
            }
        }
    }
}

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

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

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

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

    // still not in the leader change phase?

    if (lcManager.getNextReg() == lcManager.getLastReg()) {

        Logger.println("(TOMLayer.triggerTimeout) initialize synch phase");

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

        int regency = lcManager.getNextReg();

        // 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

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

            if (lcManager.getCurrentRequestTimedOut() != null) {

                //TODO: If this is null, then there was no timeout. What to do?
                byte[] msgs = bb.makeBatch(lcManager.getCurrentRequestTimedOut(), 0, 0, controller);
                out.writeBoolean(true);
                out.writeObject(msgs);
            } else {
                out.writeBoolean(false);
            }

            byte[] payload = bos.toByteArray();

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

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

            // send STOP-message
            Logger.println("(TOMLayer.triggerTimeout) sending STOP message to install regency " + regency);
            communication.send(this.controller.getCurrentViewOtherAcceptors(), new LCMessage(
                    this.controller.getStaticConf().getProcessId(), TOMUtil.STOP, regency, payload));

        } 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);
            }
        }

        evaluateStops(regency); // evaluate STOP messages

    }

}

From source file:it.govpay.web.rs.dars.anagrafica.ruoli.RuoliHandler.java

@Override
public Ruolo creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Ruolo entry = null;//from  www . ja v  a  2  s.  c om

    String funzionalita_A_PPAId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_A_PPA.id");
    String domini_A_PPAId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_A_PPA.id");
    String diritti_A_PPAId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_A_PPA.id");

    String funzionalita_A_CONId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_A_CON.id");
    String domini_A_CONId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_A_CON.id");
    String diritti_A_CONId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_A_CON.id");

    String funzionalita_A_APPId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_A_APP.id");
    String domini_A_APPId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_A_APP.id");
    String diritti_A_APPId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_A_APP.id");

    String funzionalita_A_USRId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_A_USR.id");
    String domini_A_USRId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_A_USR.id");
    String diritti_A_USRId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_A_USR.id");

    String funzionalita_G_PAGId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_G_PAG.id");
    String domini_G_PAGId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_G_PAG.id");
    String diritti_G_PAGId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_G_PAG.id");
    String admin_G_PAGId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".admin_G_PAG.id");

    String funzionalita_G_RNDId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_G_RND.id");
    String domini_G_RNDId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_G_RND.id");
    String diritti_G_RNDId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_G_RND.id");

    String funzionalita_GDEId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_GDE.id");
    String domini_GDEId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".domini_GDE.id");
    String diritti_GDEId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".diritti_GDE.id");

    String funzionalita_MANId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_MAN.id");
    String funzionalita_STATId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".funzionalita_STAT.id");

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();

        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        classMap.put(domini_A_PPAId, Long.class);
        classMap.put(diritti_A_PPAId, Long.class);
        classMap.put(domini_A_CONId, Long.class);
        classMap.put(diritti_A_CONId, Long.class);
        classMap.put(domini_A_APPId, Long.class);
        classMap.put(diritti_A_APPId, Long.class);
        classMap.put(domini_A_USRId, Long.class);
        classMap.put(diritti_A_USRId, Long.class);
        classMap.put(domini_G_PAGId, Long.class);
        classMap.put(diritti_G_PAGId, Long.class);
        classMap.put(domini_G_RNDId, Long.class);
        classMap.put(diritti_G_RNDId, Long.class);
        classMap.put(domini_GDEId, Long.class);
        classMap.put(diritti_GDEId, Long.class);
        jsonConfig.setClassMap(classMap);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

        baos.flush();
        baos.close();

        JSONObject jsonObjectRuolo = JSONObject.fromObject(baos.toString());

        List<Acl> lstAclDominiFunzionalita_A_PPA = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_A_PPAId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_A_PPAId);
            // diritti
            Long diritti_A_PPA = jsonObjectRuolo.getLong(diritti_A_PPAId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Anagrafica_PagoPa);
                acl.setDiritti(diritti_A_PPA.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_A_PPA.add(acl);
                } else {
                    lstAclDominiFunzionalita_A_PPA.clear();
                    lstAclDominiFunzionalita_A_PPA.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_A_PPA
        jsonObjectRuolo.remove(funzionalita_A_PPAId);
        jsonObjectRuolo.remove(domini_A_PPAId);
        jsonObjectRuolo.remove(diritti_A_PPAId);

        List<Acl> lstAclDominiFunzionalita_A_CON = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_A_CONId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_A_CONId);
            // diritti
            Long diritti_A_CON = jsonObjectRuolo.getLong(diritti_A_CONId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Anagrafica_Contabile);
                acl.setDiritti(diritti_A_CON.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_A_CON.add(acl);
                } else {
                    lstAclDominiFunzionalita_A_CON.clear();
                    lstAclDominiFunzionalita_A_CON.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_A_CON
        jsonObjectRuolo.remove(funzionalita_A_CONId);
        jsonObjectRuolo.remove(domini_A_CONId);
        jsonObjectRuolo.remove(diritti_A_CONId);

        List<Acl> lstAclDominiFunzionalita_A_APP = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_A_APPId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_A_APPId);
            // diritti
            Long diritti_A_APP = jsonObjectRuolo.getLong(diritti_A_APPId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Anagrafica_Applicazioni);
                acl.setDiritti(diritti_A_APP.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_A_APP.add(acl);
                } else {
                    lstAclDominiFunzionalita_A_APP.clear();
                    lstAclDominiFunzionalita_A_APP.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_A_APP
        jsonObjectRuolo.remove(funzionalita_A_APPId);
        jsonObjectRuolo.remove(domini_A_APPId);
        jsonObjectRuolo.remove(diritti_A_APPId);

        List<Acl> lstAclDominiFunzionalita_A_USR = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_A_USRId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_A_USRId);
            // diritti
            Long diritti_A_USR = jsonObjectRuolo.getLong(diritti_A_USRId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Anagrafica_Utenti);
                acl.setDiritti(diritti_A_USR.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_A_USR.add(acl);
                } else {
                    lstAclDominiFunzionalita_A_USR.clear();
                    lstAclDominiFunzionalita_A_USR.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_A_USR
        jsonObjectRuolo.remove(funzionalita_A_USRId);
        jsonObjectRuolo.remove(domini_A_USRId);
        jsonObjectRuolo.remove(diritti_A_USRId);

        List<Acl> lstAclDominiFunzionalita_G_PAG = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_G_PAGId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_G_PAGId);
            boolean admin = jsonObjectRuolo.getBoolean(admin_G_PAGId);
            // diritti
            Long diritti_G_PAG = jsonObjectRuolo.getLong(diritti_G_PAGId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Gestione_Pagamenti);
                acl.setDiritti(diritti_G_PAG.intValue());
                acl.setAdmin(admin);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_G_PAG.add(acl);
                } else {
                    lstAclDominiFunzionalita_G_PAG.clear();
                    lstAclDominiFunzionalita_G_PAG.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_G_PAG
        jsonObjectRuolo.remove(funzionalita_G_PAGId);
        jsonObjectRuolo.remove(domini_G_PAGId);
        jsonObjectRuolo.remove(diritti_G_PAGId);
        jsonObjectRuolo.remove(admin_G_PAGId);

        List<Acl> lstAclDominiFunzionalita_G_RND = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_G_RNDId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_G_RNDId);
            // diritti
            Long diritti_G_RND = jsonObjectRuolo.getLong(diritti_G_RNDId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Gestione_Rendicontazioni);
                acl.setDiritti(diritti_G_RND.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_G_RND.add(acl);
                } else {
                    lstAclDominiFunzionalita_G_RND.clear();
                    lstAclDominiFunzionalita_G_RND.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_G_RND
        jsonObjectRuolo.remove(funzionalita_G_RNDId);
        jsonObjectRuolo.remove(domini_G_RNDId);
        jsonObjectRuolo.remove(diritti_G_RNDId);

        List<Acl> lstAclDominiFunzionalita_GDE = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_GDEId)) {
            JSONArray jsonDomini = jsonObjectRuolo.getJSONArray(domini_GDEId);
            // diritti
            Long diritti_GDE = jsonObjectRuolo.getLong(diritti_GDEId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.Giornale_Eventi);
                acl.setDiritti(diritti_GDE.intValue());
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiFunzionalita_GDE.add(acl);
                } else {
                    lstAclDominiFunzionalita_GDE.clear();
                    lstAclDominiFunzionalita_GDE.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte Funzionalita_GDE
        jsonObjectRuolo.remove(funzionalita_GDEId);
        jsonObjectRuolo.remove(domini_GDEId);
        jsonObjectRuolo.remove(diritti_GDEId);

        List<Acl> lstAclDominiFunzionalita_MAN = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_MANId)) {
            int diritti_MAN = Ruolo.DIRITTI_LETTURA;
            Acl acl = new Acl();
            acl.setTipo(Tipo.DOMINIO);
            acl.setServizio(Servizio.Manutenzione);
            acl.setDiritti(diritti_MAN);
            lstAclDominiFunzionalita_MAN.add(acl);
        }
        // rimuovo gli oggetti della parte Funzionalita_MAN
        jsonObjectRuolo.remove(funzionalita_MANId);

        List<Acl> lstAclDominiFunzionalita_STAT = new ArrayList<Acl>();

        if (jsonObjectRuolo.getBoolean(funzionalita_STATId)) {
            int diritti_STAT = Ruolo.DIRITTI_LETTURA;
            Acl acl = new Acl();
            acl.setTipo(Tipo.DOMINIO);
            acl.setServizio(Servizio.Statistiche);
            acl.setDiritti(diritti_STAT);
            lstAclDominiFunzionalita_STAT.add(acl);
        }
        // rimuovo gli oggetti della parte Funzionalita_STAT
        jsonObjectRuolo.remove(funzionalita_STATId);

        jsonConfig.setRootClass(Ruolo.class);
        entry = (Ruolo) JSONObject.toBean(jsonObjectRuolo, jsonConfig);

        // colleziono gli acl
        entry.setAcls(lstAclDominiFunzionalita_A_PPA);
        entry.getAcls().addAll(lstAclDominiFunzionalita_A_CON);
        entry.getAcls().addAll(lstAclDominiFunzionalita_A_APP);
        entry.getAcls().addAll(lstAclDominiFunzionalita_A_USR);
        entry.getAcls().addAll(lstAclDominiFunzionalita_G_PAG);
        entry.getAcls().addAll(lstAclDominiFunzionalita_G_RND);
        entry.getAcls().addAll(lstAclDominiFunzionalita_GDE);
        entry.getAcls().addAll(lstAclDominiFunzionalita_MAN);
        entry.getAcls().addAll(lstAclDominiFunzionalita_STAT);

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.java

/**
 * Read response from the input stream, converting to MD5 digest if the useMD5 property is set.
 * <p>/*from   w w w  . j a  va  2 s. c o  m*/
 * For the MD5 case, the result byte count is set to the size of the original response.
 * <p>
 * Closes the inputStream
 *
 * @param sampleResult sample to store information about the response into
 * @param in input stream from which to read the response
 * @param length expected input length or zero
 * @return the response or the MD5 of the response
 * @throws IOException if reading the result fails
 */
public byte[] readResponse(SampleResult sampleResult, InputStream in, int length) throws IOException {
    try {
        byte[] readBuffer = new byte[8192]; // 8kB is the (max) size to have the latency ('the first packet')
        int bufferSize = 32;// Enough for MD5

        MessageDigest md = null;
        boolean asMD5 = useMD5();
        if (asMD5) {
            try {
                md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
            } catch (NoSuchAlgorithmException e) {
                log.error("Should not happen - could not find MD5 digest", e);
                asMD5 = false;
            }
        } else {
            if (length <= 0) {// may also happen if long value > int.max
                bufferSize = 4 * 1024;
            } else {
                bufferSize = length;
            }
        }
        ByteArrayOutputStream w = new ByteArrayOutputStream(bufferSize);
        int bytesRead = 0;
        int totalBytes = 0;
        boolean first = true;
        while ((bytesRead = in.read(readBuffer)) > -1) {
            if (first) {
                sampleResult.latencyEnd();
                first = false;
            }
            if (asMD5 && md != null) {
                md.update(readBuffer, 0, bytesRead);
                totalBytes += bytesRead;
            } else {
                w.write(readBuffer, 0, bytesRead);
            }
        }
        if (first) { // Bug 46838 - if there was no data, still need to set latency
            sampleResult.latencyEnd();
        }
        in.close();
        w.flush();
        if (asMD5 && md != null) {
            byte[] md5Result = md.digest();
            w.write(JOrphanUtils.baToHexBytes(md5Result));
            sampleResult.setBytes(totalBytes);
        }
        w.close();
        return w.toByteArray();
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:fi.foyt.fni.materials.MaterialController.java

private org.w3c.dom.Document tidyForPdf(String title, String bodyContent)
        throws ParserConfigurationException, IOException, SAXException {
    String documentHtml = HtmlUtils.getAsHtmlText(title, bodyContent);
    String cleanedHtml = null;//from w  w  w.ja v a  2s.co  m

    ByteArrayOutputStream tidyStream = new ByteArrayOutputStream();
    try {
        Tidy tidy = new Tidy();
        tidy.setInputEncoding("UTF-8");
        tidy.setOutputEncoding("UTF-8");
        tidy.setShowWarnings(true);
        tidy.setNumEntities(false);
        tidy.setXmlOut(true);
        tidy.setXHTML(true);

        cleanedHtml = HtmlUtils.printDocument(tidy.parseDOM(new StringReader(documentHtml), null));
    } catch (Exception e) {
        throw e;
    } finally {
        tidyStream.flush();
        tidyStream.close();
    }

    InputStream documentStream = new ByteArrayInputStream(cleanedHtml.getBytes("UTF-8"));
    try {

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(false);
        builderFactory.setValidating(false);
        builderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
        builderFactory.setFeature("http://xml.org/sax/features/validation", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        return builder.parse(documentStream);

    } finally {
        documentStream.close();
    }
}

From source file:com.techventus.server.voice.Voice.java

/**
 * Downloads a voicemail./*from w w w .  j a  v  a2s  .com*/
 *
 * @param msgID the msg id
 * @return byte output stream
 * @throws IOException Signals that an I/O exception has occurred.
 */
public ByteArrayOutputStream downloadVoicemail(String msgID) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        URL u = new URL(voicemailDownloadURLString + msgID);
        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
        huc.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
        huc.setRequestProperty("User-agent", USER_AGENT);
        huc.setRequestMethod("GET");
        huc.connect();
        InputStream is = huc.getInputStream();

        if (huc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            byte[] buffer = new byte[4096];
            int bytes = 0;

            while (true) {
                bytes = is.read(buffer);
                if (bytes <= 0)
                    break;
                outputStream.write(buffer, 0, bytes);
            }

            outputStream.flush();
        }

        huc.disconnect();

        return outputStream;
    } catch (IOException e) {
        System.out.println("Exception\n" + e);
    }

    return null;
}

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

private void evaluateStops(int nextReg) {

    boolean enterFirstPhase = this.controller.getStaticConf().isBFT();
    boolean condition = false;
    ObjectOutputStream out = null;
    ByteArrayOutputStream bos = null;

    // pass to the leader change phase if more than f messages have been received already
    if (enterFirstPhase && lcManager.getStopsSize(nextReg) > this.controller.getQuorumF()
            && lcManager.getNextReg() == lcManager.getLastReg()) {

        Logger.println("(TOMLayer.evaluateStops) initialize synch phase");
        requestsTimer.Enabled(false);//from  www  . j  a  v  a 2s  .  c  o  m
        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

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

            if (lcManager.getCurrentRequestTimedOut() != null) {

                //TODO: If this is null, there was no timeout. What shall be done then?
                out.writeBoolean(true);
                byte[] msgs = bb.makeBatch(lcManager.getCurrentRequestTimedOut(), 0, 0, controller);
                out.writeObject(msgs);
            } else {
                out.writeBoolean(false);
            }

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

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

            // send message STOP
            Logger.println("(TOMLayer.evaluateStops) sending STOP message to install regency " + regency);
            communication.send(this.controller.getCurrentViewOtherAcceptors(), new LCMessage(
                    this.controller.getStaticConf().getProcessId(), TOMUtil.STOP, regency, payload));

        } 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) > this.controller.getCertificateQuorum()
                && lcManager.getNextReg() > lcManager.getLastReg();
    } else {
        condition = (lcManager.getStopsSize(nextReg) > this.controller.getQuorumAccept()
                && lcManager.getNextReg() > lcManager.getLastReg());
    }
    // May I proceed to the synchronization phase?
    //if (lcManager.getStopsSize(nextReg) > this.reconfManager.getQuorum2F() && lcManager.getNextReg() > lcManager.getLastReg()) {
    if (condition) {

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

        int regency = lcManager.getLastReg();

        // avoid a memory leak
        lcManager.removeStops(nextReg);

        requestsTimer.Enabled(true);
        requestsTimer.setShortTimeout(-1);
        //requestsTimer.setTimeout(requestsTimer.getTimeout() * 2);
        requestsTimer.startTimer();

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

        lm.setNewLeader(leader);

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

            try { // serialize content of the SYNC message

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

                if (last > -1) { // content of the last decided eid

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

                    ////// ISTO E PARA APANHAR UM BUG!!!!!
                    if (exec.getDecisionRound() == null || exec.getDecisionRound().propValue == null) {

                        System.out.println("[DEBUG INFO FOR LAST EID #1]");

                        if (exec.getDecisionRound() == null) {
                            System.out.println("No decision round for eid " + last);
                        } else {
                            System.out.println(
                                    "round for eid: " + last + ": " + exec.getDecisionRound().toString());

                            if (exec.getDecisionRound().propValue == null)
                                System.out.println("No propose for eid " + last);
                            else {
                                System.out.println("Propose hash for eid " + last + ": " + Base64
                                        .encodeBase64String(computeHash(exec.getDecisionRound().propValue)));
                            }
                        }

                        return;
                    }

                    byte[] decision = exec.getDecisionRound().propValue;
                    Set<PaxosMessage> proof = exec.getDecisionRound().getProof();

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

                }

                else
                    out.writeBoolean(false);

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

                    Execution exec = execManager.getExecution(in);

                    TimestampValuePair quorumWrites = exec.getQuorumWrites();
                    HashSet<TimestampValuePair> writeSet = exec.getWriteSet();

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

                    SignedObject signedCollect = sign(collect);

                    out.writeObject(signedCollect);

                }

                else {

                    CollectData collect = new CollectData(this.controller.getStaticConf().getProcessId(), -1,
                            new TimestampValuePair(-1, new byte[0]), new HashSet<TimestampValuePair>());

                    SignedObject signedCollect = 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;

                Logger.println("(TOMLayer.evaluateStops) 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);
                }
            }

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

            Logger.println("(TOMLayer.evaluateStops) I'm the leader for this new regency");
            LastEidData lastData = null;
            CollectData collect = null;

            if (last > -1) { // content of the last decided eid 
                Execution exec = execManager.getExecution(last);
                //byte[] decision = exec.getLearner().getDecision();

                ////// ISTO E PARA APANHAR UM BUG!!!!!
                if (exec.getDecisionRound() == null || exec.getDecisionRound().propValue == null) {

                    System.out.println("[DEBUG INFO FOR LAST EID #2]");

                    if (exec.getDecisionRound() == null)
                        System.out.println("No decision round for eid " + last);
                    else
                        System.out
                                .println("round for eid: " + last + ": " + exec.getDecisionRound().toString());
                    if (exec.getDecisionRound().propValue == null)
                        System.out.println("No propose for eid " + last);
                    else {
                        System.out.println("Propose hash for eid " + last + ": "
                                + Base64.encodeBase64String(computeHash(exec.getDecisionRound().propValue)));
                    }

                    return;
                }

                byte[] decision = exec.getDecisionRound().propValue;
                Set<PaxosMessage> proof = exec.getDecisionRound().getProof();

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

            } else {
                lastData = new LastEidData(this.controller.getStaticConf().getProcessId(), last, null, null);
            }
            lcManager.addLastEid(regency, lastData);

            if (in > -1) { // content of eid being executed
                Execution exec = execManager.getExecution(in);

                TimestampValuePair quorumWrites = exec.getQuorumWrites();
                HashSet<TimestampValuePair> writeSet = exec.getWriteSet();

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

            } else {
                collect = new CollectData(this.controller.getStaticConf().getProcessId(), -1,
                        new TimestampValuePair(-1, new byte[0]), new HashSet<TimestampValuePair>());
            }

            SignedObject signedCollect = sign(collect);

            lcManager.addCollect(regency, signedCollect);
        }

    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPSamplerBaseClassifier.java

/**
 * Read response from the input stream, converting to MD5 digest if the
 * useMD5 property is set.//from w  w w  .  j  ava  2s .c o m
 * 
 * For the MD5 case, the result byte count is set to the size of the
 * original response.
 * 
 * Closes the inputStream
 * 
 * @param sampleResult
 * @param in
 *            input stream
 * @param length
 *            expected input length or zero
 * @return the response or the MD5 of the response
 * @throws IOException
 */
public byte[] readResponse(SampleResult sampleResult, InputStream in, int length) throws IOException {
    try {
        byte[] readBuffer = new byte[8192]; // 8kB is the (max) size to have
        // the latency ('the first
        // packet')
        int bufferSize = 32;// Enough for MD5

        MessageDigest md = null;
        boolean asMD5 = useMD5();
        if (asMD5) {
            try {
                md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
            } catch (NoSuchAlgorithmException e) {
                log.error("Should not happen - could not find MD5 digest", e);
                asMD5 = false;
            }
        } else {
            if (length <= 0) {// may also happen if long value > int.max
                bufferSize = 4 * 1024;
            } else {
                bufferSize = length;
            }
        }
        ByteArrayOutputStream w = new ByteArrayOutputStream(bufferSize);
        int bytesRead = 0;
        int totalBytes = 0;
        boolean first = true;
        while ((bytesRead = in.read(readBuffer)) > -1) {
            if (first) {
                sampleResult.latencyEnd();
                first = false;
            }
            if (asMD5 && md != null) {
                md.update(readBuffer, 0, bytesRead);
                totalBytes += bytesRead;
            } else {
                w.write(readBuffer, 0, bytesRead);
            }
        }
        if (first) { // Bug 46838 - if there was no data, still need to set
                     // latency
            sampleResult.latencyEnd();
        }
        in.close();
        w.flush();
        if (asMD5 && md != null) {
            byte[] md5Result = md.digest();
            w.write(JOrphanUtils.baToHexBytes(md5Result));
            sampleResult.setBytes(totalBytes);
        }
        w.close();
        return w.toByteArray();
    } finally {
        IOUtils.closeQuietly(in);
    }
}