List of usage examples for java.io ByteArrayOutputStream toString
public synchronized String toString()
From source file:com.amazonaws.tvm.Utilities.java
public static String getRawPolicyFile() { if (RAW_POLICY_OBJECT == null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(8196); InputStream in = null;//from w w w .java2s .co m try { in = Utilities.class.getResourceAsStream("/TokenVendingMachinePolicy.json"); byte[] buffer = new byte[1024]; int length = 0; while ((length = in.read(buffer)) != -1) { baos.write(buffer, 0, length); } RAW_POLICY_OBJECT = baos.toString(); } catch (Exception exception) { log.log(Level.SEVERE, "Unable to load policy object.", exception); RAW_POLICY_OBJECT = ""; } finally { try { baos.close(); in.close(); } catch (Exception exception) { log.log(Level.SEVERE, "Unable to close streams.", exception); } in = null; baos = null; } } return RAW_POLICY_OBJECT; }
From source file:sep.gaia.resources.poi.POILoaderWorker.java
/** * Generates a Overpass API-request in XML-format. The request complies to the limitations and the * bounding box in <code>query</code> and is designed to retrieve both nodes and recursed ways. * @param query The query to generate XML for. * @return The generated XML-query.//from w w w. j ava2 s. c o m */ private static String generateQueryXML(POIQuery query) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // The root of a OSM-query is always osm-script: Element script = doc.createElement("osm-script"); doc.appendChild(script); // First element is the union containing the queries: Element unionElement = doc.createElement("union"); script.appendChild(unionElement); // Second element says that the recused union of the prior results should be formed: Element recurseUnion = doc.createElement("union"); Element itemElement = doc.createElement("item"); recurseUnion.appendChild(itemElement); Element recurseElement = doc.createElement("recurse"); recurseElement.setAttribute("type", "down"); recurseUnion.appendChild(recurseElement); script.appendChild(recurseUnion); // The last element means, that the results (of the recursed union) // should be written as response: Element printElement = doc.createElement("print"); script.appendChild(printElement); // First query (in the query union) askes for nodes conforming the given attributes: Element queryNodeElement = doc.createElement("query"); queryNodeElement.setAttribute("type", "node"); // The second element does the same for ways: Element queryWayElement = doc.createElement("query"); queryWayElement.setAttribute("type", "way"); // Add them to the first union: unionElement.appendChild(queryNodeElement); unionElement.appendChild(queryWayElement); // Now iterate all key-value-pairs and add "has-kv"-pairs to both queries: POIFilter filter = query.getLimitations(); Map<String, String> attributes = filter.getLimitations(); for (String key : attributes.keySet()) { String value = attributes.get(key); // The values returned by POIFilter are regular expressions, so use regv instead of v: Element currentKVNode = doc.createElement("has-kv"); currentKVNode.setAttribute("k", key); currentKVNode.setAttribute("regv", value); queryNodeElement.appendChild(currentKVNode); Element currentKVWay = doc.createElement("has-kv"); currentKVWay.setAttribute("k", key); currentKVWay.setAttribute("regv", value); queryWayElement.appendChild(currentKVWay); } // We don't want the data of the whole earth, so add bounding-boxes to the queries: Element nodeBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryNodeElement.appendChild(nodeBBoxElement); Element wayBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryWayElement.appendChild(wayBBoxElement); // Now the XML-tree is built, so transform it to a string and return it: TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(stream); transformer.transform(source, result); return stream.toString(); } catch (ParserConfigurationException | TransformerException e) { Logger.getInstance().error("Cannot write cache-index: " + e.getMessage()); return null; } }
From source file:com.vmware.photon.controller.api.frontend.lib.ova.OvaTestModule.java
/** * Read a binary stream as string.//w w w . j ava 2 s .c o m * * @param stream * @return * @throws java.io.IOException */ public static String readStringFromStream(InputStream stream) throws IOException { ByteArrayOutputStream byteString = new ByteArrayOutputStream(); int c; int i = 0; while ((c = stream.read()) != -1) { byteString.write(c); byte[] b = new byte[i + i]; int readBytes = stream.read(b, i, i); for (int k = 0; k < readBytes; k++) { byteString.write(b[k + i]); } if (readBytes != i) { i = i / 2; } else { i = i + 1; } } return byteString.toString(); }
From source file:com.tellapart.taba.Transport.java
/** * Encode a single Event.//from w ww . ja v a 2s . com * * @param event Event to encode. * @param factory * * @return Encoded event String. */ protected static String encodeEvent(Event event, JsonFactory factory) throws IOException { ByteArrayOutputStream encodedPayload = new ByteArrayOutputStream(); JsonGenerator payloadGenerator = factory.createGenerator(encodedPayload); event.getPayload().serialize(payloadGenerator); payloadGenerator.close(); ByteArrayOutputStream encodedEvent = new ByteArrayOutputStream(); JsonGenerator eventGenerator = factory.createGenerator(encodedEvent); eventGenerator.writeStartArray(); eventGenerator.writeString(event.getTabType()); eventGenerator.writeNumber(event.getTimestamp()); eventGenerator.writeString(encodedPayload.toString()); eventGenerator.writeEndArray(); eventGenerator.close(); return encodedEvent.toString(); }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static String convertToBase64PEMString(X509Certificate x509Certificate) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write("-----BEGIN CERTIFICATE-----".getBytes()); byteArrayOutputStream.write("\n".getBytes()); byteArrayOutputStream.write(Base64Utils.encodeToBytes(x509Certificate.getEncoded())); byteArrayOutputStream.write("-----END CERTIFICATE-----".getBytes()); byteArrayOutputStream.write("\n".getBytes()); return byteArrayOutputStream.toString(); }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java
/** * @param string/* w w w.java2 s . c o m*/ * @return * @throws JAXBException */ private static String generateFailure(String code, String codeValue) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); ServiceResponseType value = factory.createServiceResponseType(); AuthenticationFailureType failure = factory.createAuthenticationFailureType(); failure.setValue(codeValue); failure.setCode(code); value.setAuthenticationFailure(failure); JAXBElement<ServiceResponseType> createServiceResponse = factory.createServiceResponse(value); JAXB.marshal(createServiceResponse, os); return os.toString(); }
From source file:com.yahoo.ycsb.db.RedisClient.java
public static String decompress(String st) { if (compress != null && compress.equals("y")) { if (compressAlgo != null && (compressAlgo.equals("lz4") || compressAlgo.equals("lz4hc"))) { try { int split = st.indexOf('|'); final int decompressedLength = Integer.parseInt(st.substring(0, split)); LZ4FastDecompressor decompressor = lz4factory.fastDecompressor(); byte[] restored = new byte[decompressedLength]; byte[] compressed = st.substring(split + 1, st.length()).getBytes("ISO-8859-1"); decompressor.decompress(compressed, 0, restored, 0, decompressedLength); String ret = new String(restored, "ISO-8859-1"); return ret; } catch (Exception e) { e.printStackTrace();//from w w w. j ava 2s .c o m } } else if (compressAlgo != null && compressAlgo.equals("bzip2")) { try { InputStream in = new StringBufferInputStream(st); BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in); byte[] data = st.getBytes("ISO-8859-1"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int n = 0; while (-1 != (n = bzIn.read(data))) { baos.write(data, 0, n); } bzIn.close(); return baos.toString(); } catch (Exception e) { e.printStackTrace(); } } else if (compressAlgo != null && compressAlgo.equals("snappy")) { try { byte[] uncompressed = Snappy.uncompress(st.getBytes("ISO-8859-1")); String ret = new String(uncompressed, "ISO-8859-1"); return ret; } catch (Exception e) { e.printStackTrace(); } } } return st; }
From source file:XMLUtils.java
public static String toString(Source source, Properties props) throws TransformerException, IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult sr = new StreamResult(bos); Transformer trans = newTransformer(); if (props == null) { props = new Properties(); props.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); }/*w ww. j a va 2 s .co m*/ trans.setOutputProperties(props); trans.transform(source, sr); bos.close(); return bos.toString(); }
From source file:Main.java
public static String toString(final Document document) { try {// w w w. j a v a 2 s. co m final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //http://johnsonsolutions.blogspot.ca/2007/08/xml-transformer-indent-doesnt-work-with.html transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(document), new StreamResult(baos)); final String result = baos.toString(); return result; } catch (final TransformerException e) { throw new Error(e); } }
From source file:com.freesundance.contacts.google.ContactsExample.java
/** * Print the contents of a ContactEntry to System.err. * * @param contact The ContactEntry to display. */// w ww. j av a 2 s . c o m private static void printContact(ContactEntry contact) { LOG.debug("Id: " + contact.getId()); if (contact.getTitle() != null) { LOG.debug("Contact name: " + contact.getTitle().getPlainText()); } else { LOG.debug("Contact has no name"); } LOG.debug("Last updated: " + contact.getUpdated().toUiString()); if (contact.hasDeleted()) { LOG.debug("Deleted:"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ElementHelper.printContact(ps, contact); LOG.info("\n{}", baos.toString()); Link photoLink = contact.getLink("http://schemas.google.com/contacts/2008/rel#photo", "image/*"); LOG.debug("Photo link: " + photoLink.getHref()); String photoEtag = photoLink.getEtag(); LOG.debug(" Photo ETag: " + (photoEtag != null ? photoEtag : "(No contact photo uploaded)")); LOG.debug("Self link: " + contact.getSelfLink().getHref()); LOG.debug("Edit link: " + contact.getEditLink().getHref()); LOG.debug("ETag: " + contact.getEtag()); LOG.debug("-------------------------------------------\n"); }