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:edu.cornell.mannlib.vitro.webapp.servlet.ConceptSearchServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doGet(req, resp);
    VitroRequest vreq = new VitroRequest(req);

    try {//  w  w  w. jav  a  2s .c  om
        ServletContext ctx = vreq.getSession().getServletContext();
        //Captures both concept list and any errors if they exist
        ConceptInfo conceptInfo = new ConceptInfo();
        conceptInfo.setSemanticServicesError(null);

        //Json output should be written out
        List<Concept> results = null;
        try {
            results = ConceptSearchServiceUtils.getSearchResults(ctx, vreq);
        } catch (Exception ex) {
            SemanticServicesError semanticServicesError = new SemanticServicesError("Exception encountered ",
                    ex.getMessage(), "fatal");
            log.error("An error occurred retrieving search results", ex);
            conceptInfo.setSemanticServicesError(semanticServicesError);
        }
        conceptInfo.setConceptList(results);

        String json = renderJson(conceptInfo);

        json = StringUtils.replaceChars(json, "\r\t\n", "");
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        writer.write(json);
        writer.close();

    } catch (Exception ex) {
        log.warn(ex, ex);
    }
}

From source file:eu.stratosphere.nephele.jobmanager.web.SetupInfoServlet.java

private void writeTaskmanagers(HttpServletResponse resp) throws IOException {

    Set<InstanceConnectionInfo> keys = jobmanager.getInstances().keySet();
    List<InstanceConnectionInfo> list = new ArrayList<InstanceConnectionInfo>(keys);
    Collections.sort(list);//from w  w w .  j  a v a 2 s.  c  o  m

    JSONObject obj = new JSONObject();
    JSONArray array = new JSONArray();
    for (InstanceConnectionInfo k : list) {
        JSONObject objInner = new JSONObject();

        AbstractInstance instance = jobmanager.getInstances().get(k);
        // long time = new Date().getTime() - instance.getLastHeartBeat();

        try {
            objInner.put("inetAdress", k.getAddress());
            objInner.put("ipcPort", k.getIPCPort());
            objInner.put("dataPort", k.getDataPort());
            objInner.put("timeSinceLastHeartbeat", "?");
            objInner.put("slotsNumber", "?"); // instance.getNumberOfSlots()
            objInner.put("freeSlots", "?"); // instance.getNumberOfAvailableSlots());
            objInner.put("cpuCores", instance.getHardwareDescription().getNumberOfCPUCores());
            objInner.put("physicalMemory",
                    instance.getHardwareDescription().getSizeOfPhysicalMemory() / 1048576);
            objInner.put("freeMemory", instance.getHardwareDescription().getSizeOfFreeMemory() / 1048576);
            array.put(objInner);
        } catch (JSONException e) {
            LOG.warn("Json object creation failed", e);
        }

    }
    try {
        obj.put("taskmanagers", array);
    } catch (JSONException e) {
        LOG.warn("Json object creation failed", e);
    }

    PrintWriter w = resp.getWriter();
    w.write(obj.toString());
}

From source file:com.eternity.common.communication.servlet.AsyncDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;//  w  ww .  jav  a2s  . c o  m
    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (charset == null) {
        charset = "UTF-8";
    }

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim());
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable or missing ACCEPT header!");
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    MessageConsumer.dispatchAsyncMessage(message, null, hostName);
    Response result = new Response();
    result.setStatus(200);
    resp.getOutputStream().write(encoder.encode(result).array());
}

From source file:javax.portlet.tck.portlets.AddlRequestTests_SPEC2_11_EventReq_event.java

@Override
public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException {

    portletResp.setContentType("text/html");
    PrintWriter writer = portletResp.getWriter();
    writer.write("<h3>Event Companion Portlet </h3>\n");
    writer.write("<p>AddlRequestTests_SPEC2_11_EventReq_event</p>\n");

    String msg = (String) portletReq.getPortletSession()
            .getAttribute(RESULT_ATTR_PREFIX + "AddlRequestTests_SPEC2_11_EventReq", APPLICATION_SCOPE);
    msg = (msg == null) ? "Not ready. click test case link." : msg;
    writer.write("<p>" + msg + "</p>\n");

}

From source file:org.eurekastreams.server.service.servlets.GetThemeCssServlet.java

/**
 * {@inheritDoc}//w ww  .  ja  v a 2 s.  c  om
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // grab items from spring context if not initialized, 500 error if unable
    try {
        initializeSpringObjects();
    } catch (Exception e) {
        httpError(HttpStatus.SC_INTERNAL_SERVER_ERROR, response);
        return;
    }

    // Convert request to theme uuid, 400 if error.
    String themeUuid = null;
    try {
        themeUuid = requestUriToThemeUuIdTransformer.transform(request.getRequestURI());

        // StringUtils.isEmpty checks for null or empty string, String.isEmtpy only checks length
        if (StringUtils.isEmpty(themeUuid)) {
            httpError(HttpStatus.SC_BAD_REQUEST, response);
            return;
        }
    } catch (Exception e) {
        httpError(HttpStatus.SC_BAD_REQUEST, response);
        return;
    }

    // get the string css by theme uuid, 404 on error.
    String themeCss = null;
    try {
        themeCss = getThemeCssByUuidMapper.execute(themeUuid);
    } catch (Exception e) {
        httpError(HttpStatus.SC_NOT_FOUND, response);
        return;
    }

    response.setContentType("text/css");
    response.setContentLength(themeCss.getBytes().length);

    PrintWriter out = response.getWriter();
    out.write(themeCss);
    out.flush();
}

From source file:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*  ww  w .j  a v a2  s . c  o  m*/

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}

From source file:com.alibaba.doris.admin.service.main.DorisAdminServlet.java

@SuppressWarnings("unchecked")
private void doResponse(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String ip = DorisConfigUtil.getIpAddr(request);
    String uuid = UUID.randomUUID().toString();
    long begin = System.currentTimeMillis();
    if (logger.isDebugEnabled()) {
        logger.debug("The request is from :" + ip + ", new assigned id is :" + uuid);
    }//from  w w w .  j  a v a2  s  . c o m
    String resTxt = AdminServiceConstants.ADMIN_SERVICE_ERROR;
    try {

        String actionName = request.getParameter(AdminServiceConstants.ADMIN_SERVICE_ACTION_NAME);

        if (StringUtils.isNotEmpty(actionName)) {
            // get Action
            AdminServiceAction serviceAction = AdminServiceActionFactory.getAdminServiceAction(actionName);
            if (logger.isDebugEnabled()) {
                logger.debug("The action for request\"" + uuid + "\" is " + actionName);
            }
            Map<String, String[]> paramsMap = request.getParameterMap();
            Map<String, String> paras = new HashMap<String, String>();
            for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
                String paraKey = entry.getKey();
                String[] values = entry.getValue();
                if (values.length > 0) {
                    String paraValue = entry.getValue()[0];
                    paras.put(paraKey, paraValue);
                }
            }
            // used in some action
            paras.put(AdminServiceConstants.REMOTE_IP, ip);

            resTxt = serviceAction.execute(paras);

        } else {
            // return empty string for request that is not specified action name.
            resTxt = AdminServiceConstants.ADMIN_SERVICE_ERROR;
        }

    } catch (Exception e) {
        resTxt = AdminServiceConstants.ADMIN_SERVICE_ERROR;
        logger.error(e.getMessage(), e);
    }

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/plain;charset=UTF-8");
    PrintWriter writer = response.getWriter();
    writer.write(resTxt);

    writer.close();

    if (logger.isDebugEnabled()) {
        long end = System.currentTimeMillis();
        logger.debug("The time cost for request\"" + uuid + "\" is " + (end - begin));
    }
}

From source file:com.st.qunar.order.web.order.OrderController.java

@RequestMapping(value = "allExport")
public void allExport(@RequestParam String key, HttpServletResponse resp) throws IOException {
    resp.setCharacterEncoding("UTF-8");
    PrintWriter pw = resp.getWriter();
    if (key.equalsIgnoreCase("kxhu")) {
        orderExportService.allExport();//from w  ww  . ja va  2 s.  c  o  m
        pw.write("allexport");
    } else {
        pw.write("error key all export");
    }
    pw.close();
}

From source file:com.ctb.prism.report.api.CustomViewerServlet.java

/**
 *
 *///ww w. j  ava  2 s  . c  o  m
public void render(HttpServletRequest request, WebReportContext webReportContext, PrintWriter writer) {

    writer.write(getHeader(request, webReportContext));
    writer.write(getBody(request, webReportContext));
    writer.write(getFooter());
}

From source file:com.eternity.common.communication.servlet.SyncDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;//  w w  w  .j av  a2  s  .c  o  m

    if (charset == null) {
        charset = "UTF-8";
    }

    contentType += ";" + charset;

    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        log.warn("Received request with invalid content type of: {} (derived: {})", req.getContentType(),
                contentType);
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim() + ";" + charset);
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.println("{\"status\": 400, \"errors\": [\"Unacceptable or missing ACCEPT header!\"]}");
        log.warn(
                "Cannot return data in formats: {}  - if you think this is wrong please check character encodings.",
                acceptsHeader);
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    if (message.subsystemName == null) {
        message.subsystemName = req.getRequestURL().toString().replaceFirst(".*/([^/?]+).*", "$1");
    }
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    Response result = MessageConsumer.dispatchMessage(message, null, hostName);
    resp.setStatus(result.getStatus());
    resp.getOutputStream().write(result.data.array());
}