Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

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

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file.

Usage

From source file:WebstartLauncher.java

private String createRmiEnhancedJnlp(String rmiConfigFilePath, String jnlpUrl)
        throws Exception, FileNotFoundException {
    Document modifiedJnlp = createEnhancedJnlp(rmiConfigFilePath, jnlpUrl);
    String localName = getLocalName(jnlpUrl);
    modifiedJnlp.printTo(new PrintStream(new FileOutputStream(localName)));
    return localName;
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Saves the given key to the given file. This method will NOT clobber
 * existing files- will return false if file exists The file will be
 * created, along with any parent directories needed.
 *
 * @param file name of file to save to/*w  w w  . ja v  a 2  s.  c  o m*/
 * @param key  key to save
 *
 * @return true if successfully written, false otherwise
 */
public static boolean storeKey(String file, Key key) {
    File f = new File(file);
    if (!f.exists())
        try {
            if (f.getParentFile() != null)
                f.getParentFile().mkdirs();
            f.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        }
    else
        return false;

    try (FileOutputStream fos = new FileOutputStream(file); PrintStream ps = new PrintStream(fos)) {
        ps.println(Base64.encodeBase64String(key.getEncoded()));
        return true;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }
}

From source file:eu.scape_project.up2ti.output.SimpleKeyValueOutputWriter.java

/**
 * Record method for command line application.
 *
 * @param resultMap Result map where K: recordkey-identificationtype, V:
 * tool identificationtype identificationresult)
 *//*from w  w w  .java 2 s.c o  m*/
@Override
public void write(HashMap<String, List<String>> resultMap) {
    Iterator iter = resultMap.keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        List<String> valueList = resultMap.get(key);
        PrintStream pout = null;
        if (outputPathStr != null) {
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(outputPathStr, true);
                pout = new PrintStream(fos);
                System.setOut(pout);
            } catch (FileNotFoundException ex) {
                LOG.error("File not found error", ex);
            }
        }
        for (String value : valueList) {
            System.out.println(key + separator + value);
        }
        if (pout != null) {
            pout.close();
        }
    }
}

From source file:net.jsign.PESignerTaskTest.java

/**
 * Redirects the Ant output to the specified stream.
 *///from  www . j av  a 2s .c  o m
private void redirectOutput(OutputStream out) {
    DefaultLogger logger = new DefaultLogger();
    logger.setOutputPrintStream(new PrintStream(out));
    logger.setMessageOutputLevel(Project.MSG_INFO);
    project.addBuildListener(logger);
}

From source file:com.aestasit.markdown.Markdown.java

public static String extractText(final RootNode node) {
    final ByteArrayOutputStream data = new ByteArrayOutputStream();
    new TextExtractor(new PrintStream(data)).visit(node);
    return new String(data.toByteArray());
}

From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java

public static Task createTask(Task t) throws IOException {
    String _url = getBaseUri().build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    addRequestHeader(conn, false);//from   www .  j a  v a2 s.  c  o  m
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Title
    jgen.writeStartObject();
    jgen.writeStringField(Keys.Task.TITLE, t.getTitle());
    jgen.writeStringField(Keys.Task.COMPLETED, Boolean.toString(t.getIsCompleted()));
    jgen.writeStringField(Keys.Task.DESC, t.getDescription());
    jgen.writeStringField(Keys.Task.DEADLINE, Long.toString(t.getEndTimeInMillis()));
    jgen.writeStringField(Keys.Task.DATE_CREATED, t.getDateCreated());
    jgen.writeStringField(Keys.Task.DATE_ASSIGNED, t.getDateAssigned());
    jgen.writeStringField(Keys.Task.CRITERIA, t.getCompletionCriteria());
    jgen.writeStringField(Keys.Task.ASSIGNED_TO, t.getAssignedTo());
    jgen.writeStringField(Keys.Task.ASSIGNED_FROM, t.getAssignedFrom());
    jgen.writeStringField(Keys.Task.CREATED_BY, t.getCreatedBy());
    jgen.writeEndObject();
    jgen.close();

    String payload = json.toString("UTF8");
    ps.close();
    // Get server response
    sendPostPayload(conn, payload);
    String response = getServerResponse(conn);
    Map<String, String> responseMap = new HashMap<String, String>();
    if (responseMap.containsKey(Keys.Task.ID)) {
        t.setID(responseMap.get(Keys.Task.ID));
    }
    return t;
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testInvalidHandshake() throws IOException, JSONException, InterruptedException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);//from  w w w  .  j a  v  a2s  . co  m
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("bar")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertTrue(JSONObject.NULL != error);
    while (!out.checkError()) {
        out.println(buildRequest(0, "makeToast", Lists.newArrayList("baz")));
    }
    client.close();
    // Further connections should fail;
    client = new Socket();
    try {
        client.connect(address);
        fail();
    } catch (IOException e) {
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestPeriods.java

@Test
public void testRun03() throws InterruptedException {
    PrintStream printStream = new PrintStream(outputStream);
    this.periods = new Periods(50, printStream);

    new Thread(this.periods).start();

    Thread.sleep(400);/*from   ww  w. j ava2s .c o m*/

    this.periods.stop();

    byte[] bytes = this.outputStream.toByteArray();
    assertTrue("The length is not correct.", bytes.length >= 6);
    assertArrayEquals("The arrays are not correct.", Arrays.copyOf(bytes, 6),
            new byte[] { '.', '.', '.', '.', '.', '.' });
}

From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java

public static String createNote(Note n) throws Exception {
    // Server URL setup
    String _url = getBaseUri().build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.POST);
    //addRequestHeader(conn, true);

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();//from  w  w  w.ja va 2  s  . c  om
    jgen.writeStringField(Keys.Note.CREATED_BY, n.getCreatedBy());
    jgen.writeStringField(Keys.Note.TITLE, n.getTitle());
    jgen.writeStringField(Keys.Note.DESC, n.getDescription());
    jgen.writeStringField(Keys.Note.CONTENT, n.getContent());
    jgen.writeStringField(Keys.Note.UPDATED, n.getDateCreated());
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    Log.d("CREATENOTE_payload", payload);
    ps.close();

    // Send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);
    Log.d("CREATENOTE_response", response);

    String ID = "";
    if (!response.isEmpty()) {
        JsonNode tree = MAPPER.readTree(response);
        if (!tree.has(Keys.Note.ID))
            ID = "-1";
        else
            ID = tree.get(Keys.Note.ID).asText();
    }

    conn.disconnect();
    return ID;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGeneratorSlowTest.java

/**
 * Sets up System.out and System.err print streams before each test
 *///from  w w w .  j  a  va  2  s. c o  m
@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
}