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

public synchronized String toString() 

Source Link

Document

Converts the buffer's contents into a string decoding bytes using the platform's default character set.

Usage

From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java

public static void main(String[] args) {
    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);/*from   w ww.j  av  a 2 s . co m*/
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    StringBuilder sbIndex = new StringBuilder(runnables.size() * 50);
    StringBuilder sbDetails = new StringBuilder(runnables.size() * 200);

    sbIndex.append("\n<table border=\"0\">\n");

    Type lastType = null;

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }

            Type type = Type.getType(c);
            if (type != lastType) {
                sbIndex.append("  <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n");
                sbDetails.append("<h2> " + type + " Applications </h2>\n");
                lastType = type;
            }
            String descr = "N/A";
            try {
                descr = (String) c.getDeclaredField("DESCRIPTION").get(null);
            } catch (Exception e) {
            }
            String longDescr = "descr";
            try {
                longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null);
            } catch (Exception e) {
            }

            sbIndex.append("  <tr>\n");
            sbIndex.append("    <td> <a href=\"#").append(c.getSimpleName()).append("\">")
                    .append(c.getSimpleName()).append("</a> </td>\n");
            sbIndex.append("    <td> ").append(descr).append(" </td>\n");
            sbIndex.append("  </tr>\n");

            sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName())
                    .append("</h3>\n");
            sbDetails.append("<p>").append(longDescr).append("</p>\n");

            try {
                Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os);
                AbstractOptionFactory.printHelp(jsap, c.getName(), ps);
                sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>");
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }

        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    sbIndex.append("</table>\n\n");
    System.out.println(sbIndex);
    System.out.println(sbDetails);
}

From source file:geocodingissues.Main.java

/**
 * @param args the command line arguments
 *///from   w w w  .j ava 2s . c o  m
public static void main(String[] args) throws JSONException {
    Main x = new Main();
    ResultSet rs = null;

    x.establishConnection();
    //x.addColumns(); //already did this

    rs = x.getLatLong();

    int id;
    double latitude;
    double longitude;
    String req;

    String street_no;
    String street;
    String neighborhood;
    String locality;
    String PC;

    JSONObject jObject;
    JSONArray resultArray;
    JSONArray compArray;

    try {
        while (rs.next()) {
            id = rs.getInt("id");
            latitude = rs.getDouble("latitude");
            longitude = rs.getDouble("longitude");

            //System.out.println("id: " + id);

            req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + Double.toString(latitude) + ","
                    + Double.toString(longitude)
                    + "&result_type=street_address|neighborhood|locality|postal_code&key=" + key;

            try {
                URL url = new URL(req + "&sensor=false");
                URLConnection conn = url.openConnection();
                ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
                IOUtils.copy(conn.getInputStream(), output);
                output.close();
                req = output.toString();
            } catch (Exception e) {
                System.out.println("Geocoding Error");
            }
            if (req.contains("OVER_QUERY_LIMIT")) {
                System.out.println("Over Daily Query Limit");
                System.exit(0);
            }
            if (!req.contains("ZERO_RESULTS")) {
                //System.out.println("req: ");
                //System.out.println(req);
                jObject = new JSONObject(req);
                resultArray = jObject.getJSONArray("results");

                // Retrieve information on street address and insert into table
                compArray0 = resultArray.getJSONObject(0).getJSONArray("address_components");
                street_no = compArray0.getJSONObject(0).getString("long_name");
                street = compArray0.getJSONObject(1).getString("long_name");
                x.insertValues(id, street_no, street);

                // Retrieve information on neighborhood and insert into table
                compArray1 = resultArray.getJSONObject(1).getJSONArray("address_components");
                neighborhood = compArray1.getJSONObject(0).getString("long_name");
                x.insertNbhd(id, neighborhood);

                // Retrieve information on locality and insert into table
                compArray2 = resultArray.getJSONObject(2).getJSONArray("address_components");
                locality = compArray2.getJSONObject(0).getString("long_name");
                x.insertLocality(id, locality);

                // Retrieve information on postal code and insert into table
                compArray3 = resultArray.getJSONObject(3).getJSONArray("address_components");
                PC = compArray3.getJSONObject(0).getString("long_name");
                x.insertPC(id, PC);
            }
        }
    } catch (Exception e) {
        System.out.println("Problem when updating the database.");
    }
    x.closeConnection();
}

From source file:Hex.java

public static void main(String[] args) {
    if (args.length != 3) {
        System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>");
        System.exit(1);//from w  w w.  jav a 2  s  . c o  m
    }
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream in = new FileInputStream(args[1]);
        int len = 0;
        byte buf[] = new byte[1024];
        while ((len = in.read(buf)) > 0)
            os.write(buf, 0, len);
        in.close();
        os.close();

        byte[] data = null;
        if (args[0].equals("dec"))
            data = decode(os.toString());
        else {
            String strData = encode(os.toByteArray());
            data = strData.getBytes();
        }

        FileOutputStream fos = new FileOutputStream(args[2]);
        fos.write(data);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from  ww  w  .j a v  a  2 s  .  co m
 *
 * @param operation The operation to invoke
 */
public static void main(String[] args) {
    try {
        /*OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("HelloWorld_sayHello");
        operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>");
        operation.setNamespaceURI("urn:jbosstest");
        operation.setOutputMessageName("HelloWorld_sayHelloResponse");
        operation.setOutputMessageText("<sayHello><return>0</return></sayHello>");
        operation.setSoapActionURI("");
        operation.setStyle("document");
        operation.setTargetMethodName("sayHello");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/

        OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("ConversionRateSoapIn");
        operation.setInputMessageText(
                "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>");
        operation.setNamespaceURI("http://www.webserviceX.NET/");
        operation.setOutputMessageName("ConversionRateSoapOut");
        operation.setOutputMessageText(
                "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>");
        operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate");
        operation.setStyle("document");
        operation.setTargetMethodName("ConversionRate");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx");

        // Determine if the operation style is RPC
        boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc");

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //envelope.addNamespaceDeclaration("", operation.getNamespaceURI());

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        //return strResponse;
    }

    catch (Throwable ex) {
        log.error("Error invoking operation:");
        log.error(ex.getMessage());
    }

    //return "";
}

From source file:Base64.java

public static void main(String[] args) throws IOException {
    boolean decode = false;
    int mode = 0;
    for (String arg : args) {
        if (arg.equals("-e")) {
            decode = false;/*from  ww  w . j  a  v a 2  s . c  o m*/
        } else if (arg.equals("-d")) {
            decode = true;
        } else if (arg.equals("-b64")) {
            mode = 0;
        } else if (arg.equals("-hqx")) {
            mode = 1;
        } else if (arg.equals("-a85")) {
            mode = 2;
        } else if (arg.equals("-l85")) {
            mode = 3;
        } else if (arg.equals("-k85")) {
            mode = 4;
        } else if (arg.equals("-uue")) {
            mode = 5;
        } else if (arg.equals("-xxe")) {
            mode = 6;
        } else if (arg.equals("--")) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1048576];
            int len = 0;
            while ((len = System.in.read(buf)) >= 0) {
                out.write(buf, 0, len);
            }
            out.close();
            if (decode) {
                switch (mode) {
                case 0:
                    System.out.println(new String(decodeBase64(out.toString())));
                    break;
                case 1:
                    System.out.println(new String(decodeBinHex(out.toString())));
                    break;
                case 2:
                    System.out.println(new String(decodeASCII85(out.toString())));
                    break;
                case 3:
                    System.out.println(new String(decodeLegacy85(out.toString())));
                    break;
                case 4:
                    System.out.println(new String(decodeKreative85(out.toString())));
                    break;
                case 5:
                    System.out.println(new String(decodeUU(out.toString())));
                    break;
                case 6:
                    System.out.println(new String(decodeXX(out.toString())));
                    break;
                }
            } else {
                switch (mode) {
                case 0:
                    System.out.println(encodeBase64(out.toByteArray()));
                    break;
                case 1:
                    System.out.println(encodeBinHex(out.toByteArray()));
                    break;
                case 2:
                    System.out.println(encodeASCII85(out.toByteArray()));
                    break;
                case 3:
                    System.out.println(encodeLegacy85(out.toByteArray()));
                    break;
                case 4:
                    System.out.println(encodeKreative85(out.toByteArray()));
                    break;
                case 5:
                    System.out.println(encodeUU(out.toByteArray()));
                    break;
                case 6:
                    System.out.println(encodeXX(out.toByteArray()));
                    break;
                }
            }
        } else if (decode) {
            switch (mode) {
            case 0:
                System.out.println(new String(decodeBase64(arg)));
                break;
            case 1:
                System.out.println(new String(decodeBinHex(arg)));
                break;
            case 2:
                System.out.println(new String(decodeASCII85(arg)));
                break;
            case 3:
                System.out.println(new String(decodeLegacy85(arg)));
                break;
            case 4:
                System.out.println(new String(decodeKreative85(arg)));
                break;
            case 5:
                System.out.println(new String(decodeUU(arg)));
                break;
            case 6:
                System.out.println(new String(decodeXX(arg)));
                break;
            }
        } else {
            switch (mode) {
            case 0:
                System.out.println(encodeBase64(arg.getBytes()));
                break;
            case 1:
                System.out.println(encodeBinHex(arg.getBytes()));
                break;
            case 2:
                System.out.println(encodeASCII85(arg.getBytes()));
                break;
            case 3:
                System.out.println(encodeLegacy85(arg.getBytes()));
                break;
            case 4:
                System.out.println(encodeKreative85(arg.getBytes()));
                break;
            case 5:
                System.out.println(encodeUU(arg.getBytes()));
                break;
            case 6:
                System.out.println(encodeXX(arg.getBytes()));
                break;
            }
        }
    }
}

From source file:Main.java

public static String toString(InputStream is) throws IOException {
    final ByteArrayOutputStream baos = toByteArrayOutputStream(is);
    return (baos != null) ? baos.toString() : null;
}

From source file:Main.java

static public String toHtml(Document xmldoc) throws TransformerException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    toHtml(xmldoc, baos);//  w  w  w  .  j  ava2  s  .c om
    return baos.toString();
}

From source file:Main.java

public static String marshal(Object o, Map<String, Object> properties) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshal(o, bos, properties);//from  w ww  . j  a va2  s  .c om
    return bos.toString();
}

From source file:Main.java

public static String getXmlString(JAXBElement versioningInfo, Boolean formatXml, Schema schema)
        throws JAXBException {
    String packageName = versioningInfo.getValue().getClass().getPackage().getName();
    JAXBContext context = JAXBContext.newInstance(packageName);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatXml);

    if (schema != null) {
        marshaller.setSchema(schema);//ww  w.j av a 2s. c  om
    }

    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    marshaller.marshal(versioningInfo, oStream);

    return oStream.toString();
}

From source file:Main.java

public static String marshal(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshal(o, bos, new HashMap<String, Object>());
    return bos.toString();
}