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.amazon.alexa.avs.FileDataStore.java

public synchronized void writeToDisk(T payload, final ResultListener<T> listener) {
    sExecutor.execute(new Runnable() {
        @Override//w  w w .  j  a  v a2 s .  c  om
        public void run() {
            ObjectWriter writer = ObjectMapperFactory.getObjectWriter();
            PrintWriter out = null;
            try {
                out = new PrintWriter(file);
                out.print(writer.writeValueAsString(payload));
                out.flush();
                listener.onSuccess(payload);
            } catch (IOException e) {
                log.error("Failed to write to disk", e);
                listener.onFailure();
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    });
}

From source file:io.apiman.manager.test.server.MockGatewayServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  ww .j a  va 2  s.co  m
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    builder.append("GET:").append(req.getRequestURI()).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
    payloads.add(null);
    if (req.getRequestURI().endsWith("/system/status")) { //$NON-NLS-1$
        resp.setStatus(200);
        resp.setContentType("application/json"); //$NON-NLS-1$
        PrintWriter printWriter = new PrintWriter(resp.getOutputStream());
        printWriter.println("{ \"up\" : true, \"version\" : \"1.0.Mock\" }"); //$NON-NLS-1$
        printWriter.flush();
        printWriter.close();
    } else {
        resp.setStatus(204);
    }
}

From source file:com.bitranger.parknshop.seller.controller.SellerPublishProductCtrl.java

@RequestMapping(value = "/seller/getTag", method = RequestMethod.GET)
public void getTags(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // get the categoryId
    String categoryId = request.getParameter("id");

    List<PsTag> tags = tagDAO.selectTopTags(Integer.parseInt(categoryId.trim()), 20);

    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setIgnoreDefaultExcludes(false);
    jsonConfig.setExcludes(new String[] { "psItems" });

    JSONArray jsonArray = JSONArray.fromObject(tags, jsonConfig);

    PrintWriter out = response.getWriter();

    out.write(jsonArray.toString());/*from  w w w .ja v a 2 s.  co m*/
    out.flush();
    out.close();

}

From source file:com.bstek.dorado.web.resolver.ErrorPageResolver.java

private void doExcecute(HttpServletRequest request, HttpServletResponse response)
        throws Exception, IOException {
    response.setContentType(HttpConstants.CONTENT_TYPE_HTML);
    response.setCharacterEncoding(Constants.DEFAULT_CHARSET);

    Context velocityContext = new VelocityContext();
    Exception e = (Exception) request.getAttribute(EXCEPTION_ATTRIBUTE);
    if (e != null) {
        logger.error(e, e);/* ww w. j  a va  2 s. c  o  m*/

        if (e instanceof PageNotFoundException) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (e instanceof PageAccessDeniedException) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }

        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
        }

        String message = null;
        if (throwable != null) {
            message = throwable.getMessage();
        }
        message = StringUtils.defaultString(message, throwable.getClass().getName());

        velocityContext.put("message", message);
        velocityContext.put(EXCEPTION_ATTRIBUTE, throwable);
    } else {
        velocityContext.put("message", "Can not gain exception information!");
    }
    velocityContext.put("esc", stringEscapeHelper);

    Template template = getVelocityEngine().getTemplate("com/bstek/dorado/web/resolver/ErrorPage.html");

    PrintWriter writer = getWriter(request, response);
    try {
        template.merge(velocityContext, writer);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:controller.UploadServlet.java

@Override
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;/* w  ww  . j  av a  2s . co m*/
    }
    // 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 + UPLOAD_DIRECTORY;

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

    try {

        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 filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName);
                    request.setAttribute("message",
                            "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName);
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    // redirects client to message page
    getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//from www .j  av a 2  s  .com
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1.java

private PrintWriter writeAuthentication() {
    PrintWriter output = new PrintWriter(out);
    output.println(password);/*w  ww.j  a va2  s. co m*/
    output.flush();
    return output;
}

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

protected void pageUpdate(HttpServletRequest request, HttpServletResponse response,
        WebReportContext webReportContext) throws JRException, IOException {
    JasperPrintAccessor jasperPrintAccessor = (JasperPrintAccessor) webReportContext
            .getParameterValue(WebReportContext.REPORT_CONTEXT_PARAMETER_JASPER_PRINT_ACCESSOR);
    if (jasperPrintAccessor == null) {
        throw new JRRuntimeException("Did not find the report on the session.");
    }//w w w  . j  a  va 2s.  c om

    String pageIdxParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE);
    Integer pageIndex = pageIdxParam == null ? null : Integer.valueOf(pageIdxParam);
    String pageTimestampParam = request.getParameter(WebUtil.REQUEST_PARAMETER_PAGE_TIMESTAMP);
    Long pageTimestamp = pageTimestampParam == null ? null : Long.valueOf(pageTimestampParam);

    if (log.isDebugEnabled()) {
        log.debug("report page update check for pageIndex: " + pageIndex + ", pageTimestamp: " + pageTimestamp);
    }

    Map<String, Object> reportStatus = new LinkedHashMap<String, Object>();
    putReportStatusResult(response, jasperPrintAccessor, reportStatus);

    if (pageIndex != null && pageTimestamp != null) {
        ReportPageStatus pageStatus = jasperPrintAccessor.pageStatus(pageIndex, pageTimestamp);
        boolean modified = pageStatus.hasModified();
        reportStatus.put("pageModified", modified);
        reportStatus.put("pageFinal", pageStatus.isPageFinal());

        if (log.isDebugEnabled()) {
            log.debug("page " + pageIndex + " modified " + modified);
        }
    }

    Map<String, Object> result = new HashMap<String, Object>();
    result.put("result", reportStatus);

    String resultString = JacksonUtil.getInstance(getJasperReportsContext()).getJsonString(result);
    PrintWriter out = response.getWriter();
    out.write(resultString);
    out.flush();
}

From source file:LoginClient.java

public LoginClient() {
    try {/*from   w  w  w . j ava2  s  . c o m*/
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", 7070);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        String userName = "MyName";
        output.println(userName);
        String password = "MyPass";
        output.println(password);
        output.flush();
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String response = input.readLine();
        System.out.println(response);

        output.close();
        input.close();
        socket.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        System.exit(0);
    }
}

From source file:bookUtilities.BookSearchServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w.  j a  va2 s.  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 {
    response.setContentType("text/html;charset=UTF-8");
    JSONArray books = getSearchResults(request.getParameter("searchPhrase"));
    PrintWriter printout = response.getWriter();
    printout.print(books);
    printout.flush();
}