Example usage for javax.servlet ServletOutputStream print

List of usage examples for javax.servlet ServletOutputStream print

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream print.

Prototype


public void print(double d) throws IOException 

Source Link

Document

Writes a double value to the client, with no carriage return-line feed (CRLF) at the end.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.grefine.GrefineMqlreadServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doGet(req, resp);
    resp.setContentType("application/json");
    VitroRequest vreq = new VitroRequest(req);
    try {//from  w  w w. j a v a2  s  .  c o  m
        if (vreq.getParameter("query") != null) {

            JSONObject qJson = getResult(vreq, req, resp);
            log.debug("result: " + qJson.toString());
            String responseStr = (vreq.getParameter("callback") == null) ? qJson.toString()
                    : vreq.getParameter("callback") + "(" + qJson.toString() + ")";
            // System.out.println(responseStr);
            ServletOutputStream out = resp.getOutputStream();
            out.print(responseStr);
        }

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

From source file:com.alibaba.dubbo.governance.web.home.module.screen.Restful.java

public void execute(Map<String, Object> context) throws Exception {
    Result result = new Result();
    if (request.getParameter("url") != null) {
        url = URL.valueOf(URL.decode(request.getParameter("url")));
    }/*from  ww  w.j a v  a 2s .  c o  m*/
    if (context.get(WebConstants.CURRENT_USER_KEY) != null) {
        User user = (User) context.get(WebConstants.CURRENT_USER_KEY);
        currentUser = user;
        operator = user.getUsername();
        role = user.getRole();
        context.put(WebConstants.CURRENT_USER_KEY, user);
    }
    operatorAddress = (String) context.get("clientid");
    if (operatorAddress == null || operatorAddress.isEmpty()) {
        operatorAddress = (String) context.get("request.remoteHost");
    }
    context.put("operator", operator);
    context.put("operatorAddress", operatorAddress);
    String jsonResult = null;
    try {
        result = doExecute(context);
        result.setStatus("OK");
    } catch (IllegalArgumentException t) {
        result.setStatus("ERROR");
        result.setCode(3);
        result.setMessage(t.getMessage());
    }
    //        catch (InvalidRequestException t) {
    //            result.setStatus("ERROR");
    //            result.setCode(2);
    //            result.setMessage(t.getMessage());
    //        }
    catch (Throwable t) {
        result.setStatus("ERROR");
        result.setCode(1);
        result.setMessage(t.getMessage());
    }
    response.setContentType("application/javascript");
    ServletOutputStream os = response.getOutputStream();
    try {
        jsonResult = JSON.toJSONString(result);
        os.print(jsonResult);
    } catch (Exception e) {
        response.setStatus(500);
        os.print(e.getMessage());
    } finally {
        os.flush();
    }
}

From source file:com.controlj.green.bulktrend.trendserver.SearchServlet.java

private void writeRawCell(ServletOutputStream out, String cssClass, String content) throws IOException {
    out.print("      <td class='" + cssClass + "'>");
    out.print(content);//from   w ww  .jav a 2 s  . c  o m
    out.println("      </td>");

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java

public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final String host = HostAccessControl.getRemoteAddress(request);
    final String ip = request.getRemoteAddr();
    final String password = request.getParameter("password");
    final String userUId = request.getParameter("userUId");
    final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8");

    String message = "ko";

    try {// ww w .j  av  a 2 s  . c o m

        SetEmail.run(host, ip, password, userUId, email);
        final User user = User.findByUsername(userUId);
        if (user.getPerson() != null && user.getPerson().getStudent() != null) {
            final Student student = user.getPerson().getStudent();
            for (final Registration registration : student.getRegistrationsSet()) {
                final StudentCandidacy candidacy = registration.getStudentCandidacy();
                if (candidacy != null
                        && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy)
                        && candidacy.getExecutionYear().isCurrent()
                        && !candidacy.getCandidacySituationsSet().isEmpty()) {
                    new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(),
                            request.getServerPort(), request.getContextPath(), request.getServletPath())
                                    .start();
                }
            }
        }
        message = "ok";
    } catch (NotAuthorizedException ex) {
        message = "Not authorized";
    } catch (UserAlreadyHasEmailException ex) {
        message = "User already has email.";
    } catch (UserDoesNotExistException ex) {
        message = "User does not exist.";
    } catch (Throwable ex) {
        message = ex.getMessage();
        logger.error(ex.getMessage(), ex);
    } finally {
        final ServletOutputStream servletOutputStream = response.getOutputStream();
        response.setContentType("text/html");
        servletOutputStream.print(message);
        servletOutputStream.flush();
        response.flushBuffer();
    }

    return null;
}

From source file:org.wso2.sample.identity.oauth2.IDTokenDecrypterServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String idToken = request.getParameter("idToken");
    String privateKeyString = request.getParameter("privateKeyString");

    ServletOutputStream out = response.getOutputStream();

    if (StringUtils.isBlank(privateKeyString)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        out.print("Client private key cannot be empty!");
    } else if (StringUtils.isBlank(idToken)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        out.print("Error occurred while decrypting: Empty id token received!");
    } else {/* w  ww  . java2s .c  o  m*/
        response.setContentType("application/json");

        EncryptedJWT encryptedJWT;
        try {
            encryptedJWT = decryptJWE(idToken, privateKeyString);
            JSONObject outJSON = new JSONObject();
            JSONObject claimsJSON = new JSONObject();

            // Get all claims set to a map and return a JSON object.
            Map<String, Object> allClaims = encryptedJWT.getJWTClaimsSet().getAllClaims();
            for (Map.Entry<String, Object> entry : allClaims.entrySet()) {
                claimsJSON.put(entry.getKey(), entry.getValue());
            }
            outJSON.put("claims", claimsJSON);

            // Get JWT header data.
            outJSON.put("header", encryptedJWT.getHeader().toJSONObject());

            out.print(outJSON.toString());
        } catch (NoSuchAlgorithmException | ParseException | JOSEException | IllegalArgumentException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            out.print("Error occurred while decrypting id token.");
        } catch (InvalidKeySpecException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            out.print("Invalid client private key.");
        }
    }
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

public static void callCtl(String class_method) throws RuntimeException {
    try {//from   w  ww  .j  a  v  a 2s .com
        HttpServletRequest req = ActionContext.getReq();
        HttpServletResponse resp = ActionContext.getResp();
        if (StringUtils.isNotBlank(class_method)) {
            Cache cache = SshConstant.CACHE_MAP.get(class_method);
            if (null != cache && !SshConstant.DEBUG_MODE) {
                // long begin = System.currentTimeMillis();
                cache.getMethod().invoke(cache.getObject(), req, resp);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            } else {
                // long begin = System.currentTimeMillis();
                int lastIndex = class_method.lastIndexOf(".");
                String clazzTemp = class_method.substring(0, lastIndex);
                // 
                Class<?> ctlClazz = null;
                for (String packageName : SshConstant.PACKAGE_NAME) {
                    try {
                        String clazz = (clazzTemp.indexOf(".") == clazzTemp.lastIndexOf("."))
                                ? (packageName + "." + clazzTemp)
                                : clazzTemp;
                        ctlClazz = Class.forName(clazz);
                    } catch (Exception e) {
                    }
                    if (ctlClazz != null)
                        break;
                }
                Object ctlObj = ctlClazz.newInstance();
                String method = class_method.substring(++lastIndex);
                // Method ctlMet = ctlClazz.getMethod(method,
                // HttpServletRequest.class, HttpServletResponse.class);
                Method ctlMet = ctlClazz.getMethod(method);
                SshConstant.CACHE_MAP.put(class_method, new Cache(ctlObj, ctlMet));// put
                // cache

                // ctlMet.invoke(ctlObj, req, resp);
                ctlMet.invoke(ctlObj);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            }
        } else {
            ServletOutputStream out = resp.getOutputStream();
            out.print("error");
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.enterprise.gui.coregui.server.gwt.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession();
    session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL);

    if (ServletFileUpload.isMultipartContent(req)) {

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        //fileItemFactory.setSizeThreshold(0);

        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        List<FileItem> fileItemsList;
        try {/*www .  j a  va2s  .  c  o m*/
            fileItemsList = (List<FileItem>) servletFileUpload.parseRequest(req);
        } catch (FileUploadException e) {
            writeExceptionResponse(resp, "File upload failed", e);
            return;
        }

        List<FileItem> actualFiles = new ArrayList<FileItem>();
        Map<String, String> formFields = new HashMap<String, String>();
        boolean retrieve = false;
        Subject authenticatedSubject = null;

        for (FileItem fileItem : fileItemsList) {
            if (fileItem.isFormField()) {
                if (fileItem.getFieldName() != null) {
                    formFields.put(fileItem.getFieldName(), fileItem.getString());
                }
                if ("retrieve".equals(fileItem.getFieldName())) {
                    retrieve = true;
                } else if ("sessionid".equals(fileItem.getFieldName())) {
                    int sessionid = Integer.parseInt(fileItem.getString());
                    SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager();
                    try {
                        authenticatedSubject = subjectManager.getSubjectBySessionId(sessionid);
                    } catch (Exception e) {
                        throw new ServletException("Cannot authenticate request", e);
                    }
                }
                fileItem.delete();
            } else {
                // file item contains an actual uploaded file
                actualFiles.add(fileItem);
                log("file was uploaded: " + fileItem.getName());
            }
        }

        if (authenticatedSubject == null) {
            for (FileItem fileItem : actualFiles) {
                fileItem.delete();
            }
            throw new ServletException("Cannot process unauthenticated request");
        }

        if (retrieve && actualFiles.size() == 1) {
            // sending in "retrieve" form element with a single file means the client just wants the content echoed back
            FileItem fileItem = actualFiles.get(0);

            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.print("<html>");
            InputStream inputStream = fileItem.getInputStream();
            try {
                StreamUtil.copy(inputStream, outputStream, false);
            } finally {
                inputStream.close();
            }
            outputStream.print("</html>");
            outputStream.flush();

            fileItem.delete();
        } else {
            Map<String, File> allUploadedFiles = new HashMap<String, File>(); // maps form field name to the actual file
            Map<String, String> allUploadedFileNames = new HashMap<String, String>(); // maps form field name to upload file name
            for (FileItem fileItem : actualFiles) {
                File theFile = forceToFile(fileItem);
                allUploadedFiles.put(fileItem.getFieldName(), theFile);
                allUploadedFileNames.put(fileItem.getFieldName(),
                        (fileItem.getName() != null) ? fileItem.getName() : theFile.getName());
            }
            processUploadedFiles(authenticatedSubject, allUploadedFiles, allUploadedFileNames, formFields, req,
                    resp);
        }
    }
}

From source file:org.apache.myfaces.trinidaddemo.webapp.SourceCodeServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    String webPage = req.getServletPath();

    // remove the '*.source' suffix that maps to this servlet
    int source = webPage.indexOf(".source");
    webPage = webPage.substring(0, source);

    //remove "/faces" mapping
    webPage = StringUtils.remove(webPage, "/faces");

    // get the actual file location of the requested resource
    String realPath = getServletConfig().getServletContext().getRealPath(webPage);

    // output an HTML page
    res.setContentType("text/plain");

    // print some html
    ServletOutputStream out = res.getOutputStream();

    // print the file
    InputStream in = null;/* w w  w .  j a  v  a  2s  . co  m*/
    try {
        in = new BufferedInputStream(new FileInputStream(realPath));
        int ch;
        while ((ch = in.read()) != -1) {
            out.print((char) ch);
        }
    } finally {
        if (in != null)
            in.close(); // very important
    }
}

From source file:com.chaosinmotion.securechat.server.DeviceServlet.java

/**
 * Handle POST commands. This uses the cookie mechanism for Java
 * servlets to track users for security reasons, and handles the
 * commands for getting a token, for verifying server status, and for
 * logging in and changing a password./* w  w  w  .java  2  s.c o m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ReturnResult retVal = null;

    /*
     * Step 1: determine the path element after the api/1/ URL. This
     * determines the command
     */

    String path = req.getPathInfo();
    if (path == null) {
        resp.sendError(404);
        return;
    }
    if (path.startsWith("/"))
        path = path.substring(1);

    try {
        /*
         * All commands require authentication. This determines if we have
         * it or not.
         */
        HttpSession session = req.getSession();
        Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo");
        if (userinfo == null) {
            retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized");
        } else {

            if (path.equalsIgnoreCase("adddevice")) {
                /*
                 * Process the adddevice request. This adds a new device
                 * to this user's list of device. We are basically a 
                 * key escrow system with each user associated with a 
                 * list of devices (by id) and their public keys.
                 * 
                 * This is a potential weak point in the protocol in that
                 * a bad guy could theoretically add his own device to
                 * this account. But to do so he'd have to have the
                 * username and password for this user, and the fact that
                 * there were multiple devices associated with this
                 * account would be effectively broadcast to all senders.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                if (AddDevice.processRequest(userinfo, requestParams)) {
                    retVal = new ReturnResult();
                } else {
                    retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error");
                }

            } else if (path.equalsIgnoreCase("removedevice")) {
                /*
                 * Process the removedevice request. This removes the
                 * device (by its device ID) from the list of devices
                 * associated with the user.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                if (RemoveDevice.processRequest(userinfo, requestParams)) {
                    retVal = new ReturnResult();
                } else {
                    retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error");
                }

            } else if (path.equalsIgnoreCase("devices")) {
                /*
                 * Process the devices request, which, for a given username
                 * returns an array of devices (device ID and public key)
                 * associated with the user. This allows each sender to
                 * know the devices to encrypt messages for.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = Devices.processRequest(userinfo, requestParams);
            }
        }
    } catch (Throwable th) {
        retVal = new ReturnResult(th);
    }

    /*
     * If we get here and we still haven't initialized return value,
     * set to a 404 error. We assume this reaches here with a null
     * value because the path doesn't exist.
     */

    if (retVal == null) {
        resp.sendError(404);

    } else {
        /*
         * We now have a return result. Formulate the response
         */

        ServletOutputStream stream = resp.getOutputStream();
        resp.setContentType("application/json");
        stream.print(retVal.toString());
    }
}

From source file:org.sakaiproject.kernel.rest.RestMySitesProvider.java

/**
 * @param response//from  w  ww  . j  a  v a  2 s.  c  o  m
 * @param itemMap
 * @throws IOException
 */
private void sendOutput(HttpServletResponse response, Map<String, Object> itemMap) throws IOException {
    response.setContentType(RestProvider.CONTENT_TYPE);
    ServletOutputStream outputStream = response.getOutputStream();

    outputStream.print(beanConverter.convertToString(itemMap));

    outputStream.flush();
    outputStream.close();

}