Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:com.isecpartners.gizmo.FourthIdea.java

private void executeCommand(final String text) {
    final InputStream procInput;
    new Thread(new Runnable() {

        public void run() {
            String newRequestText = "";
            try {
                temp_files_to_clean_up.add(buffer_file.getCanonicalPath());
                PrintWriter out = new PrintWriter(new FileOutputStream(buffer_file));
                byte[] requestBuf = null;
                if (jTextPane1.getSelectedText() != null && jTextPane1.getSelectedText().length() > 0) {
                    out.write(jTextPane1.getSelectedText());
                    requestBuf = jTextPane1.getSelectedText().getBytes();
                } else {
                    out.write(jTextPane1.getText());
                    requestBuf = jTextPane1.getText().getBytes();
                }/* w ww. j  a va2s.c o  m*/

                out.close();
                String env[] = getenv(1);
                env[0] = "BUF=" + buffer_file.getCanonicalPath();
                String cmd = "";
                if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")) {
                    cmd = "type " + buffer_file + "|" + text;
                } else {
                    cmd = "cat " + buffer_file + "|" + text;
                }

                newRequestText = exec(cmd, env, requestBuf);

            } catch (IOException ex) {
                Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);

            } finally {
                if (jTextPane1.getSelectedText() != null && jTextPane1.getSelectedText().length() > 0) {
                    jTextPane1.replaceSelection(newRequestText);
                } else {
                    FourthIdea.this.jTextPane1.setText(newRequestText);
                }
            }

        }

        private String readWholeFile(File file) {
            InputStream in = null;
            String ret = "";
            try {
                in = new FileInputStream(file);
                int file_size = Integer.MAX_VALUE;
                if (file.length() < Integer.MAX_VALUE) {
                    file_size = (int) file.length();
                }
                byte[] buf = new byte[file_size];
                // truncated because for some reason, a byte array is initialized with an int instead of a long
                // so this's a bit awful, but if you're editing a request bigger than 2G in size, then don't
                in.read(buf);
                ret = new String(buf);
            } catch (IOException ex) {
                Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return ret;
        }
    }).start();

}

From source file:edu.cornell.med.icb.goby.modes.WithinGroupVariabilityMode.java

private void processTranscriptAlignment(final String basename) throws IOException {
    final AlignmentReaderImpl reader = new AlignmentReaderImpl(basename);
    PrintWriter outputWriter = null;
    try {/* ww w.jav  a 2s .co m*/
        outputWriter = new PrintWriter(new FileWriter(outputFile));

        // outputWriter.write("# One line per reference id. Count indicates the number of times a query \n" +
        //         "# partially overlaps a target, given the various quality filters used to create the alignment.\n");
        outputWriter.write("sampleId\treferenceId\tcount\tlog10(count+1)\tcumulativeBasesAligned\n");

        reader.readHeader();

        final int numberOfReferences = reader.getNumberOfTargets();
        final int[] numberOfReadsPerReference = new int[numberOfReferences];
        final int[] cumulativeBasesPerReference = new int[numberOfReferences];

        System.out.printf("Scanning alignment %s%n", basename);
        for (final Alignments.AlignmentEntry alignmentEntry : reader) {
            ++numberOfReadsPerReference[alignmentEntry.getTargetIndex()];

            cumulativeBasesPerReference[alignmentEntry.getTargetIndex()] += Math
                    .min(alignmentEntry.getQueryAlignedLength(), alignmentEntry.getTargetAlignedLength());
        }
        final IndexedIdentifier targetIds = reader.getTargetIdentifiers();

        final DoubleIndexedIdentifier targetIdBackward = new DoubleIndexedIdentifier(targetIds);

        final String sampleId = FilenameUtils.getBaseName(basename);
        deCalculator.reserve(numberOfReferences, inputFiles.length);
        int numAlignedReadsInSample = 0;
        // define elements that will be tested for differential expression:
        for (int referenceIndex = 0; referenceIndex < numberOfReferences; ++referenceIndex) {

            final String transcriptId = targetIdBackward.getId(referenceIndex).toString();
            final int index = deCalculator.defineElement(transcriptId,
                    DifferentialExpressionCalculator.ElementType.TRANSCRIPT);

            deCalculator.defineElementLength(index, reader.getTargetLength(referenceIndex));
        }

        // observe elements:
        for (int referenceIndex = 0; referenceIndex < numberOfReferences; ++referenceIndex) {

            outputWriter.printf("%s\t%s\t%d\t%g\t%d%n", basename, targetIdBackward.getId(referenceIndex),
                    numberOfReadsPerReference[referenceIndex],
                    Math.log10(numberOfReadsPerReference[referenceIndex] + 1),
                    cumulativeBasesPerReference[referenceIndex]);

            final String transcriptId = targetIdBackward.getId(referenceIndex).toString();

            deCalculator.observe(sampleId, transcriptId, numberOfReadsPerReference[referenceIndex]);
            numAlignedReadsInSample += numberOfReadsPerReference[referenceIndex];
        }
        deCalculator.setNumAlignedInSample(sampleId, numAlignedReadsInSample);
        outputWriter.flush();

    } finally {
        IOUtils.closeQuietly(outputWriter);
        reader.close();
    }
}

From source file:de.xwic.appkit.core.remote.server.RemoteDataAccessServlet.java

/**
 * @param entityType/*from   w ww .  jav a 2  s  . c  o  m*/
 * @param req
 * @param resp
 * @param pwOut
 * @throws DocumentException
 * @throws TransportException
 * @throws ConfigurationException
 * @throws IOException
 */
private void handleUpdateEntity(final String entityType, final HttpServletRequest req,
        final HttpServletResponse resp, final PrintWriter pwOut)
        throws DocumentException, TransportException, ConfigurationException, IOException {

    String strEto = req.getParameter(PARAM_ETO);

    EntityTransferObject eto = EtoSerializer.deserialize(strEto, true);

    EntityTransferObject result = accessHandler.updateETO(eto);

    if (result == null) {
        throw new IllegalStateException("Result ETO is null");
    }

    String strResult = EtoSerializer.serialize(entityType, result, true);

    pwOut.write(strResult);
    pwOut.flush();
}

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to write content in temp file.
 * /*from ww w  .j a  va 2 s  . co  m*/
 * @param item {@link FileItem} uploaded file item.
 * @param filePath {@link String} to create temporary file.
 * @param printWriter {@link PrintWriter}.
 * @return {@link File} temporary file.
 */
private File copyItemContentInFile(final FileItem item, final String filePath, final PrintWriter printWriter) {
    File tempTableFile = null;
    OutputStream out = null;
    InputStream instream = null;
    try {
        instream = item.getInputStream();
        tempTableFile = new File(filePath);
        //         if (tempTableFile.exists()) {
        //            tempTableFile.delete();
        //         }
        out = new FileOutputStream(tempTableFile);
        final byte buf[] = new byte[1024];
        int len;
        while ((len = instream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } catch (final FileNotFoundException e) {
        printWriter.write("Unable to create the export folder.Please try again.");
    } catch (final IOException e) {
        printWriter.write("Unable to read the file.Please try again.");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ioe) {
                log.error("Could not close stream for file." + tempTableFile);
            }
        }
        if (instream != null) {
            try {
                instream.close();
            } catch (final IOException ioe) {
                log.error("Could not close stream for file." + filePath);
            }
        }
    }
    return tempTableFile;
}

From source file:com.ephesoft.dcma.gwt.customworkflow.server.ImportPluginUploadServlet.java

/**
 * @param tempZipFile//  w w w . ja va2  s.co  m
 * @param exportSerailizationFolderPath
 * @param printWriter 
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
private String processZipFileEntries(File tempZipFile, String exportSerailizationFolderPath,
        PrintWriter printWriter) throws FileNotFoundException, IOException {
    String errorMessageString;
    ZipInputStream zipInputStream;
    List<ZipEntry> zipEntries;
    tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName;
    File tempOutputUnZipDirFile = new File(tempOutputUnZipDir);
    try {
        FileUtils.copyFile(tempZipFile, tempOutputUnZipDirFile);

        // FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
    } catch (Exception e) {
        LOG.error("Unable to copy the file." + e, e);
        printWriter.write("Unable to copy the file.Please try again.");
        tempZipFile.delete();
    }

    zipInputStream = new ZipInputStream(new FileInputStream(tempOutputUnZipDir));
    // new ZipInputStream(new FileInputStream(tempOutputUnZipDir)).getNextEntry();

    zipEntries = new ArrayList<ZipEntry>();
    ZipEntry nextEntry = zipInputStream.getNextEntry();
    while (nextEntry != null) {
        zipEntries.add(nextEntry);
        nextEntry = zipInputStream.getNextEntry();
    }
    errorMessageString = processZipFileContents(zipEntries);
    return errorMessageString;
}

From source file:com.ijuru.kumva.sms.web.SearchServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w  w w .ja  v  a2 s .c  om*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String query = request.getParameter("q");

    if (query == null || query.length() == 0)
        return;

    query = query.trim();

    String keyword = Context.getOptions().getInputKeyword();

    // Strip keyword if one is specified
    if (StringUtils.isNotEmpty(keyword) && query.toLowerCase().startsWith(keyword + " ")) {
        query = query.substring((keyword + " ").length());
    }

    int timeout = Context.getOptions().getConnectionTimeout();
    String searchRef = Context.getOptions().getSearchRef();

    try {
        Search search = new RemoteSearch(Context.getDictionary(), timeout);
        SearchResult result = search.execute(query, 10, searchRef);
        String message = Messages.searchResult(result, query);

        out.write(message);
    } catch (Exception ex) {
        out.write(Messages.errorOccurred());

        log.warn("Remote search failed");
    }
}

From source file:com.browseengine.bobo.api.BoboIndexReader.java

/**
 * Utility method to dump out all fields (name and terms) for a given index.
 * /*  w  w w  .  ja  v  a  2 s  .co  m*/
 * @param outFile
 *          File to dump to.
 * @throws IOException
 */
public void dumpFields(File outFile) throws IOException {
    FileWriter writer = null;
    try {
        writer = new FileWriter(outFile);
        PrintWriter out = new PrintWriter(writer);
        Set<String> fieldNames = getFacetNames();
        for (String fieldName : fieldNames) {
            TermEnum te = terms(new Term(fieldName, ""));
            out.write(fieldName + ":\n");
            while (te.next()) {
                Term term = te.term();
                if (!fieldName.equals(term.field())) {
                    break;
                }
                out.write(term.text() + "\n");
            }
            out.write("\n\n");
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java

/**
 * Writes infos about one particular archived groupvertex in a job, including all groupmembers, their times and status
 * /*from   w  ww.  j  av a 2 s  . c om*/
 * @param wrt
 * @param jobEvent
 * @param groupvertexId
 */
private void writeJsonForArchivedJobGroupvertex(PrintWriter wrt, RecentJobEvent jobEvent,
        ManagementGroupVertexID groupvertexId) {

    try {

        ManagementGraph jobManagementGraph = jobmanager.getManagementGraph(jobEvent.getJobID());

        ManagementGroupVertex groupvertex = jobManagementGraph.getGroupVertexByID(groupvertexId);

        // Serialize ManagementGraph to json
        wrt.write("{\"groupvertex\": " + groupvertex.toJson() + ",");

        wrt.write("\"verticetimes\": {");
        boolean first = true;
        for (ManagementGroupVertex groupVertex : jobManagementGraph.getGroupVerticesInTopologicalOrder()) {

            for (int j = 0; j < groupVertex.getNumberOfGroupMembers(); j++) {
                ManagementVertex vertex = groupVertex.getGroupMember(j);

                if (first) {
                    first = false;
                } else {
                    wrt.write(",");
                }

                wrt.write("\"" + vertex.getID() + "\": {");
                wrt.write("\"vertexid\": \"" + vertex.getID() + "\",");
                wrt.write("\"vertexname\": \"" + vertex + "\",");
                wrt.write("\"CREATED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.CREATED) + ",");
                wrt.write("\"SCHEDULED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.SCHEDULED) + ",");
                wrt.write("\"ASSIGNED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.ASSIGNED) + ",");
                wrt.write("\"READY\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.READY) + ",");
                wrt.write("\"STARTING\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.STARTING) + ",");
                wrt.write("\"RUNNING\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.RUNNING) + ",");
                wrt.write("\"FINISHING\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.FINISHING) + ",");
                wrt.write("\"FINISHED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.FINISHED) + ",");
                wrt.write("\"CANCELING\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.CANCELING) + ",");
                wrt.write("\"CANCELED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.CANCELED) + ",");
                wrt.write("\"FAILED\": " + jobmanager.getArchive().getVertexTime(jobEvent.getJobID(),
                        vertex.getID(), ExecutionState.FAILED) + "");
                wrt.write("}");
            }

        }
        wrt.write("}}");

    } catch (EofException eof) { // Connection closed by client
        LOG.info("Info server for jobmanager: Connection closed by client, EofException");
    } catch (IOException ioe) { // Connection closed by client   
        LOG.info("Info server for jobmanager: Connection closed by client, IOException");
    }

}

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private String writeFile(String fileName, String data) {
    try {//from   w  ww .j  a  v  a2 s.  c om
        PrintWriter writer = new PrintWriter(fileName, "UTF-8");
        writer.write(data);
        writer.close();
        String newFileName = getOutputDir().getAbsolutePath() + java.io.File.separator + fileName
                + getExtension();
        if (rename(fileName, newFileName)) {
            log("Success writing: " + newFileName);
        } else {
            log("failed to write:" + newFileName);
        }
        ;
        return newFileName;
    } catch (IOException e) {
        e.printStackTrace();
        // do something
    }
    return null;

}