List of usage examples for java.io OutputStream toString
public String toString()
From source file:org.lockss.util.TestStreamUtil.java
public void testCopyInputStreamLength() throws IOException { InputStream is = new StringInputStream("012345678901234567890"); OutputStream baos = new ByteArrayOutputStream(20); assertEquals(5, StreamUtil.copy(is, baos, 5)); assertEquals("01234", baos.toString()); assertEquals(5, StreamUtil.copy(is, baos, 5)); assertEquals("0123456789", baos.toString()); assertEquals(5, StreamUtil.copy(is, baos, 5)); assertEquals("012345678901234", baos.toString()); StreamUtil.copy(is, baos, 5);/*from w w w. j av a 2 s . c o m*/ assertEquals("01234567890123456789", baos.toString()); is.close(); baos.close(); is = new StringInputStream("01234567890123456789012345"); baos = new ByteArrayOutputStream(2); assertEquals(2, StreamUtil.copy(is, baos, 2)); assertEquals("01", baos.toString()); baos = new ByteArrayOutputStream(5); assertEquals(5, StreamUtil.copy(is, baos, 5)); assertEquals("23456", baos.toString()); baos = new ByteArrayOutputStream(7); assertEquals(7, StreamUtil.copy(is, baos, 7)); assertEquals("7890123", baos.toString()); baos = new ByteArrayOutputStream(7); assertEquals(12, StreamUtil.copy(is, baos, -1)); assertEquals("456789012345", baos.toString()); is.close(); baos.close(); }
From source file:com.tupilabs.pbs.PBS.java
/** * PBS qnodes command.//w w w.j a v a 2s . c om * <p> * Get information about the cluster nodes. * * @param name node name * @return list of nodes * @throws PBSException if an error communicating with the PBS occurs */ public static List<Node> qnodes(String name) { final List<Node> nodes; final CommandLine cmdLine = new CommandLine(COMMAND_QNODES); cmdLine.addArgument(PARAMETER_XML); 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 qnodes command: " + e.getMessage(), e); } catch (IOException e) { throw new PBSException("Failed to execute qnodes command: " + e.getMessage(), e); } catch (InterruptedException e) { throw new PBSException("Failed to execute qnodes command: " + e.getMessage(), e); } final int exitValue = resultHandler.getExitValue(); LOGGER.info("qnodes exit value: " + exitValue); try { nodes = NODE_XML_PARSER.parse(out.toString()); } catch (ParseException pe) { throw new PBSException("Failed to parse node XML: " + pe.getMessage(), pe); } return nodes; }
From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java
private void dumpPart(Part p, Element msg, Document doc) throws Exception { Element content = null;//from ww w . j a v a 2s. c o m if (p.isMimeType("text/plain")) { content = doc.createElement("PlainMessage"); Text body = doc.createTextNode((String) p.getContent()); content.appendChild(body); } else if (p.isMimeType("text/html")) { content = doc.createElement("HTMLMessage"); CDATASection body = doc.createCDATASection((String) p.getContent()); content.appendChild(body); } else if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); content = doc.createElement("Multipart"); for (int i = 0; i < count; i++) { dumpPart(mp.getBodyPart(i), content, doc); } } else if (p.isMimeType("message/rfc822")) { content = doc.createElement("NestedMessage"); dumpPart((Part) p.getContent(), content, doc); } else { content = doc.createElement("EncodedContent"); DataHandler dh = p.getDataHandler(); OutputStream os = new ByteArrayOutputStream(); Base64EncodingOutputStream b64os = new Base64EncodingOutputStream(os); dh.writeTo(b64os); b64os.flush(); b64os.close(); content.appendChild(doc.createTextNode(os.toString())); } msg.appendChild(content); String filename = p.getFileName(); if (filename != null) { content.setAttribute("file-name", filename); } String ct = p.getContentType(); if (ct != null) { content.setAttribute("content-type", ct); } String desc = p.getDescription(); if (desc != null) { content.setAttribute("description", desc); } }
From source file:net.sourceforge.vulcan.mailer.EmailPlugin.java
private String generateXhtml(Document projectDom, URL projectSiteURL, URL statusURL, URL trackerURL, Locale locale) throws SAXException, IOException, TransformerException, NoSuchTransformFormatException, MalformedURLException {/*from ww w. jav a 2 s.c o m*/ final JDOMResult xhtmlResult = new JDOMResult(); final Map<String, ? super Object> params = new HashMap<String, Object>(); params.put("showBuildDirectory", Boolean.FALSE); if (projectSiteURL != null) { params.put("projectSiteURL", projectSiteURL.toExternalForm()); } if (statusURL != null) { params.put("viewProjectStatusURL", statusURL.toExternalForm()); } if (trackerURL != null) { params.put("issueTrackerURL", trackerURL.toExternalForm()); } projectDomBuilder.transform(projectDom, params, locale, stylesheet, xhtmlResult); final Document xhtmlDom = xhtmlResult.getDocument(); xhtmlDom.setDocType( new DocType("html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd")); addStyle(xhtmlDom.getRootElement()); final OutputStream os = new ByteArrayOutputStream(); final XMLOutputter out = new XMLOutputter(Format.getRawFormat()); out.output(xhtmlDom, os); return os.toString(); }
From source file:com.thoughtworks.go.util.ProcessWrapperTest.java
@Test public void shouldTypeInputToConsole() { OutputStream processInputStream = new ByteArrayOutputStream();// mock(OutputStream.class); Process process = getMockedProcess(processInputStream); ProcessWrapper processWrapper = new ProcessWrapper(process, "", "", inMemoryConsumer(), null, null); ArrayList<String> inputs = new ArrayList<String>(); inputs.add("input1"); inputs.add("input2"); processWrapper.typeInputToConsole(inputs); String input = processInputStream.toString(); String[] parts = input.split("\\r?\\n"); assertThat(parts[0], is("input1")); assertThat(parts[1], is("input2")); }
From source file:info.rmapproject.api.responsemgr.ResourceResponseManager.java
/** * Generate HTTP Response for list of RDF triples that reference the resource URI provided. * Graph is filtered according to query params provided. * * @param strResourceUri the Resource URI * @param returnType the RDF return type * @param queryParams the query params//from ww w . ja v a 2 s .c o m * @return HTTP Response * @throws RMapApiException the RMap API exception */ public Response getRMapResourceTriples(String strResourceUri, RdfMediaType returnType, MultivaluedMap<String, String> queryParams) throws RMapApiException { boolean reqSuccessful = false; Response response = null; try { if (strResourceUri == null || strResourceUri.length() == 0) { throw new RMapApiException(ErrorCode.ER_NO_OBJECT_URI_PROVIDED); } if (returnType == null) { returnType = Constants.DEFAULT_RDF_TYPE; } URI uriResourceUri = convertPathStringToURI(strResourceUri); RMapSearchParams params = generateSearchParamObj(queryParams); Integer currPage = extractPage(queryParams); Integer limit = params.getLimit(); //we are going to get one extra record to see if we need a "next" params.setLimit(limit + 1); //get resource triples List<RMapTriple> stmtList = rmapService.getResourceRelatedTriples(uriResourceUri, params); if (stmtList == null) { //if the object is found, should always have at least one event throw new RMapApiException(ErrorCode.ER_CORE_GET_RDFSTMTLIST_EMPTY); } if (stmtList.size() == 0) { throw new RMapApiException(ErrorCode.ER_NO_STMTS_FOUND_FOR_RESOURCE); } ResponseBuilder responseBldr = null; //if the list is longer than the limit and there is currently no page defined, then do 303 with pagination if (!queryParams.containsKey(PAGE_PARAM) && stmtList.size() > limit) { //start See Other response to indicate need for pagination String otherUrl = getPaginatedLinkTemplate(Utils.makeResourceUrl(strResourceUri), queryParams, limit); otherUrl = otherUrl.replace(PAGENUM_PLACEHOLDER, FIRST_PAGE); responseBldr = Response.status(Response.Status.SEE_OTHER) .entity(ErrorCode.ER_RESPONSE_TOO_LONG_NEED_PAGINATION.getMessage()) .location(new URI(otherUrl)); } else { responseBldr = Response.status(Response.Status.OK); if (stmtList.size() > limit || (currPage != null && currPage > 1)) { boolean showNextLink = stmtList.size() > limit; String pageLinkTemplate = getPaginatedLinkTemplate(Utils.makeResourceUrl(strResourceUri), queryParams, limit); String pageLinks = generatePaginationLinks(pageLinkTemplate, currPage, showNextLink); responseBldr.header("Link", pageLinks); if (showNextLink) { //gone over limit so remove the last record since it was only added to check for record that would spill to next page stmtList.remove(stmtList.size() - 1); } } //convert to RDF OutputStream rdf = rdfHandler.triples2Rdf(stmtList, returnType.getRdfType()); if (rdf == null) { throw new RMapApiException(ErrorCode.ER_CORE_CANT_CREATE_STMT_RDF); } responseBldr.entity(rdf.toString()).type(returnType.getMimeType()); } response = responseBldr.build(); reqSuccessful = true; } catch (RMapApiException ex) { throw RMapApiException.wrap(ex); } catch (RMapObjectNotFoundException ex) { throw RMapApiException.wrap(ex, ErrorCode.ER_OBJECT_NOT_FOUND); } catch (RMapDefectiveArgumentException ex) { throw RMapApiException.wrap(ex, ErrorCode.ER_GET_RESOURCE_BAD_ARGUMENT); } catch (RMapException ex) { throw RMapApiException.wrap(ex, ErrorCode.ER_CORE_GENERIC_RMAP_EXCEPTION); } catch (Exception ex) { throw RMapApiException.wrap(ex, ErrorCode.ER_UNKNOWN_SYSTEM_ERROR); } finally { if (rmapService != null) rmapService.closeConnection(); if (!reqSuccessful && response != null) response.close(); } return response; }
From source file:org.ebayopensource.turmeric.eclipse.utils.test.xml.TestFreeMarkerUtil.java
/** * Test method for {@link org.ebayopensource.turmeric.eclipse.utils.xml.FreeMarkerUtil#generate(java.util.Map, java.lang.Object, java.lang.String, java.io.OutputStream)}. * @throws TemplateException // w ww .ja v a 2s .com * @throws IOException */ @Test public void testGenerate() throws IOException, TemplateException { OutputStream output = null; InputStream input = null; try { output = new ByteArrayOutputStream(); Map<String, String> data = new ConcurrentHashMap<String, String>(); data.put("serviceName", "NikonLensService"); String templateFileName = "geronimo-web.xml.ftl"; URL templateParentFolder = TestFreeMarkerUtil.class.getResource(templateFileName); Assert.assertNotNull(templateParentFolder); FreeMarkerUtil.generate(data, templateParentFolder, templateFileName, output); System.out.println(output.toString()); input = TestFreeMarkerUtil.class.getResourceAsStream("geronimo-web.xml"); Assert.assertNotNull(templateParentFolder); String expected = IOUtils.toString(input); Assert.assertEquals(expected, output.toString()); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
From source file:org.kalypsodeegree_impl.io.sax.test.MarshallFileTest.java
@Test public void writeFile() throws IOException, SAXException { /* Output: to stream */ final OutputStream os = new ByteArrayOutputStream(); final XMLReader reader = SaxParserTestUtils.createXMLReader(os); /* Test data */ final RangeSetFile file = new RangeSetFile("testname.tif"); //$NON-NLS-1$ file.setMimeType("image/tif"); //$NON-NLS-1$ final RangeSetFileMarshaller marshaller = new RangeSetFileMarshaller(reader); SaxParserTestUtils.marshallDocument(reader, marshaller, file); os.close();/*from w w w . j a v a2 s . c o m*/ final URL url = getClass().getResource("/etc/test/resources/file_marshall.gml"); final String actualContent = os.toString(); SaxParserTestUtils.assertContentEquals(url, actualContent); }
From source file:com.tethrnet.manage.action.AuthKeysAction.java
/** * generates public private key from passphrase * // ww w. j av a 2 s .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 (SSHUtil.KEY_TYPE.equals("dsa")) { type = KeyPair.DSA; } else if (SSHUtil.KEY_TYPE.equals("ecdsa")) { 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 for Array Jobs// w ww . ja v a2 s. c om * <p> * Equivalent to qstat -f -t [param] * * @param name job name * @return list of jobs */ public static List<Job> qstatArrayJob(String name) { final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT); cmdLine.addArgument(PARAMETER_FULL_STATUS); cmdLine.addArgument(PARAMETER_ARRAY_JOB_STATUS); if (StringUtils.isNotBlank(name)) { cmdLine.addArgument(name); } final OutputStream out = new ByteArrayOutputStream(); final OutputStream err = new ByteArrayOutputStream(); DefaultExecuteResultHandler resultHandler; try { resultHandler = execute(cmdLine, 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); }