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.siemens.sw360.portal.portlets.projects.ProjectImportPortlet.java

@Override
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws IOException, PortletException {
    LoginState loginState = new LoginState();
    String requestedAction = request.getParameter(PortalConstants.IMPORT_USER_ACTION);
    JSONObject responseData = handleRequestedAjaxAction(requestedAction, request, response, loginState);

    PrintWriter writer = response.getWriter();
    writer.write(responseData.toString());
}

From source file:org.jasig.portlet.test.mvc.tests.CacheControlTestController.java

/**
 * Writes some simple JSON output. Sets cache expiration time of 120 seconds.
 * @param request/*  w w  w.jav a2  s.com*/
 * @param response
 * @throws IOException
 */
@ResourceMapping(value = "jsonExpirationCachingTest")
public void writeJsonContentWithExpirationCaching(ResourceRequest request, ResourceResponse response)
        throws IOException {
    response.getCacheControl().setExpirationTime(120);
    response.setContentType("application/json");
    PrintWriter writer = new PrintWriter(response.getPortletOutputStream());
    Date now = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:mm:ss");
    writer.write("{ \"hello\": \"true\", \"timeRendered\": \"" + sdf.format(now) + "\" }");
    writer.close();
}

From source file:de.static_interface.sinkscripts.scriptengine.scriptcommand.SaveCommand.java

@Override
protected boolean onExecute(ScriptContext context, String[] args, String label, String nl) {

    if (cmdLine.getArgs().length < 1) {
        return false;
    }//from  ww w.  java 2  s . c  om

    String scriptName = cmdLine.getArgs()[0];
    File scriptFile;

    if (cmdLine.hasOption('a')) {
        scriptFile = new File(context.getScriptLanguage().AUTOSTART_DIRECTORY,
                scriptName + "." + context.getScriptLanguage().getFileExtension());
    } else {
        scriptFile = new File(context.getScriptLanguage().SCRIPTLANGUAGE_DIRECTORY,
                scriptName + "." + context.getScriptLanguage().getFileExtension());
    }

    if (scriptFile.exists()) {
        if (!scriptFile.delete()) {
            throw new RuntimeException("Couldn't override " + scriptFile + " (File.delete() returned false)!");
        }
        return true;
    }
    PrintWriter writer;
    try {
        writer = new PrintWriter(scriptFile, "UTF-8");
    } catch (Exception e) {
        Util.reportException(context.getUser(), e);
        return true;
    }
    writer.write(context.getCode());
    writer.close();
    context.getUser().sendMessage(ChatColor.DARK_GREEN + "Code saved!");
    return true;
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request//from  w  ww. ja  v a  2s .c  o m
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            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();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + 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 = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + 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) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    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");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:analysePortalU.AnalysePortalUData.java

public void analyse()
        throws HttpException, IOException, ParserConfigurationException, SAXException, TransformerException {

    Map<String, Map<String, String>> resultMap = new HashMap<String, Map<String, String>>();

    Scanner in = new Scanner(getClass().getClassLoader().getResourceAsStream("keywords.txt"));
    while (in.hasNextLine()) {
        String keyword = URLEncoder.encode(in.nextLine().trim(), "UTF-8");

        int currentPage = 1;
        boolean moreResults = true;

        while (moreResults) {

            String url = "http://www.portalu.de/opensearch/query?q=" + keyword.replace(' ', '+')
                    + "+datatype:metadata+ranking:score&h=" + PAGE_SIZE + "&detail=1&ingrid=1&p=" + currentPage;

            HttpClientParams httpClientParams = new HttpClientParams();
            HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
            httpClientParams.setSoTimeout(60 * 1000);
            httpConnectionManager.getParams().setConnectionTimeout(60 * 1000);
            httpConnectionManager.getParams().setSoTimeout(60 * 1000);

            HttpClient client = new HttpClient(httpClientParams, httpConnectionManager);
            HttpMethod method = new GetMethod(url);

            // set a request header
            // this can change in the result of the response since it might
            // be
            // interpreted differently
            // method.addRequestHeader("Accept-Language", language);
            // //"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");

            System.out.println("Query: " + url);
            int status = client.executeMethod(method);
            if (status == 200) {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(method.getResponseBodyAsStream());
                XPathUtils xpath = new XPathUtils(new ConfigurableNamespaceContext());
                NodeList results = xpath.getNodeList(doc, "/rss/channel/item");
                int numberOfResults = results.getLength();

                for (int i = 0; i < results.getLength(); i++) {
                    Node node = results.item(i);
                    String fileIdentifier = xpath.getString(node, ".//*/fileIdentifier/CharacterString");
                    if (!resultMap.containsKey(fileIdentifier)) {
                        resultMap.put(fileIdentifier, new HashMap<String, String>());
                    }//from  w  ww.j ava  2s  .c  o m
                    Map<String, String> currentMap = resultMap.get(fileIdentifier);
                    currentMap.put("uuid", fileIdentifier);
                    currentMap.put("partner", xpath.getString(node, "partner"));
                    currentMap.put("provider", xpath.getString(node, "provider"));
                    currentMap.put("udk-class", xpath.getString(node, "udk-class"));
                    currentMap.put("source", xpath.getString(node, "source"));
                    currentMap.put("url", new URL(xpath.getString(node, "link")).toString());
                    currentMap.put("title", xpath.getString(node, ".//*/title/CharacterString"));
                    currentMap.put("description", xpath.getString(node, ".//*/abstract/CharacterString"));
                    Node addressNode = xpath.getNode(node, ".//*/contact/idfResponsibleParty");
                    String addressString = "";
                    String tmp = xpath.getString(addressNode, "indiviualName/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode, "organisationName/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/deliveryPoint/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/postalCode/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + " ";
                    tmp = xpath.getString(addressNode,
                            "ontactInfo/CI_Contact/address/CI_Address/city/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/country/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/electronicMailAddress/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Email: " + tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/phone/CI_Telephone/voice/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Tel: " + tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/phone/CI_Telephone/facsimile/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Fax: " + tmp + "\n";

                    currentMap.put("pointOfContact", addressString);
                }
                if (numberOfResults > 0 && numberOfResults >= PAGE_SIZE) {
                    currentPage++;
                } else {
                    moreResults = false;
                }
            } else {
                moreResults = false;
            }
        }

    }

    StringWriter sw = new StringWriter();
    ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(sw);
    boolean fieldsWritten = false;
    for (String key : resultMap.keySet()) {
        Map<String, String> result = resultMap.get(key);
        if (!fieldsWritten) {
            for (String field : result.keySet()) {
                ecsvp.print(field);
            }
            ecsvp.println("");
            fieldsWritten = true;
        }
        for (String value : result.values()) {
            ecsvp.print(value);
        }
        ecsvp.println("");
    }

    PrintWriter out = new PrintWriter("result.csv");
    out.write(sw.toString());
    out.close();
    in.close();

    System.out.println("Done.");
}

From source file:com.adobe.acs.commons.http.injectors.AbstractHtmlRequestInjector.java

@Override
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    if (!this.accepts(servletRequest, servletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;/*from   ww  w .  j a  v  a 2 s. c o m*/
    }

    // We know these are HTTP Servlet Requests since accepts passed
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    // Prepare to capture the original response
    final BufferingResponse originalResponse = new BufferingResponse(response);

    // Process and capture the original response
    filterChain.doFilter(request, originalResponse);

    // Get contents
    final String originalContents = originalResponse.getContents();

    if (originalContents != null && StringUtils.contains(response.getContentType(), "html")) {

        final int injectionIndex = getInjectIndex(originalContents);

        if (injectionIndex != -1) {
            final PrintWriter printWriter = response.getWriter();

            // Write all content up to the injection index
            printWriter.write(originalContents.substring(0, injectionIndex));

            // Inject the contents; Pass the request/response - consumer can use as needed
            inject(request, response, printWriter);

            // Write all content after the injection index
            printWriter.write(originalContents.substring(injectionIndex));
            return;
        }
    }

    if (originalContents != null) {
        response.getWriter().write(originalContents);
    }
}

From source file:org.jasig.portlet.test.mvc.tests.CacheControlTestController.java

/**
 * //from   w ww.ja va  2s .  c  o  m
 * @param request
 * @param response
 * @throws IOException
 */
@ResourceMapping(value = "jsonValidationCachingTest")
public void writeJsonContentWithValidationCaching(ResourceRequest request, ResourceResponse response)
        throws IOException {
    if (request.getETag() != null) {
        response.getCacheControl().setUseCachedContent(true);
        //always must set expirationtime with setUseCachedContent(true); use different value for testing
        response.getCacheControl().setExpirationTime(60);
        return;
    }

    response.getCacheControl().setETag(RandomStringUtils.randomAlphanumeric(16));
    // have to set an expiration time when using etag per portlet spec (empty expiration time is treated as "expired")
    response.getCacheControl().setExpirationTime(120);

    response.setContentType("application/json");
    PrintWriter writer = new PrintWriter(response.getPortletOutputStream());
    Date now = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:mm:ss");
    writer.write("{ \"hello\": \"true\", \"timeRendered\": \"" + sdf.format(now) + "\" }");
    writer.close();
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private void batchAdd(HttpServletRequest request, String pathInfo, HttpServletResponse response)
        throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {/*www  .  j a  v a2s.  c o  m*/
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    List<Map<String, Object>> eventList = mapper.readValue(reader, TYPE_LIST_OF_MAP);
    List<ValidationResult> failedEvents = null;
    for (Map<String, Object> values : eventList) {
        if (validator != null) {
            ValidationResult result = validator.validate(values, eventType);
            if (result == null || result.isSuccess()) {
                JetstreamEvent event = createEvent(values, eventType);
                inboundChannel.onMessage(event);
            } else {
                if (failedEvents == null) {
                    failedEvents = new ArrayList<ValidationResult>();
                }
                failedEvents.add(result);
            }
        } else {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
        }
    }
    if (failedEvents == null) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter printWriter = response.getWriter();
        printWriter.write("[");
        for (int i = 0, t = failedEvents.size() - 1; i < t; i++) {
            printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(i)));
            printWriter.write(",");
        }
        printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(failedEvents.size() - 1)));
        printWriter.write("]");
    }

}

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

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    response.setContentType("application/json");

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

    if (callType != null && callType.equals("savetopk")) {

        String cId = request.getParameter("cId");
        String cType = request.getParameter("cType");
        String map = request.getParameter("map");
        String algorithm = request.getParameter("algorithm");
        String ec_number = request.getParameter("ec_number");

        Map<String, String> key = new HashMap<>();

        if (cId != null && !cId.equals("")) {
            key.put("genomeId", cId);
        }//from  w w w.j  a  v a 2s . com
        if (cType != null && !cType.equals("")) {
            key.put("cType", cType);
        }

        if (map != null && !map.equals("")) {
            key.put("map", map);
        }

        if (algorithm != null && !algorithm.equals("")) {
            key.put("algorithm", algorithm);
        }

        if (ec_number != null && !ec_number.equals("")) {
            key.put("ec_number", ec_number);
        }

        key.put("which", "download_from_heatmap_feature");

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

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

        PrintWriter writer = response.getWriter();
        writer.write("" + pk);
        writer.close();

    } else if (callType != null && callType.equals("show")) {

        JSONObject jsonResult = new JSONObject();
        JSONArray results = new JSONArray();
        String pk = request.getParameter("pk");
        Map<String, String> key = jsonReader
                .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));

        DataApiHandler dataApi = new DataApiHandler(request);
        try {
            SolrQuery query = new SolrQuery("*:*");
            List<String> joinConditions = new ArrayList<>();

            if (key.containsKey("map")) {
                joinConditions.add("pathway_id:(" + key.get("map") + ")");
            }
            if (key.containsKey("algorithm")) {
                joinConditions.add("annotation:(" + key.get("algorithm") + ")");
            }
            if (key.containsKey("ec_number")) {
                joinConditions.add("ec_number:(" + key.get("ec_number").replaceAll(",", " OR ") + ")");
            }
            if (key.containsKey("genomeId")) {
                joinConditions.add("genome_id:(" + key.get("genomeId").replace(",", " OR ") + ")");
            }

            if (!joinConditions.isEmpty()) {
                query.addFilterQuery(SolrCore.PATHWAY.getSolrCoreJoin("feature_id", "feature_id",
                        StringUtils.join(joinConditions, " AND ")));
            }
            query.setRows(10000);

            LOGGER.debug("[{}] {}", SolrCore.FEATURE.getSolrCoreName(), query.toString());

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

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

            int numFound = (Integer) respBody.get("numFound");
            List<GenomeFeature> features = dataApi.bindDocuments((List<Map>) respBody.get("docs"),
                    GenomeFeature.class);

            for (GenomeFeature feature : features) {

                results.add(feature.toJSONObject());
            }

            jsonResult.put("total", numFound);
            jsonResult.put("results", results);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        PrintWriter writer = response.getWriter();
        jsonResult.writeJSONString(writer);
        writer.close();
    }
}