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.cloud.agent.api.storage.OVFHelper.java

public void rewriteOVFFile(final String origOvfFilePath, final String newOvfFilePath, final String diskName) {
    try {/*w  ww  .  j a v a 2s  .  c o m*/
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File(origOvfFilePath));
        NodeList disks = doc.getElementsByTagName("Disk");
        NodeList files = doc.getElementsByTagName("File");
        NodeList items = doc.getElementsByTagName("Item");
        String keepfile = null;
        List<Element> toremove = new ArrayList<Element>();
        for (int j = 0; j < files.getLength(); j++) {
            Element file = (Element) files.item(j);
            String href = file.getAttribute("ovf:href");
            if (diskName.equals(href)) {
                keepfile = file.getAttribute("ovf:id");
            } else {
                toremove.add(file);
            }
        }
        String keepdisk = null;
        for (int i = 0; i < disks.getLength(); i++) {
            Element disk = (Element) disks.item(i);
            String fileRef = disk.getAttribute("ovf:fileRef");
            if (keepfile == null) {
                s_logger.info("FATAL: OVA format error");
            } else if (keepfile.equals(fileRef)) {
                keepdisk = disk.getAttribute("ovf:diskId");
            } else {
                toremove.add(disk);
            }
        }
        for (int k = 0; k < items.getLength(); k++) {
            Element item = (Element) items.item(k);
            NodeList cn = item.getChildNodes();
            for (int l = 0; l < cn.getLength(); l++) {
                if (cn.item(l) instanceof Element) {
                    Element el = (Element) cn.item(l);
                    if ("rasd:HostResource".equals(el.getNodeName())
                            && !(el.getTextContent().contains("ovf:/file/" + keepdisk)
                                    || el.getTextContent().contains("ovf:/disk/" + keepdisk))) {
                        toremove.add(item);
                        break;
                    }
                }
            }
        }

        for (Element rme : toremove) {
            if (rme.getParentNode() != null) {
                rme.getParentNode().removeChild(rme);
            }
        }

        final StringWriter writer = new StringWriter();
        final StreamResult result = new StreamResult(writer);
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        final DOMSource domSource = new DOMSource(doc);
        transformer.transform(domSource, result);
        PrintWriter outfile = new PrintWriter(newOvfFilePath);
        outfile.write(writer.toString());
        outfile.close();
    } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
        s_logger.info("Unexpected exception caught while removing network elements from OVF:" + e.getMessage(),
                e);
        throw new CloudRuntimeException(e);
    }
}

From source file:io.github.egonw.base.CMLEnricher.java

/**
 * Writes current document to a CML file.
 * //from   w w w.  j a va2s  .  c  om
 * @param fileName
 * @param extension
 *
 * @throws IOException
 *             Problems with opening output file.
 * @throws CDKException
 *             Problems with writing the CML XOM.
 */
private void writeFile(String fileName, String extension) throws IOException, CDKException {
    String basename = FilenameUtils.getBaseName(fileName);
    OutputStream outFile = new BufferedOutputStream(new FileOutputStream(basename + "-" + extension + ".cml"));
    PrintWriter output = new PrintWriter(outFile);
    this.doc.getRootElement().addNamespaceDeclaration(SreNamespace.getInstance().prefix,
            SreNamespace.getInstance().uri);
    output.write(XOMUtil.toPrettyXML(this.doc));
    output.flush();
    output.close();
}

From source file:net.sf.jasperreports.web.servlets.ReportServlet.java

protected void pageUpdate(HttpServletRequest request, HttpServletResponse response,
        WebReportContext webReportContext) throws JRException, IOException {
    JasperPrintAccessor jasperPrintAccessor = (JasperPrintAccessor) webReportContext
            .getParameterValue(WebReportContext.REPORT_CONTEXT_PARAMETER_JASPER_PRINT_ACCESSOR);
    if (jasperPrintAccessor == null) {
        throw new JRRuntimeException("Did not find the report on the session.");
    }// w ww .  j a v  a  2 s . c om

    String pageIdxParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE);
    Integer pageIndex = pageIdxParam == null ? null : Integer.valueOf(pageIdxParam);
    String pageTimestampParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE_TIMESTAMP);
    Long pageTimestamp = pageTimestampParam == null ? null : Long.valueOf(pageTimestampParam);

    if (log.isDebugEnabled()) {
        log.debug("report page update check for pageIndex: " + pageIndex + ", pageTimestamp: " + pageTimestamp);
    }

    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();
    putReportStatusResult(response, jasperPrintAccessor, result);

    if (pageIndex != null && pageTimestamp != null) {
        ReportPageStatus pageStatus = jasperPrintAccessor.pageStatus(pageIndex, pageTimestamp);
        boolean modified = pageStatus.hasModified();
        result.put("pageModified", modified);

        if (log.isDebugEnabled()) {
            log.debug("page " + pageIndex + " modified " + modified);
        }
    }

    String resultString = JacksonUtil.getInstance(getJasperReportsContext()).getJsonString(result);
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.write(resultString);
    out.flush();
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Sends request to the opened HTTP connection.
 * //from  w  w w  .j  a v a 2s . c om
 * @param input
 *          data as stream
 * @param output
 *          output as stream
 * 
 * @throws java.io.IOException
 *           if sending data failed
 */
private void send(InputStream input, OutputStream output) throws IOException {

    PrintWriter outputWriter = null;
    try {
        outputWriter = new PrintWriter(output);
        outputWriter.write(readInputCharacters(input));
        outputWriter.flush();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputWriter != null) {
            outputWriter.close();
        }
    }
}

From source file:co.cask.cdap.security.tools.AccessTokenClient.java

public String execute0(String[] args) {
    buildOptions();/*from   ww w .ja va  2  s .  c o m*/
    parseArguments(args);
    if (help) {
        return "";
    }

    String baseUrl;
    try {
        baseUrl = getAuthenticationServerAddress();
    } catch (IOException e) {
        errorDebugExit("Could not find Authentication service to connect to.", e);
        return null;
    }

    System.out.println(String.format("Authentication server address is: %s", baseUrl));
    System.out.println(String.format("Authenticating as: %s", username));

    HttpClient client = new DefaultHttpClient();
    if (useSsl && disableCertCheck) {
        try {
            client = getHTTPClient();
        } catch (Exception e) {
            errorDebugExit("Could not create HTTP Client with SSL enabled", e);
            return null;
        }
    }

    // construct the full URL and verify its well-formedness
    try {
        URI.create(baseUrl);
    } catch (IllegalArgumentException e) {
        System.err.println(
                "Invalid base URL '" + baseUrl + "'. Check the validity of --host or --port arguments.");
        return null;
    }

    HttpGet get = new HttpGet(baseUrl);
    String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes());
    auth = auth.replaceAll("(\r|\n)", "");
    get.addHeader("Authorization", String.format("Basic %s", auth));
    HttpResponse response;
    try {
        response = client.execute(get);
    } catch (IOException e) {
        errorDebugExit("Error sending HTTP request: " + e.getMessage(), e);
        return null;
    }
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        System.out.println(
                "Authentication failed. Please ensure that the username and password provided are correct.");
        return null;
    } else {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ByteStreams.copy(response.getEntity().getContent(), bos);
            String responseBody = bos.toString("UTF-8");
            bos.close();
            JsonParser parser = new JsonParser();
            JsonObject responseJson = (JsonObject) parser.parse(responseBody);
            String token = responseJson.get(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN)
                    .getAsString();

            PrintWriter writer = new PrintWriter(filePath, "UTF-8");
            writer.write(token);
            writer.close();
            System.out.println("Your Access Token is:" + token);
            System.out.println("Access Token saved to file " + filePath);
        } catch (Exception e) {
            System.err.println("Could not parse response contents.");
            e.printStackTrace(System.err);
            return null;
        }
    }
    client.getConnectionManager().shutdown();
    return "OK.";
}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobControlInProgressHandler.java

/**
 * Invokes this EntryPageHandler object/*w ww.  j a va  2  s.  c  o m*/
 * <p>
 * 
 * @param p_ageDescriptor
 *            the description of the page to be produced.
 * @param p_request
 *            original request sent from the browser.
 * @param p_response
 *            original response object.
 * @param p_context
 *            the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    boolean stateMarch = false;
    if (Job.DISPATCHED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    String action = p_request.getParameter(ACTION_STRING);
    if (StringUtil.isNotEmpty(action) && "removeJobFromGroup".equals(action)) {
        removeJobFromGroup(p_request);
    }
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, BASE_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));

    // since an instance of a page handler is used by different clients,
    // this instance variable needs to be set only once. There's no need
    // to synchronize this section as the value of export url is always the
    // same.
    if (m_exportUrl == null) {
        m_exportUrl = ((NavigationBean) beanMap.get(EXPORT_BEAN)).getPageURL();
    }

    if (p_request.getParameter("checkIsUploadingForExport") != null) {
        long jobId = Long.parseLong(p_request.getParameter("jobId"));
        Job job = WorkflowHandlerHelper.getJobById(jobId);
        String result = "";
        for (Workflow workflow : job.getWorkflows()) {
            if (result.length() > 0)
                break;
            Hashtable<Long, Task> tasks = workflow.getTasks();
            for (Long taskKey : tasks.keySet()) {
                if (tasks.get(taskKey).getIsUploading() == 'Y') {
                    result = "uploading";
                    break;
                }
            }
        }
        PrintWriter out = p_response.getWriter();
        p_response.setContentType("text/html");
        out.write(result);
        out.close();
        return;
    } else if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.DISPATCHED);
    JobVoInProgressSearcher searcher = new JobVoInProgressSearcher();
    searcher.setJobVos(p_request, true);
    p_request.setAttribute(EXPORT_URL_PARAM, m_exportUrl);
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.DISPATCHED));
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);
    sessionMgr.setAttribute("destinationPage", "inprogress");
    // clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache. do both. "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); // HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); // HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to
                                                        // cache
                                                        // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Sends request to the opened HTTP connection.
 * /*from  w  w  w  . j av a  2s . c  o m*/
 * @param requestBody
 *          as string
 * @param output
 *          to stream the data
 * 
 * @throws java.io.IOException
 *           if sending data failed
 */
private void send(String requestBody, OutputStream output) throws IOException {

    PrintWriter outputWriter = null;
    try {
        outputWriter = new PrintWriter(output);
        outputWriter.write(requestBody);
        outputWriter.flush();

    } catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        try {
            if (output != null) {
                output.close();
            }
        } catch (Exception ef) {
            ef.printStackTrace();
        }
    }
}

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

/**
 * Run the map2text mode./*w w w  .  j  a  v a2s  . c  om*/
 *
 * @throws java.io.IOException error reading / writing
 */
@Override
public void execute() throws IOException {
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(
                new GZIPOutputStream(new FastBufferedOutputStream(new FileOutputStream(outputFile + ".gz"))));
        writer.write("track type=wiggle_0 name=" + label + " visibility=full viewLimits=1:200\n");
        final AlignmentReaderImpl alignment = new AlignmentReaderImpl(inputBasename);
        alignment.readHeader();
        alignment.close();
        final IndexedIdentifier referenceIds = alignment.getTargetIdentifiers();
        final DoubleIndexedIdentifier backwards = new DoubleIndexedIdentifier(referenceIds);
        final CountsArchiveReader reader = new CountsArchiveReader(inputBasename,
                alternativeCountArchiveExtension);
        final WiggleWindow wiggleWindow = new WiggleWindow(writer, resolution, 0);

        for (int referenceIndex = 0; referenceIndex < reader.getNumberOfIndices(); referenceIndex++) {
            String referenceId = backwards.getId(referenceIndex).toString();
            boolean processThisSequence = true;
            // prepare reference ID for UCSC genome browser.
            if ("MT".equalsIgnoreCase(referenceId)) {
                // patch chromosome name for UCSC genome browser:
                referenceId = "M";
            }

            // ignore c22_H2, c5_H2, and other contigs but not things like chr1 (mm9)
            if (referenceId.startsWith("c") && !referenceId.startsWith("chr")) {
                processThisSequence = false;
            }

            // ignore NT_*
            if (referenceId.startsWith("NT_")) {
                processThisSequence = false;
            }

            if (filterByReferenceNames && !includeReferenceNames.contains(referenceId)) {
                processThisSequence = false;
            }

            if (processThisSequence) {
                // prepend the reference id with "chr" if it doesn't use that already
                final String chromosome;
                if (referenceId.startsWith("chr")) {
                    chromosome = referenceId;
                } else {
                    chromosome = "chr" + referenceId;
                }

                long sumCount = 0;
                int numCounts = 0;

                CountsReader counts = reader.getCountReader(referenceIndex);
                int lastLength = 0;
                int lastPosition = 0;
                while (counts.hasNextTransition()) {
                    counts.nextTransition();
                    lastPosition = counts.getPosition();
                    lastLength = counts.getLength();
                }
                final int maxWritePosition = (lastPosition + lastLength - 1);
                wiggleWindow.reset();
                wiggleWindow.setMaxDataSize(maxWritePosition);

                writer.printf("variableStep chrom=%s span=%d\n", chromosome, resolution);
                counts = reader.getCountReader(referenceIndex);

                while (counts.hasNextTransition()) {
                    counts.nextTransition();
                    final int length = counts.getLength();

                    final int count = counts.getCount();
                    final int position = counts.getPosition();

                    wiggleWindow.addData(position, length, count);

                    sumCount += count;
                    numCounts++;
                }
                wiggleWindow.finish();
                final double averageCount = sumCount / (double) numCounts;
                System.out.println("average count for sequence " + referenceId + " " + averageCount);
            }
        }
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.imagelake.android.settings.Servlet_UserSetting.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {/*from   w  w w. ja  va  2 s  . c  om*/

        String type = request.getParameter("type");

        if (type.equals("all")) {
            //ja = new JSONArray();
            String chart = udi.getSubadminList();
            System.out.println(chart);
            out.write(chart);
        } else if (type.equals("user_type_all")) {
            String list = udi.getJSONAllUserTypeList();
            out.write("json=" + list);
        } else if (type.equals("update")) {
            String adtype = request.getParameter("admintype");
            String state = request.getParameter("state");
            String id = request.getParameter("id");

            System.out.println("admin type:" + adtype);
            System.out.println("state:" + state);
            System.out.println("id:" + id);

            boolean A = udi.updateUserState(Integer.parseInt(id), Integer.parseInt(state));
            boolean B = udi.updateUserType(Integer.parseInt(id), Integer.parseInt(adtype));
            System.out.println(A + "|" + B);
            if (A && B) {
                out.write("msg=Us_Successful...");
            } else {
                out.write("msg=Unable to complete the action.");
            }

        } else if (type.equals("addnewsub")) {
            InterfaceDAOImp idi = new InterfaceDAOImp();
            Interfaces in = new Interfaces();
            in.setState(1);
            in.setUrl("RegAdmin.jsp");
            boolean o = idi.updateInteface(in);
            if (o) {
                out.write("msg=addnewsub_Successful...");
            } else {
                out.write("msg=Unable to complete the action.");
            }
        } else if (type.equals("closenewsub")) {
            InterfaceDAOImp idi = new InterfaceDAOImp();
            Interfaces in = new Interfaces();
            in.setState(2);
            in.setUrl("RegAdmin.jsp");
            boolean o = idi.updateInteface(in);
            if (o) {
                out.write("msg=closenewsub_Successful...");
            } else {
                out.write("msg=Unable to complete the action.");
            }
        } else if (type.equals("editsub")) {
            InterfaceDAOImp idi = new InterfaceDAOImp();
            Interfaces in = new Interfaces();
            in.setState(1);
            in.setUrl("UpdateAdmin.jsp");
            boolean o = idi.updateInteface(in);
            if (o) {
                out.write("msg=editsub_Successful...");
            } else {
                out.write("msg=Unable to complete the action.");
            }
        } else if (type.equals("closeeditsub")) {
            InterfaceDAOImp idi = new InterfaceDAOImp();
            Interfaces in = new Interfaces();
            in.setState(2);
            in.setUrl("UpdateAdmin.jsp");
            boolean o = idi.updateInteface(in);
            if (o) {
                out.write("msg=closeeditsub_Successful...");
            } else {
                out.write("msg=Unable to complete the action.");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:edu.cornell.med.icb.goby.methylation.MethylSimilarityScan.java

private void process(String[] args) throws IOException {
    String inputFilename = CLI.getOption(args, "-i", "/data/lister/mc_h1.tsv");
    this.windowWidths = CLI.getOption(args, "-w", "10");
    this.maxBestHits = CLI.getIntOption(args, "-h", 100);
    String outputFilename = CLI.getOption(args, "-o", "out.tsv");
    final MethylationData data = load(inputFilename);
    File outputFile = new File(outputFilename);
    boolean outputFileExists = outputFile.exists();
    // append://from w w w  . j  a  v  a2 s . co  m
    PrintWriter output = new PrintWriter(new FileWriter(outputFilename, true));

    if (!outputFileExists) {
        output.write(
                "windowSize\tlocation\tchromosome\tforward strand start\tforward strand end\treverse strand start\treverse strand end\teffective window size\tstatistic\n");
    }
    for (String windowWidthString : windowWidths.split("[,]")) {
        final int windowWidth = Integer.parseInt(windowWidthString);
        System.out.println("Processing window size=" + windowWidth);
        final HitBoundedPriorityQueue hits = new HitBoundedPriorityQueue(maxBestHits);
        DoInParallel scan = new DoInParallel() {
            @Override
            public void action(DoInParallel forDataAccess, String chromosome, int loopIndex) {
                compareStrands(hits, data, windowWidth, new MutableString(chromosome));
            }
        };

        try {
            scan.execute(true, data.getChromosomeStrings());
        } catch (Exception e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

        printResults(hits, windowWidth, data, output);
    }
    output.close();
}