Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:com.silverware.ipdswizzler.EvernoteExporter.java

private void printContentAsHtml(PrintWriter printWriter, String content) {
    BufferedReader reader = new BufferedReader(new StringReader(content));
    try {/*  www .j  a va 2  s. c  o m*/
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            printWriter.print(StringEscapeUtils.escapeHtml4(line));
            printWriter.print("<p/>");
        }
    } catch (IOException e) {
        // FIXME(ssilver): Do something with this.
        return;
    }
}

From source file:com.ucap.uccc.cmis.impl.webservices.CmisWebServicesServlet.java

private void printPage(HttpServletRequest request, HttpServletResponse response, UrlBuilder baseUrl)
        throws ServletException, IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/html");
    response.setCharacterEncoding(IOUtils.UTF8);

    String urlEscaped = StringEscapeUtils
            .escapeHtml((new UrlBuilder(baseUrl)).addPath("cmis").addParameter("wsdl").toString());

    PrintWriter pw = response.getWriter();

    pw.print("<html><head><title>Apache Chemistry OpenCMIS - CMIS " + cmisVersion.value()
            + " Web Services</title>"
            + "<style><!--H1 {font-size:24px;line-height:normal;font-weight:bold;background-color:#f0f0f0;color:#003366;border-bottom:1px solid #3c78b5;padding:2px;} "
            + "BODY {font-family:Verdana,arial,sans-serif;color:black;font-size:14px;} "
            + "HR {color:#3c78b5;height:1px;}--></style></head><body>");
    pw.print("<h1>CMIS " + cmisVersion.value() + " Web Services</h1>");
    pw.print("<p>CMIS WSDL for all services: <a href=\"" + urlEscaped + "\">" + urlEscaped + "</a></p>");

    pw.print("</html></body>");
    pw.flush();//from w w  w.  ja v a  2s .c om
}

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

@Override
public void execute() throws IOException {
    final PrintWriter out = outputFilename == null ? new PrintWriter(System.out)
            : new PrintWriter(outputFilename);
    try {//  www .  j av a2 s .c  o m
        int index = 0;
        out.print("trackName\t");
        for (String attributeName : attributeNames) {
            if (!"ignore".equals(attributeName)) {
                out.print(attributeName);

                if (index != attributeNames.length) {
                    out.print('\t');
                }
            }
            index++;
        }
        out.println();
        for (String file : filenames) {
            final String file1 = file;
            String name = FilenameUtils.getName(file1);
            String filename = FilenameUtils.getBaseName(name);
            String[] tokens = filename.split(delimiter);
            out.printf("%s\t", adjustSuffix(name));
            for (int i = 0; i < attributeNames.length; i++) {
                if (!"ignore".equals(attributeNames[i])) {
                    if (tokens.length <= i) {
                        continue;
                    }
                    out.print(tokens[i]);
                    if (i != attributeNames.length) {
                        out.print('\t');
                    }
                }

            }
            out.println();
        }
        out.flush();
    } finally {
        out.close();

    }
}

From source file:com.qperior.gsa.oneboxprovider.QPOneBoxProviderServlet.java

/**
 * Top level request processor for this OneBox provider.
 * <p>//from   w  ww. ja v  a  2 s  .c om
 * Unpacks the HTTP requests parameter and passes them into one of the
 * <code>provideOneBoxResults</code> methods, delegating to one of the implemented
 * {@link #QPIProvider QPIProvider} methods depending on configurated
 * {@link QPProperties#getProviderType()}.
 * <p>
 * Returns an HTTP response with XML that adhere's to the Google DTD
 * defining the schema for OneBox for Enterprise provider results.
 * 
 * @param request 
 * @param response 
 * @throws ServletException 
 * @throws IOException 
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    QPIOneBoxResults res = null;

    try {
        try {
            // TODO: implement monitoring: JMX?

            // read in the request parameter
            QPCallParameter callParameter = new QPCallParameter(request);
            this.log.info("Servlet 1: " + callParameter.toString());

            // get the invoker for the right provider
            QPProviderInvoker invoker = QPProviderInvoker.createProviderInvoker(QPProperties.getProvider(),
                    QPProperties.getSecurityProvider(), callParameter);
            this.log.info("Servlet 2: " + invoker.toString());

            // AuthType has to be set, see constructor of QPCallParameter
            if (invoker.getSecurityProvider().getActualAuthType() == null) {
                res = new QPOneBoxResults();
                this.log.error("User authentication type not recognized: " + request.getParameter("authType"));
                res.setFailure(QPResultCode.securityFailure,
                        "User authentication type not recognized: " + request.getParameter("authType"),
                        invoker.getProviderName());
            } else {
                // AuthType has to be supported by the provider implementation
                if (!invoker.getSecurityProvider().isActualAuthTypeSupported()) {

                    res = new QPOneBoxResults();
                    this.log.error(
                            "User authentication type not supported: " + request.getParameter("authType"));
                    res.setFailure(QPResultCode.securityFailure,
                            "User authentication type not supported: " + request.getParameter("authType"),
                            invoker.getProviderName());
                } else {

                    try {
                        // Invoke the provider
                        res = invoker.invokeProvider();
                        this.log.info("Servlet 3: " + res.toString());
                    } catch (QPProviderException pe) {
                        res = new QPOneBoxResults();
                        this.log.error("Exception in invoking the provider", pe);
                        res.setFailure(QPResultCode.lookupFailure, "Exception in invoking the provider.",
                                invoker.getProviderName());
                    }
                }
            }
        }
        // Exception in converting the request in callParameter
        catch (QPRequestValidateException rve) {
            res = new QPOneBoxResults();
            this.log.error("Error in validating input parameter.", rve);
            res.setFailure(QPResultCode.securityFailure,
                    "QPRequestValidateException: " + rve.getLocalizedMessage(), "Provider not initialized.");
        }

        // Defines response MIME type
        response.setContentType("text/xml");
        // Write response back as XML string
        PrintWriter out = response.getWriter();
        String resString = res.toXMLString();
        out.print(resString);
        this.log.info("Servlet 4: " + resString);
        out.close();
    } catch (Exception exc) {
        this.log.error("Unhandled exception in servlet. ", exc);
    }
}

From source file:com.adito.vfs.webdav.methods.PROPFIND.java

/**
 * <p>/*from  www . j a  v a 2s.  c  om*/
 * Process the <code>PROPFIND</code> method.
 * </p>
 */
public void process(DAVTransaction transaction, VFSResource resource) throws LockedException, IOException {
    if (transaction.isRequiredRootRedirect() || !transaction.isResourcePath(resource.getFullPath())) {
        throw new DAVRedirection(false, resource);
    }

    String handle = VFSLockManager.getNewHandle();
    VFSLockManager.getInstance().lock(resource, transaction.getSessionInfo(), false, false, handle);
    try {
        /* Check depth */
        int depth = transaction.getDepth();
        if (depth > 1)
            throw new DAVException(403, "Invalid depth");

        if (SystemProperties.get("adito.disableFolderBrowsing", "true").equals("true")
                && !resource.isBrowsable()) {
            transaction.getResponse().sendError(404, "Not Found");
            return;
        }
        /* What to do on a collection resource */
        transaction.setStatus(207);
        transaction.setContentType("text/xml; charset=\"utf-8\"");
        PrintWriter out = transaction.write("utf-8");

        /* Output the XML declaration and the root document tag */
        out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        out.println("<D:multistatus xmlns:D=\"DAV:\">");

        /* Process this resource's property (always) */
        this.process(transaction, out, resource);

        /* Process this resource's children (if required) */
        if (resource.isCollection() && (depth > 0)) {
            Iterator children = resource.getChildren();
            while (children.hasNext()) {
                VFSResource child = (VFSResource) children.next();
                this.process(transaction, out, child);
            }
        }

        /* Close up the XML Multi-Status response */
        out.println("</D:multistatus>");
        out.flush();

        // Mount may be null at root
        if (resource.getMount() != null) {
            resource.getMount().resourceAccessList(resource, transaction, null);
        }

    } catch (Exception e) {
        // Mount may be null at root
        if (resource.getMount() != null) {
            resource.getMount().resourceAccessList(resource, transaction, e);
        }
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        VFSLockManager.getInstance().unlock(transaction.getSessionInfo(), handle);
    }
}

From source file:com.sslexplorer.vfs.webdav.methods.PROPFIND.java

/**
 * <p>/*from   ww  w.j a  va2  s  . co  m*/
 * Process the <code>PROPFIND</code> method.
 * </p>
 */
public void process(DAVTransaction transaction, VFSResource resource) throws LockedException, IOException {
    if (transaction.isRequiredRootRedirect() || !transaction.isResourcePath(resource.getFullPath())) {
        throw new DAVRedirection(false, resource);
    }

    String handle = VFSLockManager.getNewHandle();
    VFSLockManager.getInstance().lock(resource, transaction.getSessionInfo(), false, false, handle);
    try {
        /* Check depth */
        int depth = transaction.getDepth();
        if (depth > 1)
            throw new DAVException(403, "Invalid depth");

        if (SystemProperties.get("sslexplorer.disableFolderBrowsing", "true").equals("true")
                && !resource.isBrowsable()) {
            transaction.getResponse().sendError(404, "Not Found");
            return;
        }
        /* What to do on a collection resource */
        transaction.setStatus(207);
        transaction.setContentType("text/xml; charset=\"utf-8\"");
        PrintWriter out = transaction.write("utf-8");

        /* Output the XML declaration and the root document tag */
        out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        out.println("<D:multistatus xmlns:D=\"DAV:\">");

        /* Process this resource's property (always) */
        this.process(transaction, out, resource);

        /* Process this resource's children (if required) */
        if (resource.isCollection() && (depth > 0)) {
            Iterator children = resource.getChildren();
            while (children.hasNext()) {
                VFSResource child = (VFSResource) children.next();
                this.process(transaction, out, child);
            }
        }

        /* Close up the XML Multi-Status response */
        out.println("</D:multistatus>");
        out.flush();

        // Mount may be null at root
        if (resource.getMount() != null) {
            resource.getMount().resourceAccessList(resource, transaction, null);
        }

    } catch (Exception e) {
        // Mount may be null at root
        if (resource.getMount() != null) {
            resource.getMount().resourceAccessList(resource, transaction, e);
        }
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    } finally {
        VFSLockManager.getInstance().unlock(transaction.getSessionInfo(), handle);
    }
}

From source file:de.micromata.genome.gwiki.page.search.SearchFoundHighlighterFilter.java

public Void filter(GWikiFilterChain<Void, GWikiServeElementFilterEvent, GWikiServeElementFilter> chain,
        GWikiServeElementFilterEvent event) {
    String words = event.getWikiContext().getRequestParameter("_gwhiwords");
    if (StringUtils.isEmpty(words) == true) {
        return chain.nextFilter(event);
    }/* w w w  .  j  a v  a  2  s .  co  m*/
    GWikiElement el = event.getElement();
    if (el == null || (el instanceof GWikiWikiPage) == false) {
        return chain.nextFilter(event);
    }
    // el.getElementInfo().get

    HttpServletResponse resp = event.getWikiContext().getResponse();

    final StringWriter sout = new StringWriter();
    final PrintWriter pout = new PrintWriter(sout);
    final Holder<Boolean> skip = new Holder<Boolean>(Boolean.FALSE);
    HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(resp) {

        @Override
        public void sendRedirect(String location) throws IOException {
            skip.set(Boolean.TRUE);
            super.sendRedirect(location);
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            skip.set(Boolean.TRUE);
            return super.getOutputStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            return pout;
        }

        @Override
        public void resetBuffer() {
            sout.getBuffer().setLength(0);
        }
    };
    event.getWikiContext().setResponse(wrapper);
    chain.nextFilter(event);
    if (skip.get() == Boolean.TRUE) {
        return null;
    }
    try {
        PrintWriter pr = resp.getWriter();
        String orgString = sout.getBuffer().toString();
        if (StringUtils.containsIgnoreCase(orgString, "<html") == false) {
            pr.print(orgString);
            return null;
        }

        StringWriter filteredContent = new StringWriter();
        SearchHilightHtmlFilter filter = new SearchHilightHtmlFilter(filteredContent,
                Converter.parseStringTokens(words, ", ", false));
        filter.doFilter(orgString);
        // System.out.println("\n\nOrig:\n" + sout.getBuffer().toString() + "\n\nFiltered:\n" + filteredContent.getBuffer().toString());

        // pr
        // .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        pr.print(filteredContent.getBuffer().toString());
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
    return null;
}

From source file:de.viaboxx.nlstools.formats.BundleWriterJavaInterface.java

protected void writeKeyValue(PrintWriter pw, String key, String value) {
    printIndent(pw).print("String ");
    pw.print(key);
    pw.print(" = \"");
    pw.print(value);/*from  w ww .j  a  va  2  s  .c  om*/
    pw.println("\";");
}

From source file:org.loklak.api.server.SuggestServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//from  w w w  .j a v  a 2s .c  om
    }

    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);

    int requestkey = post.hashCode();
    Map<String, Object> m = post.isDoS_servicereduction() ? cache.get(requestkey) : null;
    if (m == null) {
        boolean local = post.isLocalhostAccess();
        boolean delete = post.get("delete", false);
        int count = post.get("count", 10); // number of queries
        String query = post.get("q", ""); // to get a list of queries which match; to get all latest: leave q empty
        String source = post.get("source", "all"); // values: all,query,geo
        String orders = post.get("order", query.length() == 0 ? "desc" : "asc").toUpperCase();
        SortOrder order = SortOrder.valueOf(orders);
        String orderby = post.get("orderby", query.length() == 0 ? "retrieval_next" : "query_count");
        int timezoneOffset = post.get("timezoneOffset", 0);
        Date since = post.get("since", "").equals("now") ? new Date()
                : post.get("since", (Date) null, timezoneOffset);
        Date until = post.get("until", "").equals("now") ? new Date()
                : post.get("until", (Date) null, timezoneOffset);
        String selectby = post.get("selectby", "retrieval_next");
        ResultList<QueryEntry> queryList = new ResultList<>();

        if ((source.equals("all") || source.equals("query")) && query.length() >= 0) {
            long start = System.currentTimeMillis();
            queryList = DAO.SearchLocalQueries(query, count, orderby, "long", order, since, until, selectby);
            post.recordEvent("localqueries_time", System.currentTimeMillis() - start);
        }

        if (delete && local && queryList.size() > 0) {
            long start = System.currentTimeMillis();
            for (QueryEntry qe : queryList)
                DAO.deleteQuery(qe.getQuery(), qe.getSourceType());
            queryList.clear();
            queryList = DAO.SearchLocalQueries(query, count, orderby, "long", order, since, until, selectby);
            post.recordEvent("localquerydelete_time", System.currentTimeMillis() - start);
        }

        if (source.equals("all") || source.equals("geo")) {
            long start = System.currentTimeMillis();
            LinkedHashSet<String> suggestions = DAO.geoNames.suggest(query, count, 0);
            if (suggestions.size() < count && query.length() > 2)
                suggestions.addAll(DAO.geoNames.suggest(query, count, 1));
            if (suggestions.size() < count && query.length() > 5)
                suggestions.addAll(DAO.geoNames.suggest(query, count, 2));
            for (String s : suggestions) {
                QueryEntry qe = new QueryEntry(s, 0, Long.MAX_VALUE, SourceType.IMPORT, false);
                queryList.add(qe);
            }
            post.recordEvent("suggestionsquery_time", System.currentTimeMillis() - start);
        }

        long start = System.currentTimeMillis();
        post.setResponse(response, "application/javascript");

        List<Object> queries = new ArrayList<>();
        if (queryList != null)
            for (QueryEntry t : queryList)
                queries.add(t.toMap());

        int random = post.get("random", -1);
        if (random > 0 && random < queries.size()) {
            // take the given number from the result list and use random to choose
            List<Object> random_queries = new ArrayList<>();
            Random r = new Random(System.currentTimeMillis());
            while (random-- > 0) {
                random_queries.add(queries.remove(r.nextInt(queries.size())));
                int shrink = Math.max(queries.size() / 2, random * 10);
                while (queries.size() > shrink)
                    queries.remove(queries.size() - 1); // prefer from top
            }
            queries = random_queries;
        }

        // generate json
        m = new LinkedHashMap<String, Object>();
        Map<String, Object> metadata = new LinkedHashMap<String, Object>();
        metadata.put("count", queryList == null ? "0" : Integer.toString(queries.size()));
        metadata.put("hits", queryList.getHits());
        metadata.put("query", query);
        metadata.put("order", orders);
        metadata.put("orderby", orderby);
        if (since != null)
            metadata.put("since", AbstractIndexEntry.utcFormatter.print(since.getTime()));
        if (until != null)
            metadata.put("until", AbstractIndexEntry.utcFormatter.print(until.getTime()));
        if (since != null || until != null)
            metadata.put("selectby", selectby);
        metadata.put("client", post.getClientHost());
        m.put("search_metadata", metadata);

        m.put("queries", queries);
        post.recordEvent("postprocessing_time", System.currentTimeMillis() - start);
    }

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(minified ? new ObjectMapper().writer().writeValueAsString(m)
            : new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(m));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}