Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:JSONPManager.java

/**
 * A convenience method to wrap a JSON string in a callback function name
 * used to support JSONP requests.//from  w  w  w  . jav  a  2s .  c  o  m
 * In this version the wrapped JSON is sent directly to the user via the PrintWriter
 * More information: http://en.wikipedia.org/wiki/JSON#JSONP
 *
 * @param json     the json string
 * @param callback the name of the callback method
 * @param writer   the PrintWriter to use to output the JSONP
 */
public static void wrapJSON(String json, String callback, java.io.PrintWriter writer) {
    // could do other more interesting things here, but for the moment let's keep it simple   
    writer.print(callback + "(" + json + ");");

}

From source file:mobisocial.musubi.ui.util.FeedHTML.java

public static void writeObj(FileOutputStream fo, Context context, IdentitiesManager identitiesManager,
        MObject object) {//w  ww.j a v a2  s  .c o m
    //TODO: it would be better to put the export code inside the obj handlers
    MIdentity ident = identitiesManager.getIdentityForId(object.identityId_);
    if (ident == null)
        return;
    PrintWriter w = new PrintWriter(fo);
    w.print("<div>");
    w.print("<div style=\"float:left\">");

    w.print("<img src=\"data:image/jpeg;base64,");
    Bitmap thumb = UiUtil.safeGetContactThumbnail(context, identitiesManager, ident);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    thumb.compress(CompressFormat.JPEG, 90, bos);
    w.print(Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT));
    w.print("\">");

    w.print("</div>");
    w.print("<div>");
    w.print("<h6>");
    w.print(UiUtil.safeNameForIdentity(ident));
    w.print("</h6>");

    try {
        if (object.type_.equals(StatusObj.TYPE)) {
            w.print(new JSONObject(object.json_).getString(StatusObj.TEXT));
        } else if (object.type_.equals(PictureObj.TYPE)) {
            w.print("<img src=\"data:image/jpeg;base64,");
            w.print(Base64.encodeToString(object.raw_, Base64.DEFAULT));
            w.print("\">");
        } else {
            throw new RuntimeException("unsupported type " + object.type_);
        }

    } catch (Throwable t) {
        Log.e("HTML EXPORT", "failed to process obj", t);
        w.print("<i>only visibile in musubi</i>");
    }
    w.print("</div>");
    w.print("</div>");

    w.print("</body>");
    w.print("</html>");
    w.flush();
}

From source file:com.espertech.esper.antlr.ASTUtil.java

private static void renderNode(char[] ident, Tree node, PrintWriter printer) {
    printer.print(ident);
    if (node == null) {
        printer.print("NULL NODE");
    } else {/*from   w w w.  ja  va 2  s  .co m*/
        printer.print(node.getText());
        printer.print(" [");
        printer.print(node.getType());
        printer.print("]");

        if (node.getText() == null) {
            printer.print(" (null value in text)");
        } else if (node.getText().contains("\\")) {
            int count = 0;
            for (int i = 0; i < node.getText().length(); i++) {
                if (node.getText().charAt(i) == '\\') {
                    count++;
                }
            }
            printer.print(" (" + count + " backlashes)");
        }
    }
    printer.println();
}

From source file:SimpleProxyServer.java

/**
 * runs a single-threaded proxy server on
 * the specified local port. It never returns.
 *//*from w w  w  .  java 2  s  . c  o m*/
public static void runServer(String host, int remoteport, int localport) throws IOException {
    // Create a ServerSocket to listen for connections with
    ServerSocket ss = new ServerSocket(localport);

    final byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (true) {
        Socket client = null, server = null;
        try {
            // Wait for a connection on the local port
            client = ss.accept();

            final InputStream streamFromClient = client.getInputStream();
            final OutputStream streamToClient = client.getOutputStream();

            // Make a connection to the real server.
            // If we cannot connect to the server, send an error to the
            // client, disconnect, and continue waiting for connections.
            try {
                server = new Socket(host, remoteport);
            } catch (IOException e) {
                PrintWriter out = new PrintWriter(streamToClient);
                out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
                out.flush();
                client.close();
                continue;
            }

            // Get server streams.
            final InputStream streamFromServer = server.getInputStream();
            final OutputStream streamToServer = server.getOutputStream();

            // a thread to read the client's requests and pass them
            // to the server. A separate thread for asynchronous.
            Thread t = new Thread() {
                public void run() {
                    int bytesRead;
                    try {
                        while ((bytesRead = streamFromClient.read(request)) != -1) {
                            streamToServer.write(request, 0, bytesRead);
                            streamToServer.flush();
                        }
                    } catch (IOException e) {
                    }

                    // the client closed the connection to us, so close our
                    // connection to the server.
                    try {
                        streamToServer.close();
                    } catch (IOException e) {
                    }
                }
            };

            // Start the client-to-server request thread running
            t.start();

            // Read the server's responses
            // and pass them back to the client.
            int bytesRead;
            try {
                while ((bytesRead = streamFromServer.read(reply)) != -1) {
                    streamToClient.write(reply, 0, bytesRead);
                    streamToClient.flush();
                }
            } catch (IOException e) {
            }

            // The server closed its connection to us, so we close our
            // connection to our client.
            streamToClient.close();
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try {
                if (server != null)
                    server.close();
                if (client != null)
                    client.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsLocalSchemaExtractor.java

/****
 * This function parses all the json record files in a folder and returns a counts of the total occurrences of keys
 * in all files//from   www .ja  va2 s  . c  o m
 * 
 * @param inputFolder
 * @param outputFolder
 * @throws IOException
 */
private static void countKeysInJsonRecordsFolder(String inputFolder, String outputFile) throws IOException {
    File folder = new File(inputFolder);
    File[] listOfFiles = folder.listFiles();
    KeyValueCounter totalKeyValueCounter = new KeyValueCounter();
    KeyValueCounter currentKeyValueCounter = new KeyValueCounter();
    for (File currentFile : listOfFiles) {
        if (currentFile.isFile()) {
            logger.info("Processing file: " + currentFile.getName());
            currentKeyValueCounter = countKeysInJsonRecordsFile(
                    Paths.get(inputFolder, currentFile.getName()).toString());
            totalKeyValueCounter = deepMergeKeyValueCounter(totalKeyValueCounter, currentKeyValueCounter);
        } else if (currentFile.isDirectory()) {
            logger.warn("Sub-directory folders are currently ignored");
        }
    }
    //System.out.println(totalKeyCounter.toString());
    logger.info("---------------");
    logger.info(sortOutputByKey(totalKeyValueCounter));
    logger.info("saving output to file: ");
    File outpuFile = new File(outputFile);
    outpuFile.getParentFile().mkdirs();
    PrintWriter out = new PrintWriter(outputFile);
    out.print(sortOutputByKey(totalKeyValueCounter));
    out.close();
}

From source file:it.biztech.btable.util.Utils.java

public static void buildJsonResult(final OutputStream out, final Boolean success, final Object result) {
    final JSONObject jsonResult = new JSONObject();
    jsonResult.put("status", Boolean.toString(success));
    if (result != null) {
        jsonResult.put("result", result);
    }/*w  w  w .jav  a2s .  c o  m*/
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(out);
        pw.print(jsonResult.toString(2));
        pw.flush();
    } finally {
        IOUtils.closeQuietly(pw);
    }
}

From source file:Main.java

/**
 * Write characters. Character data is properly escaped.
 * //from  w  ww . j av a2  s  .co m
 * @param out
 *            The writer.
 * @param ch
 *            The character array.
 * @param start
 *            Start position.
 * @param length
 *            Substring length.
 */
public static void writeCharacters(PrintWriter out, char[] ch, int start, int length) {
    for (int j = start; j < start + length; j++) {
        char c = ch[j];
        if (c == '&') {
            out.print("&amp;");
        } else if (c == '"') {
            out.print("&quot;");
        } else if (c == '<') {
            out.print("&lt;");
        } else if (c == '>') {
            out.print("&gt;");
        } else if (c == '\'') {
            out.print("&apos;");
        } else {
            out.print(c);
        }
    }
}

From source file:Main.java

public static int outputNode(Node outputNode, PrintWriter outputWriter, int curPos) {
    NodeList nodes = outputNode.getChildNodes();
    int curNodeNum;
    if (outputNode.getNodeType() == Node.TEXT_NODE) {
        outputWriter.print(outputNode.getNodeValue());
    } else {/*from   w  w w.  j  a  v  a2s.c o m*/
        if (outputNode.getNodeName().equals("p")) {
            outputWriter.println();
        }

        for (curNodeNum = 0; curNodeNum < nodes.getLength(); curNodeNum++) {
            Node curNode = nodes.item(curNodeNum);
            curPos = outputNode(curNode, outputWriter, curPos);
            //System.out.println(curNode.getNodeName());
            //System.out.println(curNode.getNodeValue());
        }

    }
    return (curPos);
}

From source file:jeplus.util.LineEnds.java

/**
 * Replace line ends in the (text) file with the given string. This function creates a temporary file then delete and rename.
 * @param file/*from   www .j a  v  a2  s . c o m*/
 * @param newLN 
 */
protected static void convertFile(File file, String newLN) {
    try {
        BufferedReader fr = new BufferedReader(new FileReader(file));
        File tempfile = new File(file.getAbsolutePath() + ".temp");
        PrintWriter fw = new PrintWriter(new FileWriter(tempfile));
        String line = fr.readLine();
        while (line != null) {
            fw.print(line);
            fw.print(newLN);
            line = fr.readLine();
        }
        fr.close();
        fw.close();
        file.delete();
        if (!tempfile.renameTo(file)) {
            throw new Exception("Cannot rename " + tempfile.getName() + " to " + file.getName());
        }
    } catch (Exception ex) {
        logger.error("Error converting file " + file.getAbsolutePath(), ex);
    }
}

From source file:adviewer.util.JSONIO.java

/**
*   //from  w  w  w . j a v  a2  s .  c  o  m
*
* pre  :
* post :
*
* @param info
* @param f
* @throws JSONException
*/
public static void printJSONArrayToFile(String arrName, File f) throws JSONException {

    //convert the list back to a JSONObject list
    //this.jsonObjects =  infoListToJSONList( info );
    //this.setJsonStrings();

    try {

        PrintWriter writer = new PrintWriter(f);

        writer.print(JSONIO.printJSONArray(arrName));
    } catch (Exception e) {
        e.printStackTrace();
    }

}