Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:com.kelveden.rastajax.servlet.DefaultHtmlServlet.java

private void writeRepresentationToResponse(Set<FlatResource> representation, HttpServletResponse httpResponse)
        throws IOException {

    httpResponse.setContentType("text/html; charset=utf8");

    final OutputStream outputStream = httpResponse.getOutputStream();
    final PrintStream printStream = new PrintStream(outputStream);

    printStream.println("<html>");
    printStream.println("<body>");
    printStream.println("<head>");
    printStream.println("<style type=\"text/css\">");
    printStream.println("* { font-size:10px; }");
    printStream.println("table { border-width: 1px; border-collapse: collapse; margin-left: 10px; }");
    printStream.println("table th { border: 1px solid; padding: 4px; background-color: #dedede; }");
    printStream.println("table td { border: 1px solid; padding: 4px; }");
    printStream.println("</style>");
    printStream.println("</head>");

    for (FlatResource resource : representation) {
        writeResource(resource, printStream);
    }//  www .j  a  va  2 s  . c om

    printStream.println("</body>");
    printStream.println("</html>");

    printStream.flush();
}

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * //  w w  w  .j a v  a2 s  .  co m
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();

        Random rng = new Random();
        String key = API_KEYS[rng.nextInt(API_KEYS.length)];
        hout.println(key);

        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
            mNotificationManager.cancelAll();
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/** Save this object to the given path as a file */
public void serialize(String path) {
    try {/*w  w  w.j  a v a 2  s.  co m*/
        File file = new File(path);
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        PrintStream printer = new PrintStream(outStream);
        //ObjectOutputStream objStream = new ObjectOutputStream(outStream);

        log.info("Wrote session definition to xml");
        printer.print(this.toString());

        printer.flush();
        printer.close();

        //objStream.writeObject(xml);
        //objStream.close();
        outStream.close();
    } catch (IOException e) {
        System.out.println("IO error writing session to a file");
        e.printStackTrace();
    }
}

From source file:org.codehaus.enunciate.modules.java_client.JavaClientDeploymentModule.java

/**
 * Reads a resource into string form.//  w  ww. java 2s .c om
 *
 * @param resource The resource to read.
 * @return The string form of the resource.
 */
protected String readResource(String resource) throws IOException, EnunciateException {
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("sample_service_method", getModelInternal().findExampleWebMethod());
    model.put("sample_resource", getModelInternal().findExampleResourceMethod());

    URL res = JavaClientDeploymentModule.class.getResource(resource);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    try {
        processTemplate(res, model, out);
        out.flush();
        bytes.flush();
        return bytes.toString("utf-8");
    } catch (TemplateException e) {
        throw new EnunciateException(e);
    }
}

From source file:cpcc.vvrte.services.js.JavascriptServiceTest.java

@Test
public void shouldHandleVvStorage() throws IOException {
    MyBuiltInFunctions functions = new MyBuiltInFunctions();
    JavascriptService jss = new JavascriptServiceImpl(logger, serviceResources, functions);
    jss.addAllowedClassRegex("cpcc.vvrte.services.js.JavascriptServiceTest\\$MyBuiltInFunctions");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream stdOut = new PrintStream(out, true);
    VvRteFunctions.setStdOut(stdOut);/*from ww  w.ja v  a  2 s  .co m*/

    InputStream scriptStream = this.getClass().getResourceAsStream("storage-test.js");
    String script = IOUtils.toString(scriptStream, "UTF-8");
    assertThat(script).isNotNull().isNotEmpty();

    VirtualVehicle vv = new VirtualVehicle();
    vv.setId(123);
    vv.setCode(script);
    vv.setApiVersion(1);
    vv.setUuid("599cda7e-a042-11e5-a5b4-ffed137d569e");

    functions.setMigrate(false);
    JavascriptWorker sut = jss.createWorker(vv, false);
    sut.run();
    stdOut.flush();

    // System.out.println("shouldHandleVvRte() result: '" + x.getResult() + "'");
    // System.out.println("shouldHandleVvRte() output: '" + out.toString("UTF-8") + "'");
    assertThat(sut.getWorkerState()).isNotNull().isEqualTo(VirtualVehicleState.FINISHED);

    InputStream resultStream = this.getClass().getResourceAsStream("storage-test-expected-result.txt");
    String expectedResult = IOUtils.toString(resultStream, "UTF-8");

    assertThat(out.toString("UTF-8")).isNotNull().isEqualTo(expectedResult);

    verify(sessionManager, times(3)).commit();
    verify(perthreadManager).cleanup();
}

From source file:volumesculptor.shell.Main.java

/**
 * Evaluate JavaScript source.//from   w  w w.  jav a2s .co m
 *
 * @param cx       the current context
 * @param filename the name of the file to compile, or null
 *                 for interactive mode.
 * @throws IOException    if the source could not be read
 * @throws RhinoException thrown during evaluation of source
 */
public static TriangleMesh processSource(Context cx, String filename, Object[] args, boolean show)
        throws IOException {
    if (filename == null || filename.equals("-")) {
        Scriptable scope = getShellScope();
        PrintStream ps = global.getErr();
        if (filename == null) {
            // print implementation version
            ps.println(cx.getImplementationVersion());
        }

        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc == null) {
            charEnc = System.getProperty("file.encoding");
        }
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(global.getIn(), charEnc));
        } catch (UnsupportedEncodingException e) {
            throw new UndeclaredThrowableException(e);
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            if (filename == null)
                ps.print(prompts[0]);
            ps.flush();
            String source = "";

            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = in.readLine();
                } catch (IOException ioe) {
                    ps.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                ps.print(prompts[1]);
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, null);
                if (script != null) {

                    Object result = script.exec(cx, scope);
                    // Avoid printing out undefined or function definitions.
                    if (result != Context.getUndefinedValue()
                            && !(result instanceof Function && source.trim().startsWith("function"))) {
                        try {
                            ps.println(Context.toString(result));
                        } catch (RhinoException rex) {
                            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                        }
                    }
                    NativeArray h = global.history;
                    h.put((int) h.getLength(), h, source);
                    return executeMain(cx, scope, show, args);
                }
            } catch (RhinoException rex) {
                ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                exitCode = EXITCODE_RUNTIME_ERROR;
            } catch (VirtualMachineError ex) {
                // Treat StackOverflow and OutOfMemory as runtime errors
                ex.printStackTrace();
                String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
                Context.reportError(msg);
                exitCode = EXITCODE_RUNTIME_ERROR;
            }
        }
        ps.println();
    } else if (useRequire && filename.equals(mainModule)) {
        require.requireMain(cx, filename);
    } else {
        return processFile(cx, getScope(filename), filename, args, show);
    }

    return null;
}

From source file:org.codehaus.enunciate.modules.xfire_client.XFireClientDeploymentModule.java

/**
 * Reads a resource into string form.//from  w  w  w  .java 2 s  .  co m
 *
 * @param resource The resource to read.
 * @return The string form of the resource.
 */
protected String readResource(String resource) throws IOException, EnunciateException {
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("sample_service_method", getModelInternal().findExampleWebMethod());
    model.put("sample_resource", getModelInternal().findExampleResource());

    URL res = XFireClientDeploymentModule.class.getResource(resource);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    try {
        processTemplate(res, model, out);
        out.flush();
        bytes.flush();
        return bytes.toString("utf-8");
    } catch (TemplateException e) {
        throw new EnunciateException(e);
    }
}

From source file:eu.europa.ec.fisheries.uvms.plugins.inmarsat.twostage.Connect.java

private String issueCommand(PollType poll, PrintStream out, InputStream in, String dnid, String path,
        String url, String port) throws TelnetException, IOException {
    String filename = getFileName(path);
    FileOutputStream stream = null;
    try {//from  w  ww  .j  av  a 2  s .c o  m
        stream = new FileOutputStream(filename);
    } catch (FileNotFoundException e) {
        LOG.warn("Could not read/create file for TwoStage Command: {}", filename);
    }
    String result;
    if (poll != null) {
        result = sendPollCommand(poll, out, in, stream, url, port);
    } else {
        result = sendDownloadCommand(out, in, stream, dnid, url, port);
    }
    if (stream != null) {
        stream.flush();
        stream.close();

        //Delete file for polls, these are persisted elsewhere
        if (poll != null) {
            File f = new File(filename);
            if (f.exists() && f.isFile()) {
                f.delete();
            }
        }
    }
    out.print("QUIT \r\n");
    out.flush();
    return result;
}

From source file:org.openecomp.sdnc.sli.SvcLogicNode.java

public void printAsXml(PrintStream pstr, int indentLvl) {
    if (visited) {
        return;/*from   w ww .  jav a  2s .  c om*/
    }
    // Print node tag
    for (int i = 0; i < indentLvl; i++) {
        pstr.print("  ");
    }
    pstr.print("<");
    pstr.print(this.getNodeType());

    Set<Map.Entry<String, SvcLogicExpression>> attrSet = attributes.entrySet();
    for (Iterator<Map.Entry<String, SvcLogicExpression>> iter = attrSet.iterator(); iter.hasNext();) {
        Map.Entry<String, SvcLogicExpression> curAttr = iter.next();
        pstr.print(" ");
        pstr.print(curAttr.getKey());
        pstr.print("='`");
        pstr.print(curAttr.getValue());
        pstr.print("'`");
    }

    if (((parameters == null) || (parameters.isEmpty())) && ((outcomes == null) || outcomes.isEmpty())) {
        pstr.print("/>\n");
        pstr.flush();
        return;
    } else {
        pstr.print(">\n");
    }

    // Print parameters (if any)
    if (parameters != null) {
        Set<Map.Entry<String, SvcLogicExpression>> paramSet = parameters.entrySet();
        for (Iterator<Map.Entry<String, SvcLogicExpression>> iter = paramSet.iterator(); iter.hasNext();) {
            for (int i = 0; i < indentLvl + 1; i++) {
                pstr.print("  ");
            }
            pstr.print("<parameter");
            Map.Entry<String, SvcLogicExpression> curAttr = iter.next();
            pstr.print(" name='");
            pstr.print(curAttr.getKey());
            pstr.print("' value='`");
            pstr.print(curAttr.getValue().toString());
            pstr.print("`'/>\n");
        }
    }

    // Print outcomes (if any)
    if (outcomes != null) {
        Set<Map.Entry<String, SvcLogicNode>> outcomeSet = outcomes.entrySet();
        for (Iterator<Map.Entry<String, SvcLogicNode>> iter = outcomeSet.iterator(); iter.hasNext();) {
            for (int i = 0; i < indentLvl + 1; i++) {
                pstr.print("  ");
            }
            pstr.print("<outcome");
            Map.Entry<String, SvcLogicNode> curAttr = iter.next();
            pstr.print(" value='");
            pstr.print(curAttr.getKey());
            pstr.print("'>\n");
            SvcLogicNode outNode = curAttr.getValue();
            outNode.printAsXml(pstr, indentLvl + 2);
            for (int i = 0; i < indentLvl + 1; i++) {
                pstr.print("  ");
            }
            pstr.print("</outcome>\n");
        }
    }

    // Print node end tag
    for (int i = 0; i < indentLvl; i++) {
        pstr.print("  ");
    }
    pstr.print("</");
    pstr.print(this.getNodeType());
    pstr.print(">\n");
    pstr.flush();

}

From source file:terse.vm.Terp.java

void appendWorldFile(String firstLine, String[] rest) throws IOException {
    if (loadingWorldFile) {
        return; // Don't cause infinite loop!
    }//  w w  w . ja va  2  s.c om
    if (worldFilename.length() == 0) {
        return; // For unit tests.
    }
    long timestamp = System.currentTimeMillis() / 1000;
    FileOutputStream fos = openFileAppend(worldFilename);
    PrintStream ps = new PrintStream(fos);
    ps.println(fmt("( %d %s", timestamp, firstLine));
    if (rest != null) {
        for (String s : rest) {
            ps.println(" " + s); // Stuff 1 space before each line.
        }
    }
    ps.println(fmt(") %d", timestamp));
    ps.flush();
    fos.flush();
    fos.close();
}