Example usage for java.io ByteArrayOutputStream toString

List of usage examples for java.io ByteArrayOutputStream toString

Introduction

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

Prototype

@Deprecated
public synchronized String toString(int hibyte) 

Source Link

Document

Creates a newly allocated string.

Usage

From source file:com.meetingninja.csse.database.ProjectDatabaseAdapter.java

public static void updateProject(Project p) throws IOException {
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Title
    jgen.writeStartObject();/*from w w w  .j a v  a2s.  co  m*/
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.TITLE);
    jgen.writeStringField("value", p.getProjectTitle());
    jgen.writeEndObject();
    jgen.close();
    String payloadTitle = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.MEETINGS);
    jgen.writeArrayFieldStart("value");
    for (Meeting meeting : p.getMeetings()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Meeting.ID, meeting.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadMeetings = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.NOTES);
    jgen.writeArrayFieldStart("value");
    for (Note note : p.getNotes()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Note.ID, note.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadNotes = json.toString("UTF8");
    ps.close();

    json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    ps = new PrintStream(json);
    jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Project members
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Project.ID, p.getProjectID());
    jgen.writeStringField("field", Keys.Project.MEMBERS);
    jgen.writeArrayFieldStart("value");
    for (User member : p.getMembers()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.User.ID, member.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();
    String payloadMembers = json.toString("UTF8");
    ps.close();

    // Establish connection
    updateHelper(payloadTitle);
    updateHelper(payloadMeetings);
    updateHelper(payloadNotes);
    System.out.println(updateHelper(payloadMembers));

}

From source file:com.seleniumtests.driver.CustomEventFiringWebDriver.java

/**
 * Returns a Base64 string of the desktop
 * @param driverMode//from www .ja v  a  2  s  .c  o m
 * @param gridConnector
 * @return
 */
public static String captureDesktopToBase64String(DriverMode driverMode, SeleniumGridConnector gridConnector) {
    if (driverMode == DriverMode.LOCAL) {
        BufferedImage bi = captureDesktopToBuffer();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputStream b64 = new Base64OutputStream(os);
        try {
            ImageIO.write(bi, "png", b64);
            return os.toString("UTF-8");
        } catch (IOException e) {
            return "";
        }
    } else if (driverMode == DriverMode.GRID && gridConnector != null) {
        return gridConnector.captureDesktopToBuffer();
    } else {
        throw new ScenarioException("driver supports captureDesktopToBase64String only in local and grid mode");
    }
}

From source file:es.uvigo.darwin.jmodeltest.io.HtmlReporter.java

public static void buildReport(ApplicationOptions options, Model models[], File mOutputFile,
        TreeSummary summary) {/*from  w  w  w.j  ava 2s  .c o m*/

    File outputFile;
    if (mOutputFile != null) {
        if (!(mOutputFile.getName().endsWith(".htm") || mOutputFile.getName().endsWith(".html"))) {
            outputFile = new File(mOutputFile.getAbsolutePath() + ".html");
        } else {
            outputFile = mOutputFile;
        }
    } else {
        outputFile = new File(LOG_DIR.getPath() + File.separator + options.getInputFile().getName()
                + ".jmodeltest." + options.getExecutionName() + ".html");
    }

    // Add the values in the datamodel
    datamodel = new HashMap<String, Object>();
    java.util.Date current_time = new java.util.Date();
    datamodel.put("date", current_time.toString());
    datamodel.put("system",
            System.getProperty("os.name") + " " + System.getProperty("os.version") + ", arch: "
                    + System.getProperty("os.arch") + ", bits: " + System.getProperty("sun.arch.data.model")
                    + ", numcores: " + Runtime.getRuntime().availableProcessors());

    fillInWithOptions(options);
    fillInWithSortedModels(models);
    datamodel.put("isTopologiesSummary", summary != null ? new Integer(1) : new Integer(0));
    if (summary != null) {
        fillInWithTopologies(summary, options);
    }

    if (options.doAIC) {
        Collection<Map<String, String>> aicModels = new ArrayList<Map<String, String>>();
        Map<String, String> bestAicModel = new HashMap<String, String>();
        fillInWIthInformationCriterion(ModelTest.getMyAIC(), aicModels, bestAicModel);
        datamodel.put("aicModels", aicModels);
        datamodel.put("bestAicModel", bestAicModel);
        datamodel.put("aicConfidenceCount", ModelTest.getMyAIC().getConfidenceModels().size());
        StringBuffer aicConfModels = new StringBuffer();
        for (Model model : ModelTest.getMyAIC().getConfidenceModels())
            aicConfModels.append(model.getName() + " ");
        datamodel.put("aicConfidenceList", aicConfModels.toString());
        if (options.writePAUPblock) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            TextOutputStream strOutput = new TextOutputStream(ps);
            ModelTest.WritePaupBlock(strOutput, "AIC", ModelTest.getMyAIC().getMinModel());
            try {
                String pblock = baos.toString("UTF8");
                pblock = pblock.replaceAll("\n", "<br/>");
                datamodel.put("aicPaup", pblock);
            } catch (UnsupportedEncodingException e) {
            }

        }
        buildChart(outputFile, ModelTest.getMyAIC());
        datamodel.put("aicEuImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_eu_AIC.png");
        datamodel.put("aicRfImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_rf_AIC.png");
    }

    if (options.doAICc) {
        Collection<Map<String, String>> aiccModels = new ArrayList<Map<String, String>>();
        Map<String, String> bestAiccModel = new HashMap<String, String>();
        fillInWIthInformationCriterion(ModelTest.getMyAICc(), aiccModels, bestAiccModel);
        datamodel.put("aiccModels", aiccModels);
        datamodel.put("bestAiccModel", bestAiccModel);
        datamodel.put("aiccConfidenceCount", ModelTest.getMyAICc().getConfidenceModels().size());
        StringBuffer aiccConfModels = new StringBuffer();
        for (Model model : ModelTest.getMyAICc().getConfidenceModels())
            aiccConfModels.append(model.getName() + " ");
        datamodel.put("aiccConfidenceList", aiccConfModels.toString());
        if (options.writePAUPblock) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            TextOutputStream strOutput = new TextOutputStream(ps);
            ModelTest.WritePaupBlock(strOutput, "AICc", ModelTest.getMyAICc().getMinModel());
            try {
                String pblock = baos.toString("UTF8");
                pblock = pblock.replaceAll("\n", "<br/>");
                datamodel.put("aiccPaup", pblock);
            } catch (UnsupportedEncodingException e) {
            }

        }
        buildChart(outputFile, ModelTest.getMyAICc());
        datamodel.put("aiccEuImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_eu_AICc.png");
        datamodel.put("aiccRfImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_rf_AICc.png");
    }

    if (options.doBIC) {
        Collection<Map<String, String>> bicModels = new ArrayList<Map<String, String>>();
        Map<String, String> bestBicModel = new HashMap<String, String>();
        fillInWIthInformationCriterion(ModelTest.getMyBIC(), bicModels, bestBicModel);
        datamodel.put("bicModels", bicModels);
        datamodel.put("bestBicModel", bestBicModel);
        datamodel.put("bicConfidenceCount", ModelTest.getMyBIC().getConfidenceModels().size());
        StringBuffer bicConfModels = new StringBuffer();
        for (Model model : ModelTest.getMyBIC().getConfidenceModels())
            bicConfModels.append(model.getName() + " ");
        datamodel.put("bicConfidenceList", bicConfModels.toString());
        if (options.writePAUPblock) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            TextOutputStream strOutput = new TextOutputStream(ps);
            ModelTest.WritePaupBlock(strOutput, "BIC", ModelTest.getMyBIC().getMinModel());
            try {
                String pblock = baos.toString("UTF8");
                pblock = pblock.replaceAll("\n", "<br/>");
                datamodel.put("bicPaup", pblock);
            } catch (UnsupportedEncodingException e) {
            }

        }
        buildChart(outputFile, ModelTest.getMyBIC());
        datamodel.put("bicEuImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_eu_BIC.png");
        datamodel.put("bicRfImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_rf_BIC.png");
    }

    if (options.doDT) {
        Collection<Map<String, String>> dtModels = new ArrayList<Map<String, String>>();
        Map<String, String> bestDtModel = new HashMap<String, String>();
        fillInWIthInformationCriterion(ModelTest.getMyDT(), dtModels, bestDtModel);
        datamodel.put("dtModels", dtModels);
        datamodel.put("bestDtModel", bestDtModel);
        datamodel.put("dtConfidenceCount", ModelTest.getMyDT().getConfidenceModels().size());
        StringBuffer dtConfModels = new StringBuffer();
        for (Model model : ModelTest.getMyDT().getConfidenceModels())
            dtConfModels.append(model.getName() + " ");
        datamodel.put("dtConfidenceList", dtConfModels.toString());
        if (options.writePAUPblock) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            TextOutputStream strOutput = new TextOutputStream(ps);
            ModelTest.WritePaupBlock(strOutput, "DT", ModelTest.getMyDT().getMinModel());
            try {
                String pblock = baos.toString("UTF8");
                pblock = pblock.replaceAll("\n", "<br/>");
                datamodel.put("dtPaup", pblock);
            } catch (UnsupportedEncodingException e) {
            }

        }
        buildChart(outputFile, ModelTest.getMyDT());
        datamodel.put("dtEuImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_eu_DT.png");
        datamodel.put("dtRfImagePath",
                IMAGES_DIR.getName() + File.separator + outputFile.getName() + "_rf_DT.png");
    }

    datamodel.put("doAICAveragedPhylogeny",
            ModelTest.getConsensusAIC() != null ? new Integer(1) : new Integer(0));
    if (ModelTest.getConsensusAIC() != null) {
        datamodel.put("aicConsensusTree",
                TreeUtilities.toNewick(ModelTest.getConsensusAIC().getConsensus(), true, true, true));
        datamodel.put("consensusType", ModelTest.getConsensusAIC().getConsensusType());
    }
    datamodel.put("doAICcAveragedPhylogeny",
            ModelTest.getConsensusAICc() != null ? new Integer(1) : new Integer(0));
    if (ModelTest.getConsensusAICc() != null) {
        datamodel.put("aiccConsensusTree",
                TreeUtilities.toNewick(ModelTest.getConsensusAICc().getConsensus(), true, true, true));
        datamodel.put("consensusType", ModelTest.getConsensusAICc().getConsensusType());
    }
    datamodel.put("doBICAveragedPhylogeny",
            ModelTest.getConsensusBIC() != null ? new Integer(1) : new Integer(0));
    if (ModelTest.getConsensusBIC() != null) {
        datamodel.put("bicConsensusTree",
                TreeUtilities.toNewick(ModelTest.getConsensusBIC().getConsensus(), true, true, true));
        datamodel.put("consensusType", ModelTest.getConsensusBIC().getConsensusType());
    }
    datamodel.put("doDTAveragedPhylogeny",
            ModelTest.getConsensusDT() != null ? new Integer(1) : new Integer(0));
    if (ModelTest.getConsensusDT() != null) {
        datamodel.put("dtConsensusTree",
                TreeUtilities.toNewick(ModelTest.getConsensusDT().getConsensus(), true, true, true));
        datamodel.put("consensusType", ModelTest.getConsensusDT().getConsensusType());
    }

    // Process the template using FreeMarker
    try {
        freemarkerDo(datamodel, "index.html", outputFile);
    } catch (Exception e) {
        System.out.println("There was a problem building the html log files: " + e.getLocalizedMessage());
    }

}

From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static JsonNode update(String agendaID, Map<String, String> key_values)
        throws JsonGenerationException, IOException, InterruptedException {
    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);

    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    for (String key : key_values.keySet()) {
        jgen.flush();/*from  www  .j  a  v  a 2 s.  c o  m*/
        // Build JSON Object
        jgen.writeStartObject();
        jgen.writeStringField(Keys.Agenda.ID, agendaID);
        jgen.writeStringField("field", key);
        jgen.writeStringField("value", key_values.get(key));
        jgen.writeEndObject();
        jgen.writeRaw("\f"); // write a form-feed to separate the payloads
    }

    jgen.close();
    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();
    // The backend can only update a single field at a time
    String[] payloads = payload.split("\f\\s*"); // split at each form-feed
    Thread t = new Thread(new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.getLocalizedMessage();
            }
        }
    }));
    String response = "";
    for (String p : payloads) {
        t.run();
        response = updateHelper(p);
    }
    return MAPPER.readTree(response);
}

From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java

public static String createNote(Note n) throws Exception {
    // Server URL setup
    String _url = getBaseUri().build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    //addRequestHeader(conn, true);

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();/*from w ww  . j  a v a 2  s.  c o m*/
    jgen.writeStringField(Keys.Note.CREATED_BY, n.getCreatedBy());
    jgen.writeStringField(Keys.Note.TITLE, n.getTitle());
    jgen.writeStringField(Keys.Note.DESC, n.getDescription());
    jgen.writeStringField(Keys.Note.CONTENT, n.getContent());
    jgen.writeStringField(Keys.Note.UPDATED, n.getDateCreated());
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    Log.d("CREATENOTE_payload", payload);
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);
    Log.d("CREATENOTE_response", response);

    String ID = "";
    if (!response.isEmpty()) {
        JsonNode tree = MAPPER.readTree(response);
        if (!tree.has(Keys.Note.ID))
            ID = "-1";
        else
            ID = tree.get(Keys.Note.ID).asText();
    }

    conn.disconnect();
    return ID;
}

From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java

public static Group createGroup(Group g) throws IOException, MalformedURLException {
    // Server URL setup
    String _url = getBaseUri().build().toString();

    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    addRequestHeader(conn, true);/*from  w w w.  ja  va  2 s.  c om*/

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Group.TITLE, g.getGroupTitle());
    jgen.writeArrayFieldStart(Keys.Group.MEMBERS);
    for (User member : g.getMembers()) {
        jgen.writeStartObject();
        jgen.writeStringField(Keys.User.ID, member.getID());
        jgen.writeEndObject();

    }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // prepare to get the id of the created Meeting
    // Map<String, String> responseMap = new HashMap<String, String>();

    /*
     * result should get valid={"meetingID":"##"}
     */
    String result = new String();
    if (!response.isEmpty()) {
        // responseMap = MAPPER.readValue(response,
        // new TypeReference<HashMap<String, String>>() {
        // });
        JsonNode groupNode = MAPPER.readTree(response);
        if (!groupNode.has(Keys.Group.ID)) {
            result = "invalid";
        } else
            result = groupNode.get(Keys.Group.ID).asText();
    }

    if (!result.equalsIgnoreCase("invalid"))
        g.setID(result);

    conn.disconnect();
    return g;
}

From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static Agenda createAgenda(Agenda create) throws IOException {
    Agenda newAgenda = new Agenda(create);
    // Server URL setup
    String _url = getBaseUri().build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, true);/*  w  ww.  j  a  v  a  2s  .com*/

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject(); // start agenda
    jgen.writeStringField(Keys.Agenda.TITLE, create.getTitle());
    jgen.writeStringField(Keys.Agenda.MEETING, create.getAttachedMeetingID());
    jgen.writeArrayFieldStart(Keys.Agenda.TOPIC); // start topics
    MAPPER.writeValue(jgen, create.getTopics()); // recursively does
    // subtopics
    jgen.writeEndArray(); // end topics
    jgen.writeEndObject(); // end agenda
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    newAgenda = parseAgenda(MAPPER.readTree(response));
    return newAgenda;
}

From source file:com.oculusinfo.tile.util.AvroJSONConverter.java

/**
 * Convert an Avro input stream into a JSON object
 * //from w  w  w  .jav a  2  s  .  c  o m
 * @param stream The input data
 * @return A JSON representation of the input data
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject convert(InputStream stream) throws IOException, JSONException {
    SeekableInput input = new SeekableByteArrayInput(IOUtils.toByteArray(stream));
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    // Conversion code taken from org.apache.avro.tool.DataFileReadTool
    GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
    FileReader<Object> fileReader = DataFileReader.openReader(input, reader);
    try {
        Schema schema = fileReader.getSchema();
        DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
        JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, output);
        for (Object datum : fileReader) {
            encoder.configure(output);
            writer.write(datum, encoder);
            encoder.flush();
            // For some reason, we only contain one record, but the 
            // decoding thinks we contain more and fails; so just break 
            // after our first one.
            break;
        }
        output.flush();
    } finally {
        fileReader.close();
    }
    String jsonString = output.toString("UTF-8");
    return new JSONObject(jsonString);
}

From source file:ar.com.zauber.commons.message.message.templates.AbstractMessagePartTemplate.java

/** Creates the AbstractMessagePartTemplate. */
public AbstractMessagePartTemplate(final Resource content, final String contentType, final String charset) {
    Validate.notNull(content);//from   w w  w. jav  a2  s  .c om
    Validate.notEmpty(contentType);

    final ByteArrayOutputStream os = copyResource(content);
    try {
        this.content = os.toString(charset);
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
    this.contentType = contentType;
}

From source file:org.webpda.server.core.servermessage.PingMessage.java

@Override
public String createJson() throws JsonProcessingException {
    try {/*from   w  w  w .j  ava  2  s  .c  om*/
        JsonGenerator jg = createJsonGenerator();
        jg.writeNumberField("Count", count);

        jg.writeEndObject();
        jg.close();
        ByteArrayOutputStream outputStream = (ByteArrayOutputStream) jg.getOutputTarget();
        String s = outputStream.toString(Constants.CHARSET);
        outputStream.close();
        return s;
    } catch (Exception e) {
        LoggerUtil.getLogger().log(Level.SEVERE, "Failed to create json.", e);
    }

    return null;
}