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:edu.dfci.cccb.mev.stats.domain.cli.CliRWilcoxonBuilder.java

@Override
public Wilcoxon build() throws DatasetException {
    try (TemporaryFile sample1 = new TemporaryFile();
            TemporaryFile sample2 = new TemporaryFile();
            TemporaryFile wilcoxon = new TemporaryFile();
            ByteArrayOutputStream script = new ByteArrayOutputStream();
            PrintStream s = new PrintStream(script)) {

        try (PrintStream s1 = new PrintStream(new FileOutputStream(sample1));
                PrintStream s2 = new PrintStream(new FileOutputStream(sample2))) {
            s1.println(Lambda.join(column(first()), "\t"));
            if (second() != null)
                s2.println(Lambda.join(column(second()), "\t"));
        }/* ww w.j  av  a2s .c om*/

        s.println("SAMPLE1_FILE=\"" + sample1.getAbsolutePath() + "\"");
        s.println("SAMPLE2_FILE=" + (second() == null ? "NULL" : ("\"" + sample2.getAbsolutePath() + "\"")));
        s.println("ALT_HYPOTHESIS=\"" + hypothesis() + "\"");
        s.println("IS_PAIRED=" + valueOf(pair()).toString().toUpperCase());
        s.println("IS_CONF_INT=" + valueOf(confidentInterval()).toString().toUpperCase());
        s.println("WILCOX_OUT=\"" + wilcoxon.getAbsolutePath() + "\"");

        copy(getClass().getResourceAsStream("/wilcoxon.r"), s);

        r.eval(script.toString());

        try (BufferedReader reader = new BufferedReader(new FileReader(wilcoxon))) {
            reader.readLine();
            final double wStat = Double.parseDouble(reader.readLine().split("\t")[1]);
            final double pValue = Double.parseDouble(reader.readLine().split("\t")[1]);

            return new PojoWilcoxon(wStat, pValue).name(this.name()).type(type());
        }
    } catch (IOException | ScriptException e) {
        throw new DatasetException(e);
    }
}

From source file:mx.itesm.imb.handlers.RooHandler.java

@SuppressWarnings("unchecked")
public Object execute(final ExecutionEvent event) throws ExecutionException {
    File rooFile;// w  ww.j  av a 2s  . com
    File ecoreFile;
    IProject project;
    File installRooFile;
    Map<String, File> rooFiles;
    List<File> installRooFiles;
    List<EPackage> ecorePackages;
    MessageConsoleStream consoleStream;

    consoleStream = this.getConsoleStream();
    ecorePackages = (List<EPackage>) Util.getSelectedItems(event);

    // Generate the IMB artifacts for the selected Ecore packages
    this.clearConsole();
    for (EPackage ecorePackage : ecorePackages) {
        try {
            ecoreFile = Util.getEcoreFile(ecorePackage);

            // Roo and Bus scripts
            consoleStream.println("Generating roo scripts for package: " + ecorePackage.getName() + "...");
            rooFiles = Util.executeAtlQueries(this, ecoreFile, consoleStream);

            // Generate a new project for each roo script
            installRooFiles = new ArrayList<File>(rooFiles.size());
            for (String script : rooFiles.keySet()) {
                rooFile = rooFiles.get(script);
                project = Util.createProject(ecoreFile.getName().replace(".ecore", "." + script));
                installRooFile = new File(project.getLocation().toFile(), rooFile.getName());

                installRooFiles.add(installRooFile);
                FileUtils.copyFile(rooFile, installRooFile);
                rooFile.delete();
            }
        } catch (Exception e) {
            consoleStream
                    .println("The Ecore package could not be successfully transformed to a Spring Roo script");
            e.printStackTrace(new PrintStream(consoleStream));
        }
    }

    return null;
}

From source file:com.xqdev.jam.MLJAM.java

private static Interpreter getInterpreter(String contextId) throws EvalError {
    // Get the appropriate interpreter
    Interpreter i = null;// ww  w  .  ja  va2 s. com
    boolean createdInterp = false;
    synchronized (interpreters) { // serialize two gets of the same name
        i = interpreters.get(contextId);
        if (i == null) {
            i = new Interpreter();
            interpreters.put(contextId, i);
            createdInterp = true;
        }
    }
    if (createdInterp) {
        Log.log("Created context: " + contextId + " (" + i + ")");

        // Now configure stdin and stdout to capture 10k of content
        // Store references to the circular buffers within the interpreter itself.
        // This provides a nice place to store them plus theoretically allows
        // advanced use from within the bsh environment.
        // On Windows print() outputs \r\n but in XQuery that's normalized to \n
        // so the 10k of Java buffer may produce less than 10k of content in XQuery!
        OutputStream circularOutput = new CircularByteArrayOutputStream(10240);
        PrintStream printOutput = new PrintStream(circularOutput);
        i.setOut(printOutput);
        i.set("mljamout", circularOutput);

        OutputStream circularError = new CircularByteArrayOutputStream(10240);
        PrintStream printError = new PrintStream(circularError);
        i.setErr(printError);
        i.set("mljamerr", circularError);

        // Capture the built-in System.out and System.err also.
        // (Commented out since System appears global, can't do per interpreter.)
        //i.set("mljamprintout", printOutput);
        //i.set("mljamprinterr", printError);
        //i.eval("System.setOut(mljamprintout);");
        //i.eval("System.setErr(mljamprinterr);");

        // Need to expose hexdecode() and base64decode() built-in functions
        i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }");
        i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }");

        // Let's tell the context what its id is
        i.set("mljamid", contextId);
    }

    // Update the last accessed time, used for cleaning
    i.set("mljamlast", System.currentTimeMillis());

    // If it's been long enough, go snooping for stale contexts
    if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) {
        Log.log("Initiated periodic scan for stale context objects");
        lastClean = System.currentTimeMillis();
        Iterator<Interpreter> itr = interpreters.values().iterator();
        while (itr.hasNext()) {
            Interpreter interp = itr.next();
            Long last = (Long) interp.get("mljamlast");
            if (System.currentTimeMillis() > last + STALE_TIMEOUT) {
                itr.remove();
                Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")");
            } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT)
                    && ("" + interp.get("mljamid")).startsWith("temp:")) {
                itr.remove();
                Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")");
            }
        }
    }

    return i;
}

From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java

public CompareErrorType(File mismatch_out, File indel_out, File qualOutFile) throws IOException {
    misMatch_writer = new PrintStream(mismatch_out);
    indel_writer = new PrintStream(indel_out);

    if (qualOutFile != null) {
        qualOut = new PrintStream(qualOutFile);
    }//from w w  w .j  a  v  a 2s.  com

}

From source file:S3DataManagerTest.java

@Before
public void setUp() throws FileNotFoundException {
    //set the CodeBuilder instance to write its messages to the log here so
    //we can read what it prints.
    log = new ByteArrayOutputStream();
    PrintStream p = new PrintStream(log);
    when(listener.getLogger()).thenReturn(p);
}

From source file:br.com.ingenieux.mojo.beanstalk.env.DumpInstancesMojo.java

@Override
protected Object executeInternal() throws Exception {
    AmazonEC2 ec2 = clientFactory.getService(AmazonEC2Client.class);

    DescribeEnvironmentResourcesResult envResources = getService().describeEnvironmentResources(
            new DescribeEnvironmentResourcesRequest().withEnvironmentId(curEnv.getEnvironmentId())
                    .withEnvironmentName(curEnv.getEnvironmentName()));
    List<String> instanceIds = new ArrayList<String>();

    for (Instance i : envResources.getEnvironmentResources().getInstances()) {
        instanceIds.add(i.getId());//  w  w w. j a v a  2  s . c  om
    }

    DescribeInstancesResult ec2Instances = ec2
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));

    PrintStream printStream = null;

    if (null != outputFile) {
        printStream = new PrintStream(outputFile);
    }

    for (Reservation r : ec2Instances.getReservations()) {
        for (com.amazonaws.services.ec2.model.Instance i : r.getInstances()) {
            String ipAddress = dumpPrivateAddresses ? i.getPrivateIpAddress()
                    : StringUtils.defaultString(i.getPublicIpAddress(), i.getPrivateDnsName());
            String instanceId = i.getInstanceId();

            if (null != printStream) {
                printStream.println(ipAddress + " # " + instanceId);
            } else {
                getLog().info(" * " + instanceId + ": " + ipAddress);
            }
        }
    }

    if (null != printStream) {
        printStream.close();
    }

    return null;
}

From source file:com.dragome.compiler.parser.Parser.java

public static void main(String[] args) throws Exception {
    String className = args[0];//from   ww  w. j a va2  s  .c o m
    DragomeJsCompiler.compiler = new DragomeJsCompiler(CompilerType.Standard);

    Project.createSingleton(null);
    ClassUnit classUnit = new ClassUnit(Project.singleton, Project.singleton.getSignature(className));
    classUnit.setClassFile(new FileObject(new File(args[1])));
    Parser parser = new Parser(classUnit);
    TypeDeclaration typeDecl = parser.parse();
    DragomeJavaScriptGenerator dragomeJavaScriptGenerator = new DragomeJavaScriptGenerator(Project.singleton);
    dragomeJavaScriptGenerator
            .setOutputStream(new PrintStream(new FileOutputStream(new File("/tmp/webapp.js"))));
    dragomeJavaScriptGenerator.visit(typeDecl);

    FileInputStream fis = new FileInputStream(new File("/tmp/webapp.js"));
    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
    System.out.println(md5);
}

From source file:uk.org.openeyes.oink.itest.karaf.OinkCommandIT.java

@Test
public void testOinkEnableCommandIsAvailableOnShellOnAFreshCopyOfCustomDistro() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PrintStream psout = new PrintStream(out);
    PrintStream pser = new PrintStream(err);
    CommandSession cs = commandProcessor.createSession(System.in, psout, pser);
    cs.execute("help oink:enable");
    cs.close();/*w w w.  j  a va  2  s  .c  o m*/
    psout.close();
    pser.close();
    assertTrue(err.toString().isEmpty());
    assertFalse(out.toString().contains("COMMANDS"));
}

From source file:io.hightide.handlers.ErrorHandler.java

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.addDefaultResponseListener(new DefaultResponseListener() {
        @Override/*w  w w  . jav a2  s  . c  o  m*/
        public boolean handleDefaultResponse(final HttpServerExchange exchange) {
            if (!exchange.isResponseChannelAvailable()) {
                return false;
            }
            if (exchange.getResponseCode() >= 400) {
                Throwable t = exchange.getAttachment(HightideHandler.EXCEPTION_ATTACHMENT);
                String exceptionString;
                String message = exchange.getResponseCode() == 404 ? "Wrong address, no one lives here!"
                        : "Server's on fire, run for your life!";

                String errorPage;
                try {
                    Map<String, Object> errorMap = new HashMap<>();
                    errorMap.put("message", message);
                    errorMap.put("responseCode", exchange.getResponseCode());
                    errorMap.put("reason", StatusCodes.getReason(exchange.getResponseCode()));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    t.printStackTrace(new PrintStream(baos));
                    exceptionString = baos.toString();
                    errorMap.put("exception", exceptionString);
                    errorMap.put("exceptionMsg", t.getMessage());
                    errorPage = new RythmHtmlRenderer().render("errors/default.html.rythm", errorMap);
                } catch (Exception e) {
                    exceptionString = printException(t);
                    errorPage = "<html><head><title>Error</title></head><body>" + "<h1>" + message + "</h1>"
                            + exchange.getResponseCode() + " - "
                            + StatusCodes.getReason(exchange.getResponseCode()) + exceptionString
                            + "</body></html>";
                }
                exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length());
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
                Sender sender = exchange.getResponseSender();
                sender.send(errorPage);
                return true;
            }
            return false;
        }
    });
    next.handleRequest(exchange);
}

From source file:com.collabnet.ccf.core.hospital.Ambulance.java

public Object[] process(Object data) {
    log.warn("Artifact reached ambulance");
    if (data instanceof MessageException) {
        MessageException exception = (MessageException) data;
        Object dataObj = exception.getData();
        String source = exception.getOriginatingModule();
        Exception rootCause = exception.getException();
        Document doc = createXMLDocument("UTF-8");
        Element failure = doc.addElement("Failure");
        Element failureSource = failure.addElement("Source");
        if (source != null)
            failureSource.setText(source);
        Element exceptionDetail = failure.addElement("Exception");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream st = new PrintStream(bos);
        rootCause.printStackTrace(st);/* w w w  .ja va 2 s  . co  m*/
        exceptionDetail.setText(new String(bos.toByteArray()));
        Element dataElement = failure.addElement("Data");
        if (dataObj instanceof Document) {
            Document dataDoc = (Document) dataObj;
            String artifactFileName = null;
            try {
                artifactFileName = CCFUtils.getTempFileName(dataDoc);
            } catch (GenericArtifactParsingException e) {
                log.warn("The data that reached the hospital is not a Generic Artifact");
            }
            if (artifactFileName == null) {
                artifactFileName = "sync-info";
            }
            String tempFilePath = null;
            FileOutputStream fos = null;
            try {
                File tempFile = File.createTempFile(artifactFileName, ".xml", artifactsDirectoryFile);
                fos = new FileOutputStream(tempFile);
                String dataXML = dataDoc.asXML();
                fos.write(dataXML.getBytes());
                fos.flush();
                fos.close();
                tempFilePath = tempFile.getAbsolutePath();
            } catch (IOException e) {
                log.error("Could not create temporary File", e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        log.warn("Could not close temp file stream", e);
                    }
                }
            }
            dataElement.setText(tempFilePath);
        }
        String writeData = failure.asXML();
        try {
            fos.write(writeData.getBytes());
            fos.write(System.getProperty("line.separator").getBytes());
            fos.flush();
        } catch (IOException e) {
            log.error("An IO-Exception occured in the hospital: " + e.getMessage());
            return null;
        }
    }
    return new Object[0];
}