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.funambol.server.sendlog.LogServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from w w  w.j  ava  2s  .c om
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Checks mandatory headers:
    if (!validateMandatoryHeaders(request, response)) {
        //
        // If the mandatory headers are missed or in a bad format, it's
        // not possible to continue..
        //
        return;
    }

    // Authorizes and authenticates the user
    HttpBasicAuthenticator authenticator = null;
    try {

        if (log.isTraceEnabled()) {
            log.trace("Authenticating the incoming request..");
        }
        authenticator = new HttpBasicAuthenticator(credentialHeader, deviceId);

        authenticator.authenticate();

    } catch (UnauthorizedException e) {
        log.error(AUTHENTICATE_REQUEST_ERRMSG, e);
        handleError(response, e);
        return;
    } catch (Throwable e) {
        log.error(AUTHENTICATE_REQUEST_UNEXPECTED_ERRMSG, e);
        handleError(response, e);
        return;
    }

    InputStream inputStream = null;
    try {
        inputStream = request.getInputStream();
    } catch (IOException e) {
        log.error(ACCESS_REQUEST_AS_INPUT_STREAM_ERRMSG, e);
        handleError(response, e);
        return;
    }

    LogInformationProvider provider = null;
    FileUploader uploader = null;
    try {
        if (log.isTraceEnabled()) {
            log.trace("Handling the incoming request..");
        }
        String username = authenticator.getUsername();
        provider = new LogInformationProvider(inputStream, username, deviceId, contentType, clientsLogBaseDir,
                clientsLogMaxSize);

        uploader = new FileUploader(provider);

        uploader.uploadFile();

    } catch (UploadFileException e) {
        log.error(PROCESSING_UPLOAD_ERRMSG, e);
        handleError(response, e);
        return;
    } catch (Throwable e) {
        log.error(HANDLE_REQUEST_UNEXPECTED_ERRMSG, e);
        handleError(response, e);
        return;
    }

    PrintWriter writer = null;
    try {
        response.setContentType(MimeTypeDictionary.TEXT_PLAIN);
        response.setStatus(HttpServletResponse.SC_OK);
        writer = response.getWriter();
        writer.write(UPLOAD_COMPLETED_MSG);
        writer.flush();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:gumga.framework.presentation.push.GumgaNotificationsServlet.java

@RequestMapping("/notifications/source")
protected void notifications(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    QueryObject qo = new QueryObject();
    qo.setAq("destinationLogin='" + GumgaThreadScope.login.get() + "' and viewedIn is null ");
    qo.setAq("viewedIn is null ");
    qo.setPageSize(1000);//from  w ww  . j a v a 2s .co m

    for (int i = 0; i < cycles; i++) {
        SearchResult<GumgaMessage> pesquisa = messageService.pesquisa(qo);
        String message = "data: {" + " \"newMessagesCount\":" + pesquisa.getCount() + ",\"newMessages\":"
                + pesquisa.getValues() + "}";
        writer.write(message + "\n\n");
        writer.flush();
        try {
            Thread.sleep(intervalTime);
        } catch (InterruptedException e) {
            log(e.getMessage());
        }
    }
    writer.close();
}

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

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

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

    if (sraction != null && sraction.equals("save_params")) {

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

        String taxonId = "";
        String cType = request.getParameter("context_type");
        String cId = request.getParameter("context_id");
        if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) {
            taxonId = cId;/*w  ww.  ja va  2  s . c  o  m*/
        }
        String keyword = request.getParameter("keyword");
        String state = request.getParameter("state");

        if (!taxonId.equalsIgnoreCase("")) {
            key.put("taxonId", taxonId);
        }
        if (keyword != null) {
            key.put("keyword", keyword.trim());
        }
        if (state != null) {
            key.put("state", state);
        }
        long pk = (new Random()).nextLong();

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

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

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

        switch (need) {
        case "0": {

            String pk = request.getParameter("pk");
            //
            Map data = processExperimentTab(request);
            Map<String, String> key = (Map) data.get("key");
            int numFound = (Integer) data.get("numFound");
            List<Map> sdl = (List<Map>) data.get("experiments");

            JSONArray docs = new JSONArray();
            for (Map doc : sdl) {
                JSONObject item = new JSONObject();
                item.putAll(doc);
                docs.add(item);
            }

            if (data.containsKey("facets")) {
                JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets"));
                key.put("facets", facets.toJSONString());
                SessionHandler.getInstance().set(SessionHandler.PREFIX + pk,
                        jsonWriter.writeValueAsString(key));
            }

            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();

            break;
        }
        case "1": {

            String pk = request.getParameter("pk");
            //
            Map data = processProteinTab(request);
            Map<String, String> key = (Map) data.get("key");
            int numFound = (Integer) data.get("numFound");
            List<Map> sdl = (List<Map>) data.get("proteins");

            JSONArray docs = new JSONArray();
            for (Map doc : sdl) {
                JSONObject item = new JSONObject(doc);
                docs.add(item);
            }

            if (data.containsKey("facets")) {
                JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets"));
                key.put("facets", facets.toJSONString());
                SessionHandler.getInstance().set(SessionHandler.PREFIX + pk,
                        jsonWriter.writeValueAsString(key));
            }

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

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.write(jsonResult.toString());
            writer.close();

            break;
        }
        case "tree": {

            String pk = request.getParameter("pk");
            String state;
            Map<String, String> key = jsonReader
                    .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk));

            if (key.containsKey("state"))
                state = key.get("state");
            else
                state = request.getParameter("state");

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

            JSONArray tree = new JSONArray();
            try {
                if (!key.containsKey("facets") && !key.get("facets").isEmpty()) {
                    JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets"));
                    DataApiHandler dataApi = new DataApiHandler(request);
                    tree = FacetHelper.processStateAndTree(dataApi, SolrCore.PROTEOMICS_EXPERIMENT, key, need,
                            facet_fields, key.get("facet"), state, null, 4);
                }
            } catch (ParseException e) {
                LOGGER.error(e.getMessage(), e);
            }

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            tree.writeJSONString(writer);
            writer.close();

            break;
        }
        case "getFeatureIds": {

            String keyword = request.getParameter("keyword");
            Map<String, String> key = new HashMap<>();
            key.put("keyword", keyword);

            DataApiHandler dataApi = new DataApiHandler(request);

            SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false);

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

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

            JSONObject object = new JSONObject(respBody);
            //            solr.setCurrentInstance(SolrCore.PROTEOMICS_PROTEIN);
            //            JSONObject object = null; //solr.getData(key, null, facet, 0, -1, false, false, false);

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            object.writeJSONString(writer);
            //            writer.write(object.get("response").toString());
            writer.close();

            break;
        }
        case "getPeptides": {

            String experiment_id = request.getParameter("experiment_id");
            String na_feature_id = request.getParameter("na_feature_id");

            Map<String, String> key = new HashMap<>();
            key.put("keyword", "na_feature_id:" + na_feature_id + " AND experiment_id:" + experiment_id);
            key.put("fields", "peptide_sequence");

            DataApiHandler dataApi = new DataApiHandler(request);

            SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false);

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

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

            JSONObject object = new JSONObject();
            object.putAll(respBody);

            //            solr.setCurrentInstance(SolrCore.PROTEOMICS_PEPTIDE);
            //            JSONObject object = solr.getData(key, null, facet, 0, -1, false, false, false);
            //            object = (JSONObject) object.get("response");
            object.put("aa", FASTAHelper.getFASTASequence(request, Arrays.asList(na_feature_id), "protein"));

            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            object.writeJSONString(writer);
            writer.close();
            break;
        }
        }
    }
}

From source file:com.jeans.iservlet.controller.impl.ImportController.java

private void closeProgressDialog(PrintWriter out) {
    out.write("<script>parent.__hidePrg();</script>");
    out.flush();
}

From source file:org.apache.servicemix.http.HttpWsdlTest.java

public void testExternalNonStandaloneWsdl() throws Exception {

    //startup-jetty as mirror for 
    //http://www.ws-i.org/SampleApplications/SupplyChainManagement/2002-08/Retailer.wsdl
    int remoteHttpServerPort = getFreePortNumber();
    Server remoteServer = new Server(remoteHttpServerPort);
    Handler handler = new AbstractHandler() {

        public void handle(String arg0, HttpServletRequest req, HttpServletResponse res, int arg3)
                throws IOException, ServletException {

            res.setContentType("text/xml");
            PrintWriter writer = res.getWriter();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("wsdls" + req.getPathInfo())));
            String line = br.readLine();
            while (line != null) {
                writer.write(line);
                line = br.readLine();//from w  w  w .j  a v  a  2  s.c om
            }
            br.close();
            writer.close();
        }

    };

    remoteServer.addHandler(handler);
    remoteServer.start();

    try {
        int localHttpServerPort = getFreePortNumber();

        // HTTP Component
        HttpEndpoint ep = new HttpEndpoint();
        ep.setService(new QName("http://servicemix.apache.org/wsn/jaxws", "PullPointService"));
        ep.setEndpoint("JBI");
        ep.setRoleAsString("consumer");
        ep.setLocationURI("http://localhost:" + localHttpServerPort + "/Service/");
        ep.setDefaultMep(MessageExchangeSupport.IN_OUT);
        ep.setWsdlResource(new UrlResource("http://localhost:" + remoteHttpServerPort + "/wsn.wsdl"));
        HttpComponent http = new HttpComponent();
        http.setEndpoints(new HttpEndpoint[] { ep });
        container.activateComponent(http, "PullPointService");

        // Start container
        container.start();

        GetMethod get = new GetMethod("http://localhost:" + localHttpServerPort + "/Service/?wsdl");
        int state = new HttpClient().executeMethod(get);
        assertEquals(HttpServletResponse.SC_OK, state);
        Document doc = (Document) new SourceTransformer()
                .toDOMNode(new StringSource(get.getResponseBodyAsString()));
        get.releaseConnection();

        // Test WSDL
        WSDLFactory factory = WSDLFactory.newInstance();
        WSDLReader reader = factory.newWSDLReader();
        Definition def;

        def = reader.readWSDL("http://localhost:" + localHttpServerPort + "/Service/?wsdl", doc);
        assertNotNull(def);
        assertNotNull(def.getImports());
        assertEquals(1, def.getImports().size());

    } finally {
        remoteServer.stop();
    }

}

From source file:de.tudarmstadt.lt.lm.web.servlet.LanguageModelProviderServlet.java

private void show(String inputtype, String lm_key, String plaintext, String crawluri, boolean show_all_ngrams,
        PrintWriter w) throws Exception {
    if ("uri".equals(inputtype))
        plaintext = null;//w w w.j  a va  2 s  .  co  m
    if ("text".equals(inputtype))
        crawluri = null;

    if (plaintext == null && crawluri == null) // no parameter set
        plaintext = _test_text;

    w.write(_html_header);
    final Integer lm_index = _lm_keys.get(lm_key);
    if (lm_index == null) {
        LOG.error("Language model '{}' unknown.", lm_key);
        w.format("<p>Language model '%s' unknown. Please go to <a href='?'>main page</a>.</p>", lm_key);
        return;
    }

    StringProviderMXBean s = _lm_provider.get(lm_index);
    if (s == null) {
        if (!connectToLanguageModel(lm_key)) {
            w.format("<p>Language Model is loading. Please try again later.</p>", lm_key);
            w.write(_html_footer);
            w.flush();
            return;
        }
        s = _lm_provider.get(lm_index);
    }

    w.format("<h3>%s</h3>%n", lm_key);

    double crawl_perp = -1d;

    if (crawluri != null) {
        Object[] triple = crawl_and_extract_plaintext(crawluri, lm_key, lm_index);
        plaintext = (String) triple[0];
        crawl_perp = (Double) triple[1];
    } else
        crawluri = "";

    w.format(
            "<p>Crawl URI:</p>%n<p><form action='' method='get'><input type='text' name='crawluri' value='%s' size='100' />&nbsp;&nbsp;<input type='submit' value='Submit'><input type='hidden' name='inputtype' value='uri'><input type='hidden' name='lm' value='%s'><input type='hidden' name='action' value='show'></form></p>%n",
            crawluri, lm_key);
    w.format("<p>Crawler Perplexity = %012g</p>%n", crawl_perp);
    w.format("<p>Bytes Plaintext = %d</p>%n", plaintext.getBytes().length);
    w.format("<br />%n");
    w.format(
            "<p>Plaintext:</p>%n<p><form action='' method='get'><textarea rows='20' cols='150' name='plaintext'>%s</textarea><p><input type='submit' value='Submit'></p><input type='hidden' name='inputtype' value='text'><input type='hidden' name='lm' value='%s'><input type='hidden' name='action' value='show'></form></p>%n",
            plaintext, lm_key);
    w.format("<p>Perplexity = %012g</p>%n", s.getPerplexity(plaintext, false));
    w.format("<br />%n");

    w.format("<tt>%n");
    List<String>[] ngram_sequence = s.getNgrams(plaintext);
    w.format("+++ #ngrams= %d +++ <br /><br />%n", ngram_sequence.length);

    // TODO: provide ngrams
    for (int i = 0; i < ngram_sequence.length && (i <= 500 || show_all_ngrams); i++) {
        List<String> ngram = ngram_sequence[i];
        double log10_prob = s.getNgramLog10Probability(ngram);
        double prob10 = Math.pow(10, log10_prob);
        double log2_prob = log10_prob / Math.log10(2);
        int[] ngram_ids = s.getNgramAsIds(ngram);
        List<String> ngram_lm = s.getNgramAsWords(ngram_ids);
        w.format("%s <br />%n &nbsp;=> %s <br />%n &nbsp;= %012g (log_2 = %012g)<br /><br />%n",
                StringEscapeUtils.escapeHtml(ngram.toString()),
                StringEscapeUtils.escapeHtml(ngram_lm.toString()), prob10, log2_prob);
    }
    if (ngram_sequence.length > 500 && !show_all_ngrams)
        w.format("...%n");
    w.format("<br />%n");
    w.format("</tt>%n");

    w.write(_html_footer);

}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

private void writeResponse(HttpServletResponse response, String result, MimeType mimeType) throws IOException {
    response.setContentType(mimeType.toString());
    PrintWriter writer = response.getWriter();
    writer.write(result);
    writer.flush();/*from ww w  .  ja v  a2 s. co m*/
}

From source file:com.jeans.iservlet.controller.impl.ImportController.java

private void showProgressDialog(PrintWriter out, String title) {
    out.write("<script>parent.__showPrg('" + title + "');</script>");
    out.flush();/*from ww w  .  j a  va2 s. c  om*/
}

From source file:com.sap.dirigible.repository.ext.db.DBUtils.java

/**
 * Read whole SQL script from the class path. It can contain multiple
 * statements separated with ';'/*  www  . j ava2 s.c o  m*/
 * 
 * @param path
 * @return the SQL script as a String
 */
public String readScript(Connection conn, String path, Class<?> clazz) throws IOException {
    logger.debug("entering readScript"); //$NON-NLS-1$
    String sql = null;
    InputStream in = clazz.getResourceAsStream(path);
    if (in == null) {
        throw new IOException("SQL script does not exist: " + path);
    }

    BufferedInputStream bufferedInput = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(baos);
    byte[] buffer = new byte[1024];

    try {
        bufferedInput = new BufferedInputStream(in);
        int bytesRead = 0;

        while ((bytesRead = bufferedInput.read(buffer)) != -1) {
            String chunk = new String(buffer, 0, bytesRead, Charset.defaultCharset());
            writer.write(chunk);
        }

        writer.flush();

        sql = new String(baos.toByteArray(), Charset.defaultCharset());
        String productName = conn.getMetaData().getDatabaseProductName();
        IDialectSpecifier dialectSpecifier = getDialectSpecifier(productName);
        sql = dialectSpecifier.specify(sql);

    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } catch (SQLException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            if (bufferedInput != null)
                bufferedInput.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }

    logger.debug("exiting readScript"); //$NON-NLS-1$

    return sql;
}

From source file:com.jeans.iservlet.controller.impl.ImportController.java

private void showError(PrintWriter out, String message) {
    out.write("<script>parent.__error('" + message + "');</script>");
    out.flush();/*w  ww .ja  v a 2 s  .c  o  m*/
}