Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:com.cyclopsgroup.waterview.servlet.WaterviewServlet.java

/**
 * Do handle exception/*from  w  w w.  j  a v  a 2  s  .  com*/
 * @param request Http request
 * @param response Http response
 * @param e Throwable
 * @throws IOException Throw it out
 * @throws ServletException Throw it out
 */
protected void doHandleException(HttpServletRequest request, HttpServletResponse response, Throwable e)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter output = new PrintWriter(response.getOutputStream());
    output.print("<html><body><h2>Internal error occurs</h2><p><pre>");
    e.printStackTrace(output);
    output.print("</pre></p></body></html>");
    output.flush();
    output.close();
}

From source file:com.jjtree.servelet.Paragraphs.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from   w ww  . j a v  a 2s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    String pathInfo = request.getPathInfo();
    String[] path = pathInfo.split("/");
    int singleParagraphID = Integer.parseInt(path[1]);

    try {
        // Register JDBC driver
        Class.forName(JConstant.JDBC_DRIVER);

        // Open a connection
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);

        // Execute SQL query
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT * FROM JParagraph WHERE paragraphID = " + singleParagraphID;
        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            //Retrieve by column name
            int paragraphID = rs.getInt("paragraphID");
            int articleID = rs.getInt("articleID");
            int position = rs.getInt("position");

            String type = rs.getString("type");
            String content = rs.getString("content");

            JSONObject paragraph = new JSONObject();

            paragraph.put("paragraphID", paragraphID);
            paragraph.put("articleID", articleID);
            paragraph.put("position", position);

            paragraph.put("type", type);
            paragraph.put("content", content);

            PrintWriter writer = response.getWriter();
            writer.print(paragraph);
            writer.flush();
        }

        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try
}

From source file:feedme.controller.HomePageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from w  w  w  . ja  va 2s.c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    HashMap<String, Integer> category = new HashMap<>();
    List<Restaurant> restaurants;

    DbHPOnLoad dbPageOnLoad = new DbHPOnLoad();//creating a DbHPOnLoad object

    List<Restaurant> allResturent = new DbAdminManagmentTools().getAllRestaurants();

    int page = 1;
    int recordsPerPage = 6;

    if (request.getParameter("page") != null) {
        page = Integer.parseInt(request.getParameter("page"));
    }

    int noOfRecords = allResturent.size();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

    category = dbPageOnLoad.getCategories();//getting a categories
    restaurants = new DbRestaurantsManagement()
            .getNextRecentRestaurantsByCatAndCity((page - 1) * recordsPerPage, recordsPerPage, 0, "Asd");//get the last 6 new restaurants

    if (isAjaxRequest(request)) {
        try {
            JSONObject restObj = new JSONObject();
            JSONArray restArray = new JSONArray();
            for (Restaurant rest : restaurants) {
                restArray.put(new JSONObject().put("resturent", rest.toJson()));
            }
            restObj.put("resturent", restArray);
            restObj.put("noOfPages", noOfPages);
            restObj.put("currentPage", page);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(restObj);
            response.getWriter().flush();
            return;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    List<String> cities = dbPageOnLoad.getCities();
    if (request.getSession().getAttribute("shoppingCart") == null) {
        request.getSession().setAttribute("shoppingCart", new Order());//crete a new shopping cart
    }

    List<RestaurantRanking> rankings = dbPageOnLoad.getRestRandomComments(5);//getting a random rankings from DB

    for (RestaurantRanking re : rankings) {//looping over the rankings
        re.setResturent(new DbRestaurantsManagement().getRestaurantById(re.getRestId()));
    }

    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("category", category);//send the categories
    request.setAttribute("cities", cities);//send the cities
    request.setAttribute("restaurants", restaurants);//send the restaurants
    request.setAttribute("rankings", rankings);//send the rankings

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/index.jsp");//send a ajsp file
    dispatcher.forward(request, response);
    return;
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping(value = "/resetPassword", params = "action=changePassword", produces = "text/javascript")
public void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (!checkVcode(request)) {
        out.print("alert(\"??\");");
        return;/*from  w w w  . j  ava2  s .c  om*/
    }
    String newPassword = request.getParameter("newPassword");
    ValueCheck.checkPassword(newPassword);
    User user = userMapper.findOne(request.getParameter("u"));
    userMapper.update(user.toBuilder().password(passwordEncoder.encode(newPassword)).vcode(null)
            .expireTime(null).build());
    out.print("alert(\"???\");");
    out.print("document.location='" + request.getContextPath() + "'");
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP//from   ww  w.  ja v  a  2  s  .  co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:be.fedict.eid.idp.webapp.IdentityServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");

    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    IdPIdentity activeIdentity = identityService.findIdentity();
    if (null == activeIdentity) {

        out.print("No active identity eID IdP Identity configured.");

    } else {/*from   w  w  w.  j a va 2  s  .  c  o m*/

        String pemCertificateChain;
        try {
            pemCertificateChain = toPem(activeIdentity.getPrivateKeyEntry().getCertificateChain());
        } catch (Exception e) {
            LOG.error(e);
            return;
        }
        out.print(pemCertificateChain);
    }

    out.close();
}

From source file:Json.JsonCodes.java

public void jsonCreate(String patchName) {
    JSONObject obj = new JSONObject();
    JSONArray ar = new JSONArray();

    for (int i = 0; i < this.pageList.size(); i++) {

        ar.add(this.pageList.get(i));
    }/*from  w  w w. j  av  a2  s.  com*/
    obj.put("patch", this.patch);
    obj.put("page", ar);

    File file = new File(patchName);

    try {
        //?,  ?   ??  ? 
        if (!file.exists()) {
            file.createNewFile();
        }

        //PrintWriter ? ? ?  
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());

        try {
            //? ?  
            out.print(obj);
        } finally {
            //?     
            //   ??
            out.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.loklak.api.server.GeocodeServlet.java

@SuppressWarnings("unchecked")
@Override/*  w w  w .  j  a  v a 2s  . co  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RemoteAccess.Post post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            Map<String, Object> map = DAO.jsonMapper.readValue(data, DAO.jsonTypeRef);
            Object places_obj = map.get("places");
            if (places_obj instanceof List<?>) {
                List<Object> p = (List<Object>) places_obj;
                place = new String[p.size()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // find locations for places
    Map<String, Object> locations = new LinkedHashMap<>();
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        Map<String, Object> location = new LinkedHashMap<>();
        if (loc != null) {
            location.put("place",
                    minified ? new String[] { loc.getNames().iterator().next() } : loc.getNames());
            location.put("population", loc.getPopulation());
            location.put("country_code", loc.getISO3166cc());
            location.put("country", DAO.geoNames.getCountryName(loc.getISO3166cc()));
            location.put("location", new double[] { loc.lon(), loc.lat() });
            location.put("mark", new double[] { loc.mlon(), loc.mlat() });
        }
        locations.put(p, location);
    }

    post.setResponse(response, "application/javascript");

    // generate json
    Map<String, Object> m = new LinkedHashMap<>();
    m.put("locations", locations);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print((minified ? new ObjectMapper().writer() : new ObjectMapper().writerWithDefaultPrettyPrinter())
            .writeValueAsString(m));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.ebay.jetstream.management.HtmlResourceFormatter.java

protected void formatBean(boolean end, Class<?> bclass, String help) throws IOException {
    PrintWriter pw = getWriter();
    if (!CommonUtils.isEmptyTrimmed(help)) {
        pw.print("<I>" + help + "</I>: ");
    }/*from  w ww  . j av  a 2 s  .c o  m*/
    pw.println("type " + bclass.getName() + "<P/>");
}

From source file:com.streak.logging.analysis.AnalysisUtility.java

public static void writeSchema(FileService fileService, String bucketName, String schemaKey,
        List<String> fieldNames, List<String> fieldTypes, List<BigqueryFieldExporter> exporters)
        throws IOException, FileNotFoundException, FinalizationException, LockException {
    GSFileOptionsBuilder schemaOptionsBuilder = new GSFileOptionsBuilder().setBucket(bucketName)
            .setKey(createSchemaFilename(schemaKey)).setAcl("project-private");
    AppEngineFile schemaFile = fileService.createNewGSFile(schemaOptionsBuilder.build());

    FileWriteChannel schemaChannel = fileService.openWriteChannel(schemaFile, true);
    PrintWriter schemaWriter = new PrintWriter(Channels.newWriter(schemaChannel, "UTF8"));

    JSONArray fields = new JSONArray();

    for (int i = 0; i < fieldNames.size(); i++) {
        try {//ww w  . j  a v  a2s  .co  m
            JSONObject obj = new JSONObject();
            obj.put("name", fieldNames.get(i));
            obj.put("type", fieldTypes.get(i));

            BigqueryFieldExporter exp = exporters.get(i);
            if (exp instanceof BigqueryRecordFieldExporter) {
                obj.put("mode", "repeated");
                obj.put("fields", ((BigqueryRecordFieldExporter) exp).getRecordFields());
            } else {
                obj.put("mode", "nullable");
            }

            fields.put(obj);
        } catch (JSONException e) {
            log.severe("This should not happen!");
        }
    }

    schemaWriter.print(fields.toString());
    schemaWriter.close();

    schemaChannel.closeFinally();
}