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.bstek.dorado.view.registry.AbstractVelocityResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isBlank(pageTemplate)) {
        throw new IllegalArgumentException("'pageTemplate' undefined.");
    }//from   ww w.  j a  v a 2 s .  c  o  m

    org.apache.velocity.context.Context velocityContext = velocityHelper.getContext(null, request, response);
    initVelocityContext(velocityContext, request, response);

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

From source file:Employee.CreateMailingList.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request// w w  w.  ja va 2 s . co m
 * @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 jsonArray = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "SELECT P.SSN, P.FirstName, P.LastName, P.Email "
                + "FROM [MatchesFromAbove].[dbo].[Person] P, [MatchesFromAbove].[dbo].[Customer] C"
                + " WHERE C.Active = 'true' AND P.SSN = C.SSN";

        ResultSet rs = st.executeQuery(query);
        //loop through result set and create the json objects
        while (rs.next()) {
            JSONObject emailToAdd = new JSONObject();
            emailToAdd.put("ssn", rs.getString("SSN"));
            emailToAdd.put("firstName", rs.getString("FirstName"));
            emailToAdd.put("lastName", rs.getString("LastName"));
            emailToAdd.put("email", rs.getString("Email"));
            //add the json object that we're passing into the json array
            jsonArray.add(emailToAdd);
        }
        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        PrintWriter printout = response.getWriter();
        printout.print(jsonArray);
        printout.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:net.openhft.chronicle.queue.ChronicleHistoryReaderMain.java

protected void printUsageAndExit(final Options options) {
    final PrintWriter writer = new PrintWriter(System.out);
    new HelpFormatter().printUsage(writer, 180, ChronicleHistoryReaderMain.class.getSimpleName(), options);
    writer.flush();
    System.exit(1);/*  w w  w.  j a v  a2s .  c  om*/
}

From source file:net.psexton.authzwriter.Main.java

/**
 * Given a String body and a file path, writes fileBody to filePath
 * @param fileBody/*w w w.  jav a 2 s .c  o m*/
 * @param filePath 
 */
private void writeToFile(String fileBody, String filePath) {
    File file = new File(filePath);
    try {
        PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        writer.print(fileBody);
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:Employee.getAllCustomers.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w w .j ava  2s  .  c  o 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 {
    //json to pass back to our ajax request
    JSONArray jsonArray = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "SELECT * FROM [MatchesFromAbove].[dbo].[Customer] WHERE active=1";

        ResultSet rs = st.executeQuery(query);

        //loop through result set and create the json objects
        while (rs.next()) {
            JSONObject customerToAdd = new JSONObject();
            customerToAdd.put("ssn", rs.getString("SSN"));
            customerToAdd.put("ppp", rs.getString("PPP"));
            customerToAdd.put("rating", rs.getInt("Rating"));
            customerToAdd.put("lastActiveDate", rs.getTimestamp("LastActive").toString());
            //add the json object that we're passing into the json array
            jsonArray.add(customerToAdd);
        }
        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        PrintWriter printout = response.getWriter();
        printout.print(jsonArray);
        printout.flush();
        con.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:bookUtilities.PopulateMyBooksServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from w w  w.j  ava 2  s  .  c om*/
 * @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");
    String email;
    email = (String) request.getSession().getAttribute("email");
    JSONArray fileTypes = new JSONArray();
    JSONArray userBooks = getUserBooks(email, fileTypes);
    JSONArray infoToPush = new JSONArray();
    infoToPush.add(userBooks);
    infoToPush.add(fileTypes);
    PrintWriter printout = response.getWriter();
    printout.print(infoToPush);
    printout.flush();
}

From source file:com.exzogeni.dk.log.formatter.SimpleLogFormatter.java

@Override
public String format(@NonNull Thread thread, @NonNull StackTraceElement caller, @NonNull Throwable e) {
    final StringBuilder message = newMessageBuilder(thread, caller);
    final StringWriter trace = new StringWriter();
    final PrintWriter traceWriter = new PrintWriter(new BufferedWriter(trace, 512), true);
    try {/*w  w w .j a  va  2  s  .  c  o  m*/
        e.printStackTrace(traceWriter);
    } finally {
        traceWriter.flush();
        IOUtils.closeQuietly(traceWriter);
    }
    return message.append(trace.toString()).toString();
}

From source file:com.amazonaws.mturk.cmd.AssignQualification.java

protected void printHelp() {
    log.info(AssignQualification.class.getName() + " -" + ARG_QUALTYPE + " [qual to grant] " + " -"
            + ARG_WORKERID + " [worker to be granted]" + " -" + ARG_SCORE + " [value to grant]");
    log.info("Or");
    log.info(AssignQualification.class.getName() + " -" + ARG_INPUT_FILE
            + " [ input file containing Qualification Type] " + " -" + ARG_SCORE_FILE + " [ score file ] "
            + " -" + ARG_SCORE + " [value to grant]");

    PrintWriter pw = new PrintWriter(System.out);
    formatter.printOptions(pw, formatter.defaultWidth, opt, formatter.defaultLeftPad, formatter.defaultDescPad);
    pw.flush();
}

From source file:com.controlj.green.istat.web.StatServlet.java

public void writeStats(final ServletOutputStream out, final String location, HttpServletRequest req)
        throws IOException, SystemException, ActionExecutionException, InvalidConnectionRequestException {
    final JSONArray arrayData = new JSONArray();

    SystemConnection connection = DirectAccess.getDirectAccess().getUserSystemConnection(req);

    connection.runReadAction(FieldAccessFactory.newFieldAccess(), new ReadAction() {
        public void execute(@NotNull SystemAccess access) throws Exception {
            Location eqLoc = access.getGeoRoot().getTree().resolve(location);
            Collection<SetPoint> setPoints = eqLoc.find(SetPoint.class, Acceptors.acceptAll());
            if (setPoints.isEmpty()) {
                throw new Exception("Invalid location, no SetPoints here: " + location);
            }/*  www. ja  v a 2 s . co  m*/
            Collection<SetPointAdjust> setPointAdjusts = eqLoc.find(SetPointAdjust.class,
                    Acceptors.acceptAll());
            if (setPointAdjusts.isEmpty()) {
                throw new Exception("Invalid location, no SetPointAdjusts here: " + location);
            }

            SetPoint setPoint = setPoints.iterator().next();
            SetPointAdjust setPointAdjust = setPointAdjusts.iterator().next();
            JSONObject next = new JSONObject();

            next.put("hsp", nFormat.format(setPoint.getEffectiveHeating()));
            next.put("csp", nFormat.format(setPoint.getEffectiveCooling()));
            next.put("current", nFormat.format(setPoint.getZoneTemp()));
            next.put("off", nFormat.format(setPointAdjust.getCoolingSetpointAdjust().getValue()));
            next.put("lim", nFormat.format(setPointAdjust.getCoolingSetpointAdjust().getMaximum()));
            next.put("loc", location);
            next.put("adjustable", setPointAdjust.getCoolingSetpointAdjust().isWritable());
            arrayData.put(next);
        }
    });

    try {
        PrintWriter writer = new PrintWriter(out);
        arrayData.write(writer);
        writer.flush();
    } catch (JSONException e) {
        Logging.LOGGER.println("Unexpected exception:");
        e.printStackTrace(Logging.LOGGER);
    }
}

From source file:cc.kune.core.server.rack.filters.rest.RESTServiceFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final String methodName = RackHelper.getMethodName(request, pattern);
    final ParametersAdapter parameters = new ParametersAdapter(request);
    LOG.debug("JSON METHOD: '" + methodName + "' on: " + serviceClass.getSimpleName());

    response.setCharacterEncoding("utf-8");

    final String callbackMethod = getCallbackMethod(request);
    final boolean isJsonP = isJSONPRequest(callbackMethod);

    response.setContentType(isJsonP ? "text/javascript" : "text/json");

    final RESTResult result = transactionalFilter.doService(serviceClass, methodName, parameters,
            getInstance(serviceClass));/*from  w ww.  j a v a 2s .  com*/
    if (result != null) {
        if (result.getOutput() != null) {
            final Object output = wrap(result.getOutput(), isJsonP, callbackMethod);
            if (output != null) {
                final PrintWriter writer = response.getWriter();
                writer.print(output);
                writer.flush();
            } else {
                chain.doFilter(request, response);
            }

        } else {
            chain.doFilter(request, response);
        }
    }
}