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:TextFileHandler.java

public void saveGZipFile(File outFile, String content) throws Exception {
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFile));
    PrintWriter pw = new PrintWriter(out);
    pw.write(content);
    pw.flush();/*from w  w  w . j a  v a2s. c  o  m*/
    pw.close();
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

public void testReport(String reportFile) throws UploadReportException {
    ReportType report = getReportFromFile(reportFile);
    testObj.uploadReport(report);/*from   ww w. j  av  a  2 s .c om*/
    String uuid = report.getIdentification().getReportUUID();
    String expectedPath = testObj.outputDir + "/" + uuid + ".xml";
    String content1 = null;
    String content2 = null;
    try {
        Assert.assertTrue(new File(expectedPath).exists());

        content1 = FileUtils.readFileToString(new File(reportFile), Charset.forName("utf-8"));
        content2 = FileUtils.readFileToString(new File(expectedPath), Charset.forName("utf-8"));
    } catch (IOException e) {
        Assert.fail(e.toString());
    }

    if (content1.startsWith(UTF8_BOM)) {
        content1 = content1.substring(1);
    }

    try {
        Diff diff = new Diff(content1, content2);
        log.debug("Diff: " + diff.toString());
        java.io.PrintWriter writer = new java.io.PrintWriter("/tmp/" + uuid + ".xml", "UTF-8");
        writer.write(content2);
        writer.close();
        Assert.assertTrue("Output differs", diff.similar());
    } catch (IOException | SAXException e) {
        Assert.fail(e.toString());
    }
}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request/*from  w  w w.  j  a v  a 2  s . c om*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = getFile(request, request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            try (ServletOutputStream op = response.getOutputStream()) {
                response.setContentType(getMimeType(file));
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

                byte[] bbuf = new byte[1024];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, bytes);
                }

                in.close();
                op.flush();
            }
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = getFile(request, request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = getFile(request, request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    int newWidth = 75;
                    if (request.getParameter("w") != null) {
                        try {
                            newWidth = Integer.parseInt(request.getParameter("w"));
                        } catch (Exception e) {
                            //Se mantiene el valor por defecto de 75
                        }
                    }

                    BufferedImage thumb = Scalr.resize(im, newWidth);
                    if (request.getParameter("h") != null) {
                        try {
                            thumb = Scalr.crop(thumb, newWidth, Integer.parseInt(request.getParameter("h")));
                        } catch (IllegalArgumentException | ImagingOpException e) {
                            //Se mantienen las proporciones.
                        }
                    }

                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    try (ServletOutputStream srvos = response.getOutputStream()) {
                        response.setContentLength(os.size());
                        response.setHeader("Content-Disposition",
                                "inline; filename=\"" + file.getName() + "\"");
                        os.writeTo(srvos);
                        srvos.flush();
                    }
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:com.funambol.json.coredb.CoreDBServlet.java

private void sendHtmlPage(HttpServletResponse response, String result) throws IOException {
    PrintWriter writer = response.getWriter();
    writer.write(result);
    writer.flush();//from   w w w  .  j  a va 2s .  com
}

From source file:io.neba.core.selftests.SelftestConsolePlugin.java

@Override
protected void renderContent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    writeScriptIncludes(request, response);
    writeHeadNavigation(response);/*from   w ww.j  a v a  2 s . com*/

    writer.write("<table id=\"plugin_table\" class=\"nicetable tablesorter noauto\">");
    writer.write("<thead><tr><th>Name</th><th>Source bundle</th><th>Action</th><th>Status</th></tr></thead>");
    writer.write("<tbody>");
    int count = 0;
    for (SelftestReference reference : getSelftestReferences()) {
        writer.write("<tr id=\"row" + count + "\">");
        writer.write("<td>" + reference.getDescription() + "</td>");
        writer.write("<td><a href=\"bundles/" + reference.getBundleId() + "\">" + reference.getBundleId()
                + "</a></td>");
        writer.write("<td><a href=\"#\" class=\"runlink\" onclick=\"run('" + reference.getId() + "', this, "
                + count + ");return false;\">run</a></td>");
        writer.write("<td><div id=\"signal" + count + "\" class=\"signal result" + count
                + "\" style=\"width:14px;height:14px;background-color:gray;margin:2px 0 0 0;\"></div></td>");
        writer.write("</tr>");
        ++count;
    }
    writer.write("</tbody>");
    writer.write("</table>");

}

From source file:edu.vt.vbi.patric.portlets.SingleFIGfam.java

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {
    String callType = request.getParameter("callType");

    if (callType != null) {
        Map<String, String> key = new HashMap<>();
        if (callType.equals("saveState")) {
            String genomeIds = request.getParameter("genomeIds");
            String familyIds = request.getParameter("familyIds");
            String familyType = request.getParameter("familyType");

            key.put("genomeIds", genomeIds);
            key.put("familyIds", familyIds);
            key.put("familyType", familyType);

            Random g = new Random();
            long pk = g.nextLong();

            SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key));

            PrintWriter writer = response.getWriter();
            writer.write("" + pk);
            writer.close();/*from  w  w w  .j  a v  a2s .co  m*/

        } else if (callType.equals("getData")) {

            Map data = processFeatureTab(request);
            int numFound = (Integer) data.get("numFound");
            List<GenomeFeature> features = (List<GenomeFeature>) data.get("features");

            JSONArray docs = new JSONArray();
            for (GenomeFeature feature : features) {
                docs.add(feature.toJSONObject());
            }

            JSONObject jsonResult = new JSONObject();
            jsonResult.put("results", docs);
            jsonResult.put("total", numFound);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            jsonResult.writeJSONString(writer);
            writer.close();
        } else if (callType.equals("download")) {

            List<String> tableHeader = new ArrayList<>();
            List<String> tableField = new ArrayList<>();
            JSONArray tableSource = new JSONArray();

            String fileName = "FeatureTable";
            String fileFormat = request.getParameter("fileformat");

            // features
            Map data = processFeatureTab(request);
            List<GenomeFeature> features = (List<GenomeFeature>) data.get("features");

            for (GenomeFeature feature : features) {
                tableSource.add(feature.toJSONObject());
            }

            tableHeader.addAll(DownloadHelper.getHeaderForFeatures());
            tableField.addAll(DownloadHelper.getFieldsForFeatures());

            ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource);
            excel.buildSpreadsheet();

            if (fileFormat.equalsIgnoreCase("xlsx")) {
                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                excel.writeSpreadsheettoBrowser(response.getPortletOutputStream());
            } else if (fileFormat.equalsIgnoreCase("txt")) {

                response.setContentType("application/octetstream");
                response.addProperty("Content-Disposition",
                        "attachment; filename=\"" + fileName + "." + fileFormat + "\"");

                response.getPortletOutputStream().write(excel.writeToTextFile().getBytes());
            }
        }
    }
}

From source file:com.suntek.gztpb.controller.DriverLicenseController.java

@RequestMapping(value = "saveApply.htm", method = RequestMethod.POST)
public String saveApply(DriverLicenseModel apply, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    try {//w w w.  j ava  2s  . c o  m
        String applyNum = IdGenerator.getInstance().getBizCode("ITMS_SEQ", 5);
        apply.setApplyNum(applyNum);
        driverLicenseService.saveApply(apply);
        out.write("<script>parent.saveCallback(1,'" + applyNum + "')</script>");
    } catch (Exception e) {
        logger.error(e.getMessage());
        out.write("<script>parent.saveCallback(0)</script>");
    }

    return null;
}

From source file:TextFileHandler.java

/**
 * Save content to a .gz file/*from   w  ww .  ja  v a2s  . c  o  m*/
 * @param fileName e.g. foo.txt.gz
 * @param content
 */
public void saveGZipFile(String fileName, String content) {
    try {
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(fileName));
        PrintWriter pw = new PrintWriter(out);
        pw.write(content);
        pw.flush();
        pw.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:edu.vt.vbi.patric.portlets.FeaturePropertiesPortlet.java

protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {

    SiteHelper.setHtmlMetaElements(request, response, "Feature Overview");

    response.setContentType("text/html");
    String cType = request.getParameter("context_type");
    String cId = request.getParameter("context_id");

    if (cType != null && cId != null && cType.equals("feature")) {

        DataApiHandler dataApi = new DataApiHandler(request);
        GenomeFeature feature = dataApi.getPATRICFeature(cId);

        if (feature != null) {
            List<GenomeFeature> listReleateFeatures;
            List<String> listUniprotkbAccessions = null;
            List<Map<String, String>> listUniprotIds = null;
            String refseqLink = null;
            String refseqLocusTag = null;
            Map<String, String> virulenceFactor = null;

            SolrQuery query = new SolrQuery("pos_group:" + feature.getPosGroupInQuote());
            query.setSort("annotation_sort", SolrQuery.ORDER.asc);

            String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            listReleateFeatures = dataApi.bindDocuments((List<Map>) respBody.get("docs"), GenomeFeature.class);

            // build listUniprotkbAccessions based on GI number
            if (feature.getGi() > 0) {
                query = new SolrQuery("id_value:(" + feature.getGi() + ")");
                query.addFilterQuery("id_type:GI").setRows(dataApi.MAX_ROWS);

                apiResponse = dataApi.solrQuery(SolrCore.ID_REF, query);

                resp = jsonReader.readValue(apiResponse);
                respBody = (Map) resp.get("response");

                List<Map> uniprotList = (List<Map>) respBody.get("docs");

                if (uniprotList.size() > 0) {
                    listUniprotkbAccessions = new ArrayList<>();
                }/* www. ja v a2  s  .com*/

                for (Map doc : uniprotList) {
                    listUniprotkbAccessions.add(doc.get("uniprotkb_accession").toString());
                }
            }

            if (listUniprotkbAccessions != null) {
                query = new SolrQuery(
                        "uniprotkb_accession:(" + StringUtils.join(listUniprotkbAccessions, " OR ") + ")");
                query.setFields("uniprotkb_accession,id_type,id_value");
                query.setRows(1000);

                apiResponse = dataApi.solrQuery(SolrCore.ID_REF, query);

                resp = jsonReader.readValue(apiResponse);
                respBody = (Map) resp.get("response");

                List<Map> sdl = (List<Map>) respBody.get("docs");

                if (!sdl.isEmpty()) {
                    listUniprotIds = new ArrayList<>();
                }

                for (Map doc : sdl) {
                    Map<String, String> uniprot = new HashMap<>();

                    uniprot.put("Accession", doc.get("uniprotkb_accession").toString());
                    uniprot.put("idType", doc.get("id_type").toString());
                    uniprot.put("idValue", doc.get("id_value").toString());

                    listUniprotIds.add(uniprot);
                }
            }

            if (feature.getAnnotation().equals("PATRIC")) {

                if (feature.hasGeneId()) {
                    refseqLink = SiteHelper.getExternalLinks("ncbi_gene").replace("&", "&amp;")
                            + feature.getGeneId();
                }
                refseqLocusTag = feature.getRefseqLocusTag();
            } else if (feature.getAnnotation().equals("RefSeq")) {
                refseqLocusTag = feature.getAltLocusTag();
            }

            query = new SolrQuery("(locus_tag:" + feature.getAltLocusTag()
                    + (feature.hasRefseqLocusTag() ? " OR locus_tag: " + feature.getRefseqLocusTag() : "")
                    + ")");
            query.setFilterQueries("source:PATRIC_VF");
            query.setFields("source,source_id");

            apiResponse = dataApi.solrQuery(SolrCore.SPECIALTY_GENE, query);

            resp = jsonReader.readValue(apiResponse);
            respBody = (Map) resp.get("response");

            List<Map> sdl = (List<Map>) respBody.get("docs");

            for (Map doc : sdl) {
                virulenceFactor = new HashMap<>();

                virulenceFactor.put("source", doc.get("source").toString());
                virulenceFactor.put("sourceId", doc.get("source_id").toString());
            }

            request.setAttribute("feature", feature);
            request.setAttribute("listReleateFeatures", listReleateFeatures);
            request.setAttribute("listUniprotkbAccessions", listUniprotkbAccessions);
            request.setAttribute("listUniprotIds", listUniprotIds);
            request.setAttribute("refseqLink", refseqLink);
            request.setAttribute("refseqLocusTag", refseqLocusTag);
            request.setAttribute("virulenceFactor", virulenceFactor);

            PortletRequestDispatcher prd = getPortletContext()
                    .getRequestDispatcher("/WEB-INF/jsp/overview/feature_properties.jsp");
            prd.include(request, response);
        } else {
            PrintWriter writer = response.getWriter();
            writer.write(" ");
            writer.close();
        }
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("<p>Invalid Parameter - missing context information</p>");
        writer.close();
    }
}

From source file:de.undercouch.gradle.tasks.download.DownloadTaskPluginTest.java

/**
 * Runs an embedded HTTP server and creates test files to serve
 * @throws Exception if the server could not be started
 *//* w w  w .j a v  a 2 s . c om*/
@Before
public void setUp() throws Exception {
    //run server on any free port
    server = new Server(0);

    //serve resources from temporary folder
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource(folder.getRoot().getAbsolutePath()));

    //echo X-* headers back in response body
    ContextHandler echoHeadersHandler = new ContextHandler("/echo-headers") {
        @Override
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.write("headers:\n");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                if (name.startsWith("X-")) {
                    rw.write(String.format("  %s: %s\n", name, request.getHeader(name)));
                }
            }
            rw.close();
        }
    };

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resourceHandler, echoHeadersHandler, new DefaultHandler() });
    server.setHandler(handlers);

    server.start();

    //create temporary files
    contents = new byte[4096];
    contents2 = new byte[4096];
    for (int i = 0; i < contents.length; ++i) {
        contents[i] = (byte) (Math.random() * 255);
        contents2[i] = (byte) (Math.random() * 255);
    }

    File testFile = folder.newFile(TEST_FILE_NAME);
    FileUtils.writeByteArrayToFile(testFile, contents);
    File testFile2 = folder.newFile(TEST_FILE_NAME2);
    FileUtils.writeByteArrayToFile(testFile2, contents2);
}