Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.zanata.adapter.TSAdapterTest.java

@Test
public void testTranslatedTSDocument() throws Exception {
    Resource resource = parseTestFile("test-ts-untranslated.ts");
    Map<String, TextFlowTarget> translations = new HashMap<>();
    addTranslation(translations, resource.getTextFlows().get(0).getId(), "Found metalkcta",
            ContentState.Approved);/*from  w  w w.jav a 2 s  . com*/
    addTranslation(translations, resource.getTextFlows().get(1).getId(), "Tbad metalkcta",
            ContentState.Translated);
    File originalFile = getTestFile("test-ts-untranslated.ts");
    LocaleId localeId = new LocaleId("en");
    OutputStream outputStream = new ByteArrayOutputStream();
    try (TsFilter tsFilter = new TsFilter(); IFilterWriter writer = tsFilter.createFilterWriter()) {
        writer.setOptions(localeId, Charsets.UTF_8.name());
        writer.setOutput(outputStream);
        getAdapter().generateTranslatedFile(originalFile.toURI(), translations, localeId, writer,
                Optional.absent());
    }
    assertThat(outputStream.toString()).isEqualTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE TS []>\n"
            + "<TS version=\"2.1\" sourcelanguage=\"en\" language=\"sv\">\n" + "<message>\n"
            + "    <source>First source</source>\n"
            + "<translation type=\"unfinished\" variants=\"no\">Found metalkcta</translation>\n"
            + "  </message><message>\n" + "      <source>Second source</source>\n"
            + "<translation type=\"unfinished\" variants=\"no\">Tbad metalkcta</translation>\n"
            + "    </message>\n" + "</TS>\n");
}

From source file:com.keybox.manage.action.AuthKeysAction.java

/**
 * generates public private key from passphrase
 *  //from   w  w w  .j  a va 2s. c  o  m
 * @param username username to set in public key comment
 * @param keyname keyname to set in public key comment
 * @return public key
 */
public String generateUserKey(String username, String keyname) {

    //set key type
    int type = KeyPair.RSA;
    if ("dsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.DSA;
    } else if ("ecdsa".equals(SSHUtil.KEY_TYPE)) {
        type = KeyPair.ECDSA;
    }

    JSch jsch = new JSch();

    String pubKey = null;
    try {

        KeyPair keyPair = KeyPair.genKeyPair(jsch, type, SSHUtil.KEY_LENGTH);

        OutputStream os = new ByteArrayOutputStream();
        keyPair.writePrivateKey(os, publicKey.getPassphrase().getBytes());
        //set private key
        servletRequest.getSession().setAttribute(PVT_KEY, EncryptionUtil.encrypt(os.toString()));

        os = new ByteArrayOutputStream();
        keyPair.writePublicKey(os, username + "@" + keyname);
        pubKey = os.toString();

        keyPair.dispose();
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }

    return pubKey;
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qstat command.//from www  . j  a v  a2  s.com
 * <p>
 * Equivalent to qstat -f [param]
 *
 * @param name job name
 * @return list of jobs
 */
public static List<Job> qstat(String name) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT);
    cmdLine.addArgument(PARAMETER_FULL_STATUS);
    if (StringUtils.isNotBlank(name)) {
        cmdLine.addArgument(name);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qstat exit value: " + exitValue);

    final List<Job> jobs;
    try {
        jobs = QSTAT_JOBS_PARSER.parse(out.toString());
    } catch (ParseException pe) {
        throw new PBSException("Failed to parse qstat jobs output: " + pe.getMessage(), pe);
    }

    return (jobs == null ? new ArrayList<Job>(0) : jobs);
}

From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java

public static void listTopics(CNSControllerServlet cns, User user, OutputStream out, String token)
        throws Exception {
    HttpServletRequest request = new SimpleHttpServletRequest();
    Map<String, String[]> params = new HashMap<String, String[]>();

    addParam(params, "Action", "ListTopics");
    if (token != null)
        addParam(params, "NextToken", token);
    addParam(params, "AWSAccessKeyId", user.getAccessKey());

    ((SimpleHttpServletRequest) request).setParameterMap(params);
    SimpleHttpServletResponse response = new SimpleHttpServletResponse();
    response.setOutputStream(out);//  w  w  w .j  av a2  s.c  o  m

    cns.doGet(request, response);
    response.getWriter().flush();
    logger.debug("Response: " + out.toString());
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qstat command.//from  w w w  . j ava  2 s .c  o  m
 * <p>
 * Equivalent to qstat -Q -f [name]
 *
 * @param name queue name
 * @return list of queues
 */
public static List<Queue> qstatQueues(String name) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT);
    cmdLine.addArgument(PARAMETER_FULL_STATUS);
    cmdLine.addArgument(PARAMETER_QUEUE);
    if (StringUtils.isNotBlank(name)) {
        cmdLine.addArgument(name);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qstat exit value: " + exitValue);

    final List<Queue> queues;
    try {
        queues = QSTAT_QUEUES_PARSER.parse(out.toString());
    } catch (ParseException pe) {
        throw new PBSException("Failed to parse qstat queues output: " + pe.getMessage(), pe);
    }

    return (queues == null ? new ArrayList<Queue>(0) : queues);
}

From source file:cz.muni.fi.mir.scheduling.CanonicalizationTask.java

/**
 * Method creates CanonicOutput out of given formula. For proper
 * canonicalization we need input formula, already instantiated
 * Canonicalizer via reflection, main method obtained via reflection and
 * ApplicationRun under which canonicalization task runs.
 *
 * @param f formula to be canonicalized//  w  ww  .  jav a  2  s  .c  o  m
 * @param canonicalizer instance of Canonicalizer
 * @param canonicalize main method
 * @param applicationRun under which task runs
 * @return Canonic Output based on given formula.
 */
private CanonicOutput canonicalize(Formula f, Object canonicalizer, Method canonicalize,
        ApplicationRun applicationRun) {
    InputStream input = new ByteArrayInputStream(f.getXml().getBytes());
    OutputStream output = new ByteArrayOutputStream();
    CanonicOutput co = new CanonicOutput();
    long start = System.currentTimeMillis();
    try {
        canonicalize.invoke(canonicalizer, input, output);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        logger.fatal(ex);
    }

    co.setApplicationRun(applicationRun);
    co.setOutputForm(output.toString());
    //canonicOutput.setSimilarForm(similarityFormConverter.convert(canonicOutput.getOutputForm()));
    co.setRunningTime(System.currentTimeMillis() - start);
    co.setParents(Arrays.asList(f));

    return co;
}

From source file:com.utest.webservice.impl.v2.ProductWebServiceImpl.java

@Override
@Secured(Permission.TEST_CASE_EDIT)
@POST//from ww  w. j  av  a 2  s.c o m
@Path("/{id}/import_multistep_testcases/")
public Boolean importMultiStepTestCasesFromCsv(MultipartBody body_, @PathParam("id") final Integer productId_)
        throws Exception {
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = body_.getAllAttachments();
    javax.activation.DataHandler dataHandler = attachments.get(0).getDataHandler();
    InputStream inputStream = dataHandler.getInputStream();
    OutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);
    inputStream.close();
    outputStream.close();
    testCaseService.importMultiStepTestCasesFromCsv(outputStream.toString(), productId_);
    return Boolean.TRUE;
}

From source file:com.utest.webservice.impl.v2.ProductWebServiceImpl.java

@Override
@Secured(Permission.TEST_CASE_EDIT)
@POST/*from w  w w . ja va 2  s.  c o m*/
@Path("/{id}/import_singlestep_testcases/")
public Boolean importSingleStepTestCasesFromCsv(MultipartBody body_, @PathParam("id") final Integer productId_)
        throws Exception {
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = body_.getAllAttachments();
    javax.activation.DataHandler dataHandler = attachments.get(0).getDataHandler();
    InputStream inputStream = dataHandler.getInputStream();
    OutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);
    inputStream.close();
    outputStream.close();
    testCaseService.importSingleStepTestCasesFromCsv(outputStream.toString(), productId_);
    return Boolean.TRUE;
}

From source file:org.apache.solr.update.AddBlockUpdateTest.java

@Test
public void testXML() throws IOException, XMLStreamException {
    UpdateRequest req = new UpdateRequest();

    List<SolrInputDocument> docs = new ArrayList<>();

    String xml_doc1 = "<doc >" + "  <field name=\"id\">1</field>" + "  <field name=\"parent_s\">X</field>"
            + "<doc>  " + "  <field name=\"id\" >2</field>" + "  <field name=\"child_s\">y</field>" + "</doc>"
            + "<doc>  " + "  <field name=\"id\" >3</field>" + "  <field name=\"child_s\">z</field>" + "</doc>"
            + "</doc>";

    String xml_doc2 = "<doc >" + "  <field name=\"id\">4</field>" + "  <field name=\"parent_s\">A</field>"
            + "<doc>  " + "  <field name=\"id\" >5</field>" + "  <field name=\"child_s\">b</field>" + "</doc>"
            + "<doc>  " + "  <field name=\"id\" >6</field>" + "  <field name=\"child_s\">c</field>" + "</doc>"
            + "</doc>";

    XMLStreamReader parser = inputFactory.createXMLStreamReader(new StringReader(xml_doc1));
    parser.next(); // read the START document...
    //null for the processor is all right here
    XMLLoader loader = new XMLLoader();
    SolrInputDocument document1 = loader.readDoc(parser);

    XMLStreamReader parser2 = inputFactory.createXMLStreamReader(new StringReader(xml_doc2));
    parser2.next(); // read the START document...
    //null for the processor is all right here
    //XMLLoader loader = new XMLLoader();
    SolrInputDocument document2 = loader.readDoc(parser2);

    docs.add(document1);/* w  w  w .  ja v a  2s .  c o  m*/
    docs.add(document2);

    Collections.shuffle(docs, random());
    req.add(docs);

    RequestWriter requestWriter = new RequestWriter();
    OutputStream os = new ByteArrayOutputStream();
    requestWriter.write(req, os);
    assertBlockU(os.toString());
    assertU(commit());

    final SolrIndexSearcher searcher = getSearcher();
    assertSingleParentOf(searcher, one("yz"), "X");
    assertSingleParentOf(searcher, one("bc"), "A");

}

From source file:org.ebayopensource.turmeric.eclipse.errorlibrary.properties.ui.utils.TurmericErrorLibraryUtils.java

/**
 * Adds the domain list props./*  w ww.  j  a  va 2  s .  c  om*/
 *
 * @param project the project
 * @param domainName the domain name
 * @param monitor the monitor
 * @throws CoreException the core exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void addDomainListProps(IProject project, String domainName, IProgressMonitor monitor)
        throws CoreException, IOException {
    IFile file = TurmericErrorLibraryUtils.getDomainListPropsFile(project);
    OutputStream output = new ByteArrayOutputStream();
    InputStream input = null;
    if (file.isAccessible()) {
        try {
            input = file.getContents();
            String key = PropertiesSOAConstants.PROPS_LIST_OF_DOMAINS;
            Collection<String> domains = TurmericErrorLibraryUtils.getAllErrorDomains(project);
            if (!domains.contains(domainName)) {
                domains.add(domainName);
            }
            String domainListStr = StringUtils.join(domains, ",");
            //            if (PropertiesFileUtil.getPropertyValueByKey(input, key) == null) {
            //               input = file.getContents();
            //               Map<String, String> newProps = new HashMap<String, String>();
            //               newProps.put(key, domainListStr);
            //               PropertiesFileUtil.addProperty(input, output, newProps);
            //            } else {
            input = file.getContents();
            PropertiesFileUtil.updatePropertyByKey(input, output, key, domainListStr);
            //            }
            String contents = output.toString();
            WorkspaceUtil.writeToFile(contents, file, monitor);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }
}