Example usage for java.io PrintWriter flush

List of usage examples for java.io PrintWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:com.fengduo.bee.commons.component.ComponentController.java

@ExceptionHandler(Throwable.class)
public ModelAndView handleIOException(Throwable e) throws Throwable {

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;/* ww  w. ja v a2 s .  c o m*/
    }

    if (request == null && response == null) {
        throw e;
    }

    if (request == null && response != null) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        pw.println("{\"code\":1,\"msg\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    // if (InvokeTypeTools.isAjax(request)) {
    // return createJsonMav("server exceptin or error", ResultCode.ERROR,
    // e.getMessage());
    // }

    mav.addObject("exception", e.getCause() == null ? StringUtils.EMPTY : e.getCause().toString());
    mav.addObject("msg", StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage());
    mav.addObject("stackTrace", e.getStackTrace().toString());
    if (request.getRequestURI() != null) {
        mav.addObject("url", request.getRequestURI().toString());
    }
    mav.setViewName("error");
    return mav;
}

From source file:com.liferay.arquillian.DeployerServlet.java

private void signalError(Throwable t, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    try {//from   w  ww  .  j  ava 2  s  . c o m
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType(StringPool.UTF8);

        PrintWriter printWriter = new PrintWriter(outputStream);

        t.printStackTrace(printWriter);

        printWriter.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mockey.ui.ServiceMergeServlet.java

/**
 * /* w w w. j  av  a2s .co  m*/
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Boolean originalMode = store.getReadOnlyMode();
    store.setReadOnlyMode(true);

    String[] serviceMergeIdList = req.getParameterValues("serviceIdMergeSource[]");
    Enumeration<String> names = (Enumeration<String>) req.getParameterNames();
    while (names.hasMoreElements()) {
        log.debug(names.nextElement());
    }
    Long serviceIdMergeSource = null;
    Long serviceIdMergeDestination = null;
    ServiceMergeResults mergeResults = null;
    Map<String, String> responseMap = new HashMap<String, String>();
    try {
        for (int i = 0; i < serviceMergeIdList.length; i++) {

            serviceIdMergeSource = new Long(serviceMergeIdList[i]);
            serviceIdMergeDestination = new Long(req.getParameter("serviceIdMergeDestination"));
            if (!serviceIdMergeSource.equals(serviceIdMergeDestination)) {

                Service serviceMergeSource = store.getServiceById(serviceIdMergeSource);
                Service serviceMergeDestination = store.getServiceById(serviceIdMergeDestination);
                MockeyXmlFileManager configurationReader = new MockeyXmlFileManager();
                mergeResults = configurationReader.mergeServices(serviceMergeSource, serviceMergeDestination,
                        mergeResults, null);

            }
            responseMap.put("additions", mergeResults.getAdditionMsg());
            responseMap.put("conflicts", mergeResults.getConflictMsg());
        }

    } catch (Exception e) {
        // Do nothing
        log.error("Something wrong with merging services.", e);
        responseMap.put("conflicts",
                "Unable to merge services. The services selected may be missing or contain bad data. Sorry about this.");

    }

    // IF NO CONFLICTS, THEN DELETE OLD SOURCE SERVICES
    if (mergeResults != null
            && (mergeResults.getConflictMsgs() == null || mergeResults.getConflictMsgs().isEmpty())) {
        for (int i = 0; i < serviceMergeIdList.length; i++) {
            serviceIdMergeSource = new Long(serviceMergeIdList[i]);
            Service service = store.getServiceById(serviceIdMergeSource);
            store.deleteService(service);
        }

    }
    resp.setContentType("application/json");
    PrintWriter out = resp.getWriter();

    String resultingJSON = Util.getJSON(responseMap);
    out.println(resultingJSON);

    out.flush();
    out.close();
    store.setReadOnlyMode(originalMode);
    return;
    // AJAX thing. Return nothing at this time.
}

From source file:cn.vlabs.umt.ui.actions.CreateRequestAction.java

/**
 * ????//from w ww.  ja  v a  2s. com
 * */
public ActionForward usercheck(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    response.setContentType("json");
    PrintWriter writer = response.getWriter();
    writer.println(!getUserService().isUsed(request.getParameter("username")));
    writer.flush();
    writer.close();
    return null;
}

From source file:io.github.azagniotov.stubby4j.cli.CommandLineInterpreter.java

/**
 * Prints current stubby4j version to the console
 *//*  w ww  .  j a v  a 2 s  .c o  m*/
@CoberturaIgnore
public void printVersion() {
    final HelpFormatter formatter = new HelpFormatter();
    PrintWriter pw = new PrintWriter(System.out);
    formatter.printWrapped(pw, HelpFormatter.DEFAULT_WIDTH, JarUtils.readManifestImplementationVersion());
    pw.flush();
}

From source file:io.milton.cloud.server.web.templating.TextTemplater.java

@Override
public void writePage(String templatePath, Resource aThis, Map<String, String> params, OutputStream out)
        throws IOException {
    if (!templatePath.startsWith("/")) {
        templatePath = "/templates/apps/" + templatePath;
    }//from  w  w w.  j  av a2  s.co  m
    Template template = engine.getTemplate(templatePath);
    RootFolder rootFolder = WebUtils.findRootFolder(aThis);
    Context datamodel = new VelocityContext();
    datamodel.put("rootFolder", rootFolder);
    datamodel.put("page", aThis);
    datamodel.put("params", params);
    Profile user = securityManager.getCurrentUser();
    if (user != null) {
        datamodel.put("user", user);
    }
    PrintWriter pw = new PrintWriter(out);
    template.merge(datamodel, pw);
    pw.flush();
}

From source file:de.mpg.imeji.presentation.servlet.autocompleter.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w w  w .j a  va 2s. c  o  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String suggest = request.getParameter("searchkeyword");
    String datasource = request.getParameter("datasource");
    String responseString = "";
    if (suggest.isEmpty()) {
        suggest = "a";
    } else if (datasource != null && !datasource.isEmpty()) {
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(datasource + URLEncoder.encode(suggest.toString(), "UTF-8"));
        try {
            client.executeMethod(getMethod);
            responseString = new String(StorageUtils.toBytes(getMethod.getResponseBodyAsStream()), "UTF-8");
            if (datasource != null && responseString != null)
                responseString = passResult(responseString, datasource);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getMethod.releaseConnection();
        }
    }
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.print(responseString);
    out.flush();
    out.close();
}

From source file:com.assignment.elance.controller.FileUploadServlet.java

/**
 * Upon receiving file upload submission, parses the request to read upload
 * data and saves the file on disk.//from w  ww .  j  ava  2s.  c  o  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk 
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator
            + SystemAttributes.UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String file = randomFileNameGenerator();
                    String filePath = uploadPath + File.separator + file;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    FilesManager fm = new FilesManager();
                    boolean send_dir = false;
                    switch (Integer.parseInt(request.getParameter("senddir"))) {
                    case 0:
                        send_dir = false;
                        break;
                    case 1:
                        send_dir = true;
                        break;
                    }
                    fm.insert(fileName, file, Integer.parseInt(request.getParameter("jobId")), send_dir);
                    request.setAttribute("message", "Upload has been done successfully!");
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    //        // redirects client to message page
    //        getServletContext().getRequestDispatcher("/message.jsp").forward(
    //                request, response);
    switch (Integer.parseInt(request.getParameter("callbackpage"))) {
    case 0:
        response.sendRedirect("projectOverview.jsp?pId=" + Integer.parseInt(request.getParameter("jobId")));
        break;
    case 1:
        response.sendRedirect("project.jsp?jobId=" + Integer.parseInt(request.getParameter("jobId")));
        break;

    }
}

From source file:es.itecban.deployment.executionmanager.web.view.ReportView.java

public void render(Map model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    PrintWriter out = resp.getWriter();

    resp.setContentType("application/octet-stream");

    ExecutionReportType report = (ExecutionReportType) model.get("report");
    //      report.getTechnicalExecutionReport();
    out.print(report.getTechnicalExecutionReport());
    out.flush();
    out.close();//from   w  w w  . j a v a2  s. com

}

From source file:com.ss.Controller.T4uApproveRefundServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w .j  a  v a 2s. co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser);
    if (!user.getUserGroup().equals("officer")) // Not authorised, only user himself can cancel order
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not authorised");
    else
        try {
            long orderId = Long.parseLong(request.getParameter("orderId"));
            T4uOrder order = T4uOrderDAO.getOrderById(orderId);
            if (order.getOrderStatus() == 2) { // Current status is Pending
                T4uOrderDAO.changeOrderStatus(orderId, 3, user);
                T4uOrder t4uOrder = new T4uOrder();
                t4uOrder.setOrderId(orderId);
                String json = new Gson().toJson(t4uOrder);
                response.setContentType("application/json");
                // Get the printwriter object from response to write the required json object to the output stream      
                PrintWriter out = response.getWriter();
                // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
                out.print(json);
                out.flush();
            } else // Not pending status
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad order status");
        } catch (NumberFormatException ex) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "NumberFormatException");
        }
}