Example usage for java.io PrintStream print

List of usage examples for java.io PrintStream print

Introduction

In this page you can find the example usage for java.io PrintStream print.

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:com.bigdata.dastor.tools.SSTableExport.java

static void export(SSTableReader reader, PrintStream outs, String[] excludes) throws IOException {
    SSTableScanner scanner = reader.getScanner(INPUT_FILE_BUFFER_SIZE);
    Set<String> excludeSet = new HashSet();

    if (excludes != null)
        excludeSet = new HashSet<String>(Arrays.asList(excludes));

    outs.println("{");

    while (scanner.hasNext()) {
        IteratingRow row = scanner.next();
        if (excludeSet.contains(row.getKey().key))
            continue;
        try {//from ww w. jav a2s  .  com
            String jsonOut = serializeRow(row);
            outs.print("  " + jsonOut);
            if (scanner.hasNext())
                outs.println(",");
            else
                outs.println();
        } catch (IOException ioexcep) {
            System.err.println("WARNING: Corrupt row " + row.getKey().key + " (skipping).");
            continue;
        } catch (OutOfMemoryError oom) {
            System.err.println("ERROR: Out of memory deserializing row " + row.getKey().key);
            continue;
        }
    }

    outs.println("}");
    outs.flush();
}

From source file:org.imsglobal.simplelti.SimpleLTIUtil.java

public static Properties doLaunch(String lti2EndPoint, Properties newMap) {
    M_log.warning("Warning: SimpleLTIUtil using deprecated non-POST launch to -" + lti2EndPoint);
    Properties retProp = new Properties();
    retProp.setProperty("status", "fail");

    String postData = "";
    // Yikes - iterating through properties is nasty
    for (Object okey : newMap.keySet()) {
        if (!(okey instanceof String))
            continue;
        String key = (String) okey;
        if (key == null)
            continue;
        String value = newMap.getProperty(key);
        if (value == null)
            continue;
        if (value.equals(""))
            continue;
        value = encodeFormText(value);/*w w w  .  j a  va  2s  .  c  o  m*/
        if (postData.length() > 0)
            postData = postData + "&";
        postData = postData + encodeFormText(key) + "=" + value;
    }
    if (postData != null)
        retProp.setProperty("_post_data", postData);
    dPrint("LTI2 POST=" + postData);

    String postResponse = null;

    URLConnection urlc = null;
    try {
        // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html
        URL url = new URL(lti2EndPoint);

        InputStream inp = null;
        // make connection, use post mode, and send query
        urlc = url.openConnection();
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(postData);
        ps.close();
        dPrint("Post Complete");
        inp = urlc.getInputStream();

        // Retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(inp));
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
            sb.append("\n");
        }
        br.close();
        postResponse = sb.toString();

        if (postResponse == null) {
            setErrorMessage(retProp, "Launch REST Web Service returned nothing");
            return retProp;
        }
    } catch (Exception e) {
        // Retrieve error stream if it exists
        if (urlc != null && urlc instanceof HttpURLConnection) {
            try {
                HttpURLConnection urlh = (HttpURLConnection) urlc;
                BufferedReader br = new BufferedReader(new InputStreamReader(urlh.getErrorStream()));
                String str;
                StringBuffer sb = new StringBuffer();
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                    sb.append("\n");
                }
                br.close();
                postResponse = sb.toString();
                dPrint("LTI ERROR response=" + postResponse);
            } catch (Exception f) {
                dPrint("LTI Exception in REST call=" + e);
                // e.printStackTrace();
                setErrorMessage(retProp, "Failed REST service call. Exception=" + e);
                postResponse = null;
                return retProp;
            }
        } else {
            dPrint("LTI General Failure" + e.getMessage());
            // e.printStackTrace();
        }
    }

    if (postResponse != null)
        retProp.setProperty("_post_response", postResponse);
    dPrint("LTI2 Response=" + postResponse);
    // Check to see if we received anything - and then parse it
    Map<String, String> respMap = null;
    if (postResponse == null) {
        setErrorMessage(retProp, "Web Service Returned Nothing");
        return retProp;
    } else {
        if (postResponse.indexOf("<?xml") != 0) {
            int pos = postResponse.indexOf("<launchResponse");
            if (pos > 0) {
                M_log.warning("Warning: Dropping first " + pos
                        + " non-XML characters of response to find <launchResponse");
                postResponse = postResponse.substring(pos);
            }
        }
        respMap = XMLMap.getMap(postResponse);
    }
    if (respMap == null) {
        String errorOut = postResponse;
        if (errorOut.length() > 500) {
            errorOut = postResponse.substring(0, 500);
        }
        M_log.warning("Error Parsing Web Service XML:\n" + errorOut + "\n");
        setErrorMessage(retProp, "Error Parsing Web Service XML");
        return retProp;
    }

    // We will tolerate this one backwards compatibility
    String launchUrl = respMap.get("/launchUrl");
    String launchWidget = null;

    if (launchUrl == null) {
        launchUrl = respMap.get("/launchResponse/launchUrl");
    }

    if (launchUrl == null) {
        launchWidget = respMap.get("/launchResponse/widget");

        /* Remove until we have jTidy 0.8 or later in the repository
        if ( launchWidget != null && launchWidget.length() > 0 ) {
                 M_log.warning("Pre Tidy:\n"+launchWidget);
                 Tidy tidy = new Tidy();
                 tidy.setIndentContent(true);
                 tidy.setSmartIndent(true);
                 tidy.setPrintBodyOnly(true);
                 tidy.setTidyMark(false);
                 // tidy.setQuiet(true);
                 // tidy.setShowWarnings(false);
                 InputStream is = new ByteArrayInputStream(launchWidget.getBytes());
                 OutputStream os = new ByteArrayOutputStream();
                 tidy.parse(is,os);
                 String tidyOutput = os.toString();
                 M_log.warning("Post Tidy:\n"+tidyOutput);
                 if ( tidyOutput != null && tidyOutput.length() > 0 ) launchWidget = os.toString();
              }
        */
    }

    dPrint("launchUrl = " + launchUrl);
    dPrint("launchWidget = " + launchWidget);

    if (launchUrl == null && launchWidget == null) {
        String eMsg = respMap.get("/launchResponse/code") + ":" + respMap.get("/launchResponse/description");
        setErrorMessage(retProp, "Error on Launch:" + eMsg);
        return retProp;
    }

    if (launchUrl != null)
        retProp.setProperty("launchurl", launchUrl);
    if (launchWidget != null)
        retProp.setProperty("launchwidget", launchWidget);
    String postResp = respMap.get("/launchResponse/type");
    if (postResp != null)
        retProp.setProperty("type", postResp);
    retProp.setProperty("status", "success");

    return retProp;
}

From source file:edu.utah.further.core.api.xml.XmlUtil.java

/**
 * @param xmlReader/* w w w  .  j a va 2 s. co m*/
 * @param index
 */
private static void printAttribute(final PrintStream os, final XMLStreamReader xmlReader, final int index) {
    final String prefix = xmlReader.getAttributePrefix(index);
    final String namespace = xmlReader.getAttributeNamespace(index);
    final String localName = xmlReader.getAttributeLocalName(index);
    final String value = xmlReader.getAttributeValue(index);
    os.print(Strings.SPACE_STRING);
    os.print(getName(prefix, namespace, localName));
    os.print("=" + quote(value));
}

From source file:com.splicemachine.homeless.TestUtils.java

public static int printResult(String statement, ResultSet rs, PrintStream out) throws SQLException {
    if (rs.isClosed()) {
        return 0;
    }/* w  w  w . j a v  a2  s .com*/
    int resultSetSize = 0;
    out.println();
    out.println(statement);
    List<Map> maps = TestUtils.resultSetToOrderedMaps(rs);
    if (maps.size() > 0) {
        List<String> keys = new ArrayList<String>(maps.get(0).keySet());
        for (String col : keys) {
            out.print(" " + col + " |");
        }
        out.println();
        for (int i = 0; i < keys.size(); ++i) {
            out.print("-----");
        }
        out.println();
        for (Map map : maps) {
            ++resultSetSize;
            for (String key : keys) {
                out.print(" " + map.get(key) + " |");
            }
            out.println();
        }
    }
    out.println("--------------------");
    out.println(resultSetSize + " rows");
    return resultSetSize;
}

From source file:org.apache.hadoop.hdfs.server.namenode.web.resources.NamenodeWebHdfsMethods.java

private static StreamingOutput getListingStream(final NameNode np, final String p) throws IOException {
    final DirectoryListing first = getDirectoryListing(np, p, HdfsFileStatus.EMPTY_NAME);

    return new StreamingOutput() {
        @Override//from  w  w w .  j a  v a 2s.  c  om
        public void write(final OutputStream outstream) throws IOException {
            final PrintStream out = new PrintStream(outstream);
            out.println("{\"" + FileStatus.class.getSimpleName() + "es\":{\"" + FileStatus.class.getSimpleName()
                    + "\":[");

            final HdfsFileStatus[] partial = first.getPartialListing();
            if (partial.length > 0) {
                out.print(JsonUtil.toJsonString(partial[0], false));
            }
            for (int i = 1; i < partial.length; i++) {
                out.println(',');
                out.print(JsonUtil.toJsonString(partial[i], false));
            }

            for (DirectoryListing curr = first; curr.hasMore();) {
                curr = getDirectoryListing(np, p, curr.getLastName());
                for (HdfsFileStatus s : curr.getPartialListing()) {
                    out.println(',');
                    out.print(JsonUtil.toJsonString(s, false));
                }
            }

            out.println();
            out.println("]}}");
        }
    };
}

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;//from  w  ww. ja v a 2s.co m
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        //out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String s = node.getNodeValue();
        if (s != null && s.length() > 0) {
            out.print(' ');
            out.print(s);
        }
        out.print("?>");
        break;
    }

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:org.apache.any23.extractor.microdata.MicrodataParser.java

/**
 * Returns a <i>JSON</i> containing the list of all extracted Microdata,
 * as described at <a href="http://www.w3.org/TR/microdata/#json">Microdata JSON Specification</a>.
 *
 * @param document document to be processed.
 * @param ps the {@link java.io.PrintStream} to write JSON to
 *//*www  .  ja  va2s  .  c  o  m*/
public static void getMicrodataAsJSON(Document document, PrintStream ps) {
    final MicrodataParserReport report = getMicrodata(document);
    final ItemScope[] itemScopes = report.getDetectedItemScopes();
    final MicrodataParserException[] errors = report.getErrors();

    ps.append("{ ");

    // Results.
    ps.append("\"result\" : [");
    for (int i = 0; i < itemScopes.length; i++) {
        if (i > 0) {
            ps.print(", ");
        }
        ps.print(itemScopes[i].toJSON());
    }
    ps.append("] ");

    // Errors.
    if (errors != null && errors.length > 0) {
        ps.append(", ");
        ps.append("\"errors\" : [");
        for (int i = 0; i < errors.length; i++) {
            if (i > 0) {
                ps.print(", ");
            }
            ps.print(errors[i].toJSON());
        }
        ps.append("] ");
    }

    ps.append("}");
}

From source file:Armadillo.Analytics.Base.FastMathCalc.java

/**
 * Print an array./*from  w  ww.j  ava2  s  .  co  m*/
 * @param out text output stream where output should be printed
 * @param name array name
 * @param expectedLen expected length of the array
 * @param array2d array data
 */
static void printarray(PrintStream out, String name, int expectedLen, double[][] array2d) {
    out.println(name);
    checkLen(expectedLen, array2d.length);
    out.println(TABLE_START_DECL + " ");
    int i = 0;
    for (double[] array : array2d) { // "double array[]" causes PMD parsing error
        out.print("        {");
        for (double d : array) { // assume inner array has very few entries
            out.printf("%-25.25s", format(d)); // multiple entries per line
        }
        out.println("}, // " + i++);
    }
    out.println(TABLE_END_DECL);
}

From source file:com.wandrell.example.swss.client.console.ConsoleClient.java

/**
 * Calls the endpoint in the specified URI by using the received client.
 * <p>/*from   w  ww .j  av a2 s .c  o m*/
 * This client is expected to be prepared for calling the endpoint, which
 * mostly means being set up for the same security protocol it uses.
 * <p>
 * If an exception occurs while using the client an error warning will be
 * printed in the console.
 *
 * @param client
 *            client which will call the endpoint
 * @param uri
 *            URI for the endpoint
 * @param output
 *            output for the client to print information
 * @param scanner
 *            scanner for the input
 */
private static final void callEndpoint(final EntityClient client, final String uri, final PrintStream output,
        final Scanner scanner) {
    final ExampleEntity entity; // Queried entity
    final Integer id; // Id for the query

    output.println("------------------------------------");
    output.println("Write the id of the entity to query.");
    output.println("The id 1 is always valid.");
    output.println("------------------------------------");

    output.println();
    output.print("Id: ");
    id = getInteger(scanner);
    output.println();

    try {
        entity = client.getEntity(uri, id);

        if ((entity == null) || (entity.getId() < 0)) {
            // No entity found
            output.println(String.format("No entity with id %d exists", id));
        } else {
            // Entity found
            output.println("Found entity.");
            output.println();
            output.println(String.format("Entity id:\t%d", entity.getId()));
            output.println(String.format("Entity name:\t%s", entity.getName()));
        }
    } catch (final NestedRuntimeException e) {
        output.println(String.format("Error: %s", e.getMostSpecificCause().getMessage()));
    } catch (final Exception e) {
        output.println(String.format("Error: %s", e.getMessage()));
    }

    // Waits so the result information can be checked
    waitForEnter(output, scanner);
}

From source file:hu.bme.mit.sette.run.Run.java

private static Tool readTool(BufferedReader in, PrintStream out) throws IOException {
    // select tool
    Tool[] tools = ToolRegister.toArray();
    Tool tool = null;/*from  w  w  w.j  av  a  2  s.c o m*/
    while (tool == null) {
        out.println("Available tools:");
        for (int i = 0; i < tools.length; i++) {
            out.println(String.format("  [%d] %s", i + 1, tools[i].getName()));
        }

        out.print("Select tool: ");

        String line = in.readLine();

        if (line == null) {
            out.println("EOF detected, exiting");
            return null;
        } else if (StringUtils.isBlank(line)) {
            out.println("Exiting");
            return null;
        }

        line = line.trim();
        int idx = -1;

        for (int i = 0; i < tools.length; i++) {
            if (tools[i].getName().equalsIgnoreCase(line)) {
                idx = i;
                break;
            }
        }

        if (idx >= 0) {
            tool = tools[idx];
        } else {
            try {
                tool = tools[Integer.parseInt(line) - 1];
            } catch (Exception e) {
                tool = null;
            }
        }

        if (tool == null) {
            out.println("Invalid tool: " + line.trim());
        }
    }

    out.println("Selected tool: " + tool.getName());

    return tool;
}