List of usage examples for java.io ByteArrayOutputStream toString
public synchronized String toString()
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Read contents of a file into a String. * //from w ww . ja v a 2s.c o m * @param file * @return * @throws SiteWhereException */ protected static String readFile(File file) throws SiteWhereException { try { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); return out.toString(); } catch (IOException e) { throw new SiteWhereException("Unable to read content from: " + file.getAbsolutePath()); } }
From source file:fr.gael.dhus.datastore.processing.ProcessingUtils.java
public static List<MetadataIndex> getIndexesFrom(URL url) { java.util.Collection<String> properties = null; DrbNode node = null;//ww w . j a va 2s .c o m DrbCortexItemClass cl = null; // Prepare the index structure. List<MetadataIndex> indexes = new ArrayList<MetadataIndex>(); // Prepare the DRb node to be processed try { // First : force loading the model before accessing items. node = ProcessingUtils.getNodeFromPath(url.getPath()); cl = ProcessingUtils.getClassFromNode(node); logger.info("Class \"" + cl.getLabel() + "\" for product " + node.getName()); // Get all values of the metadata properties attached to the item // class or any of its super-classes properties = cl.listPropertyStrings(METADATA_NAMESPACE + PROPERTY_METADATA_EXTRACTOR, false); // Return immediately if no property value were found if (properties == null) { logger.warn("Item \"" + cl.getLabel() + "\" has no metadata defined."); return null; } } catch (IOException e) { throw new UnsupportedOperationException("Error While decoding drb node", e); } // Loop among retrieved property values for (String property : properties) { // Filter possible XML markup brackets that could have been encoded // in a CDATA section property = property.replaceAll("<", "<"); property = property.replaceAll(">", ">"); /* * property = property.replaceAll("\n", " "); // Replace eol by blank * space property = property.replaceAll(" +", " "); // Remove * contiguous blank spaces */ // Create a query for the current metadata extractor Query metadataQuery = new Query(property); // Evaluate the XQuery DrbSequence metadataSequence = metadataQuery.evaluate(node); // Check that something results from the evaluation: jump to next // value otherwise if ((metadataSequence == null) || (metadataSequence.getLength() < 1)) { continue; } // Loop among results for (int iitem = 0; iitem < metadataSequence.getLength(); iitem++) { // Get current metadata node DrbNode n = (DrbNode) metadataSequence.getItem(iitem); // Get name DrbAttribute name_att = n.getAttribute("name"); Value name_v = null; if (name_att != null) name_v = name_att.getValue(); String name = null; if (name_v != null) name = name_v.convertTo(Value.STRING_ID).toString(); // get type DrbAttribute type_att = n.getAttribute("type"); Value type_v = null; if (type_att != null) type_v = type_att.getValue(); else type_v = new fr.gael.drb.value.String(MIME_PLAIN_TEXT); String type = type_v.convertTo(Value.STRING_ID).toString(); // get category DrbAttribute cat_att = n.getAttribute("category"); Value cat_v = null; if (cat_att != null) cat_v = cat_att.getValue(); else cat_v = new fr.gael.drb.value.String("product"); String category = cat_v.convertTo(Value.STRING_ID).toString(); // get category DrbAttribute qry_att = n.getAttribute("queryable"); String queryable = null; if (qry_att != null) { Value qry_v = qry_att.getValue(); if (qry_v != null) queryable = qry_v.convertTo(Value.STRING_ID).toString(); } // Get value String value = null; if (MIME_APPLICATION_GML.equals(type) && n.hasChild()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); XmlWriter.writeXML(n.getFirstChild(), out); value = out.toString(); try { out.close(); } catch (IOException e) { logger.warn("Cannot close stream !", e); } } else // Case of "text/plain" { Value value_v = n.getValue(); if (value_v != null) { value = value_v.convertTo(Value.STRING_ID).toString(); value = value.trim(); } } if ((name != null) && (value != null)) { MetadataIndex index = new MetadataIndex(); index.setName(name); try { index.setType(new MimeType(type).toString()); } catch (MimeTypeParseException e) { logger.warn("Wrong metatdata extractor mime type in class \"" + cl.getLabel() + "\" for metadata called \"" + name + "\".", e); } index.setCategory(category); index.setValue(value); index.setQueryable(queryable); indexes.add(index); } else { String field_name = ""; if (name != null) field_name = name; else if (queryable != null) field_name = queryable; else if (category != null) field_name = "of category " + category; logger.warn("Nothing extracted for field " + field_name); } } } return indexes; }
From source file:Main.java
public static String generateXml() { DocumentBuilder documentBuilder = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/* w w w .ja v a 2 s . c o m*/ documentBuilder = docFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); DOMSource docSource = new DOMSource(document); StreamResult result = new StreamResult(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); result.setOutputStream(baos); transformer.transform(docSource, result); } catch (Exception e) { e.printStackTrace(); } return baos.toString(); }
From source file:org.escidoc.browser.elabsmodul.service.ELabsService.java
private static List<String[]> buildConfiguration(final List<Map<String, String>> list) { Preconditions.checkNotNull(list, "Config list is null"); final List<String[]> result = new ArrayList<String[]>(); if (list.isEmpty()) { LOG.error("There is not ConfigMap to process!"); return null; }//from w w w .j a v a 2s . c o m for (final Map<String, String> map : list) { final Properties config = new Properties(); config.putAll(map); if (!config.isEmpty()) { LOG.debug(config.toString()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { config.storeToXML(out, ""); LOG.debug("Configuration Properties XML \n" + out.toString()); } catch (final IOException e) { LOG.error(e.getMessage()); } result.add(new String[] { config.getProperty(ELabsServiceConstants.E_SYNC_DAEMON_ENDPOINT), out.toString() }); } else { LOG.error("Configuration is empty!"); } } return result; }
From source file:com.gimranov.zandy.app.task.ZoteroAPITask.java
/** * Executes the specified APIRequest and handles the response * /*from w w w . j a va 2 s. c o m*/ * This is done synchronously; use the the AsyncTask interface for calls * from the UI thread. * * @param req * @return */ public static String issue(APIRequest req, Database db) { // Check that the method makes sense String method = req.method.toLowerCase(); if (!method.equals("get") && !method.equals("post") && !method.equals("delete") && !method.equals("put")) { // TODO Throw an exception here. Log.e(TAG, "Invalid method: " + method); return null; } String resp = ""; try { // Append content=json everywhere, if we don't have it yet if (req.query.indexOf("content=json") == -1) { if (req.query.indexOf("?") != -1) { req.query += "&content=json"; } else { req.query += "?content=json"; } } // Append the key, if defined, to all requests if (req.key != null && req.key != "") { req.query += "&key=" + req.key; } if (method.equals("put")) { req.query = req.query.replace("content=json&", ""); } Log.i(TAG, "Request " + req.method + ": " + req.query); URI uri = new URI(req.query); HttpClient client = new DefaultHttpClient(); // The default implementation includes an Expect: header, which // confuses the Zotero servers. client.getParams().setParameter("http.protocol.expect-continue", false); // We also need to send our data nice and raw. client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); /* It would be good to rework this mess to be less repetitive */ if (method.equals("post")) { HttpPost request = new HttpPost(); request.setURI(uri); // Set headers if necessary if (req.ifMatch != null) { request.setHeader("If-Match", req.ifMatch); } if (req.contentType != null) { request.setHeader("Content-Type", req.contentType); } if (req.body != null) { Log.d(TAG, "Post body: " + req.body); // Force the encoding here StringEntity entity = new StringEntity(req.body, "UTF-8"); request.setEntity(entity); } if (req.disposition.equals("xml")) { HttpResponse hr = client.execute(request); int code = hr.getStatusLine().getStatusCode(); Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase()); if (code < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); XMLResponseParser parse = new XMLResponseParser(in); if (req.updateKey != null && req.updateType != null) parse.update(req.updateType, req.updateKey); // The response on POST in XML mode (new item) is a feed parse.parse(XMLResponseParser.MODE_FEED, uri.toString(), db); resp = "XML was parsed."; } else { Log.e(TAG, "Not parsing non-XML response, code >= 400"); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG, "Error Body: " + ostream.toString()); Log.e(TAG, "Post Body:" + req.body); } } else { BasicResponseHandler brh = new BasicResponseHandler(); try { resp = client.execute(request, brh); req.onSuccess(db); } catch (ClientProtocolException e) { Log.e(TAG, "Exception thrown issuing POST request: ", e); req.onFailure(db); } } } else if (method.equals("put")) { HttpPut request = new HttpPut(); request.setURI(uri); // Set headers if necessary if (req.ifMatch != null) { request.setHeader("If-Match", req.ifMatch); } if (req.contentType != null) { request.setHeader("Content-Type", req.contentType); } if (req.body != null) { // Force the encoding here StringEntity entity = new StringEntity(req.body, "UTF-8"); request.setEntity(entity); } if (req.disposition.equals("xml")) { HttpResponse hr = client.execute(request); int code = hr.getStatusLine().getStatusCode(); Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase()); if (code < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); XMLResponseParser parse = new XMLResponseParser(in); parse.parse(XMLResponseParser.MODE_ENTRY, uri.toString(), db); resp = "XML was parsed."; // TODO req.onSuccess(db); } else { Log.e(TAG, "Not parsing non-XML response, code >= 400"); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG, "Error Body: " + ostream.toString()); Log.e(TAG, "Put Body:" + req.body); // TODO req.onFailure(db); // "Precondition Failed" // The item changed server-side, so we have a conflict to resolve... // XXX This is a hard problem. if (code == 412) { Log.e(TAG, "Skipping dirtied item with server-side changes as well"); } } } else { BasicResponseHandler brh = new BasicResponseHandler(); try { resp = client.execute(request, brh); req.onSuccess(db); } catch (ClientProtocolException e) { Log.e(TAG, "Exception thrown issuing PUT request: ", e); req.onFailure(db); } } } else if (method.equals("delete")) { HttpDelete request = new HttpDelete(); request.setURI(uri); if (req.ifMatch != null) { request.setHeader("If-Match", req.ifMatch); } BasicResponseHandler brh = new BasicResponseHandler(); try { resp = client.execute(request, brh); req.onSuccess(db); } catch (ClientProtocolException e) { Log.e(TAG, "Exception thrown issuing DELETE request: ", e); req.onFailure(db); } } else { HttpGet request = new HttpGet(); request.setURI(uri); if (req.contentType != null) { request.setHeader("Content-Type", req.contentType); } if (req.disposition.equals("xml")) { HttpResponse hr = client.execute(request); int code = hr.getStatusLine().getStatusCode(); Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase()); if (code < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); XMLResponseParser parse = new XMLResponseParser(in); // We can tell from the URL whether we have a single item or a feed int mode = (uri.toString().indexOf("/items?") == -1 && uri.toString().indexOf("/top?") == -1 && uri.toString().indexOf("/collections?") == -1 && uri.toString().indexOf("/children?") == -1) ? XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED; parse.parse(mode, uri.toString(), db); resp = "XML was parsed."; // TODO req.onSuccess(db); } else { Log.e(TAG, "Not parsing non-XML response, code >= 400"); ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG, "Error Body: " + ostream.toString()); Log.e(TAG, "Put Body:" + req.body); // TODO req.onFailure(db); // "Precondition Failed" // The item changed server-side, so we have a conflict to resolve... // XXX This is a hard problem. if (code == 412) { Log.e(TAG, "Skipping dirtied item with server-side changes as well"); } } } else { BasicResponseHandler brh = new BasicResponseHandler(); try { resp = client.execute(request, brh); req.onSuccess(db); } catch (ClientProtocolException e) { Log.e(TAG, "Exception thrown issuing GET request: ", e); req.onFailure(db); } } } Log.i(TAG, "Response: " + resp); } catch (IOException e) { Log.e(TAG, "Connection error", e); } catch (URISyntaxException e) { Log.e(TAG, "URI error", e); } return resp; }
From source file:edu.ku.brc.ui.GraphicsUtils.java
/** * @param name// ww w . j a v a 2 s .c om * @param imgIcon * @return */ public static String uuencodeImage(final String name, final ImageIcon imgIcon) { try { BufferedImage tmp = new BufferedImage(imgIcon.getIconWidth(), imgIcon.getIconWidth(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = tmp.createGraphics(); //g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(imgIcon.getImage(), 0, 0, imgIcon.getIconWidth(), imgIcon.getIconWidth(), null); g2.dispose(); ByteArrayOutputStream output = new ByteArrayOutputStream(8192); ImageIO.write(tmp, "PNG", output); byte[] outputBytes = output.toByteArray(); output.close(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); UUEncoder uuencode = new UUEncoder(name); uuencode.encode(new ByteArrayInputStream(outputBytes), bos); return bos.toString(); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(GraphicsUtils.class, ex); ex.printStackTrace(); } return ""; }
From source file:hudson.plugins.android_emulator.SdkInstaller.java
private static String getBuildToolsPackageName(PrintStream logger, Launcher launcher, AndroidSdk sdk) throws IOException, InterruptedException { ByteArrayOutputStream output = new ByteArrayOutputStream(); Utils.runAndroidTool(launcher, output, logger, sdk, Tool.ANDROID, "list sdk --extended", null); Matcher m = Pattern.compile("\"(build-tools-.*?)\"").matcher(output.toString()); if (!m.find()) { return null; }/*from ww w .jav a2s .c om*/ return m.group(0); }
From source file:net.itransformers.bgpPeeringMap.BgpPeeringMap.java
public static void discover() throws Exception { Map<String, String> settings = loadProperties(new File(settingsFile)); logger.info("Settings" + settings.toString()); String folderPlaceholder = settings.get("output.dir"); File outputDir = new File(projectDir + File.separator + folderPlaceholder, label); System.out.println(outputDir.getAbsolutePath()); boolean result = outputDir.mkdir(); File graphmlDir = new File(outputDir, "undirected"); result = outputDir.mkdir();/* w w w. j a v a 2 s .co m*/ XsltTransformer transformer = new XsltTransformer(); logger.info("SNMP walk start"); byte[] rawData = snmpWalk(settings); logger.info("SNMP walk end"); File rawDataFile = new File(outputDir, "raw-data-bgpPeeringMap.xml"); FileUtils.writeStringToFile(rawDataFile, new String(rawData)); logger.info("Raw-data written to a file in folder " + outputDir); logger.info("First-transformation has started with xsltTransformator " + settings.get("xsltFileName1")); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); File xsltFileName1 = new File(projectDir, settings.get("xsltFileName1")); ByteArrayInputStream inputStream1 = new ByteArrayInputStream(rawData); transformer.transformXML(inputStream1, xsltFileName1, outputStream1, settings); logger.info("First transformation finished"); File intermediateDataFile = new File(outputDir, "intermediate-bgpPeeringMap.xml"); FileUtils.writeStringToFile(intermediateDataFile, new String(outputStream1.toByteArray())); logger.trace("First transformation output"); logger.trace(outputStream1.toString()); logger.info("Second transformation started with xsltTransformator " + settings.get("xsltFileName2")); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); File xsltFileName2 = new File(projectDir, settings.get("xsltFileName2")); ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream1.toByteArray()); transformer.transformXML(inputStream2, xsltFileName2, outputStream2, settings); logger.info("Second transformation info"); logger.trace("Second transformation Graphml output"); logger.trace(outputStream2.toString()); ByteArrayInputStream inputStream3 = new ByteArrayInputStream(outputStream2.toByteArray()); ByteArrayOutputStream outputStream3 = new ByteArrayOutputStream(); File xsltFileName3 = new File(System.getProperty("base.dir"), settings.get("xsltFileName3")); transformer.transformXML(inputStream3, xsltFileName3, outputStream3, null); File outputFile = new File(graphmlDir, "undirected-bgpPeeringMap.graphml"); FileUtils.writeStringToFile(outputFile, new String(outputStream3.toByteArray())); logger.info("Output Graphml saved in a file in" + graphmlDir); //FileUtils.writeStringToFile(nodesFileListFile, "bgpPeeringMap.graphml"); FileWriter writer = new FileWriter(new File(outputDir, "undirected" + ".graphmls"), true); writer.append("undirected-bgpPeeringMap.graphml").append("\n"); writer.close(); }
From source file:Main.java
public static <T> String write(T content, Class<T> typeParameterClass) { ByteArrayOutputStream baos = null; try {/*from ww w. ja v a 2 s . c o m*/ JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed //jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos, "UTF-8"); jaxbMarshaller.marshal(content, osw); } catch (JAXBException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return baos != null ? baos.toString() : null; }
From source file:at.treedb.util.Execute.java
public static ExecResult execute(String command, String[] param, Map<String, File> map) { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = null;/*from w w w. jav a 2 s . co m*/ int exitValue = 0; try { PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); cmdLine = new CommandLine(command); if (param != null) { for (String s : param) { s = s.trim(); if (s.isEmpty()) { continue; } cmdLine.addArgument(s); } } cmdLine.setSubstitutionMap(map); executor.setStreamHandler(streamHandler); exitValue = executor.execute(cmdLine); return new ExecResult(exitValue, outputStream.toString(), null); } catch (Exception e) { return new ExecResult(-1, outputStream.toString(), e); } }