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.hzc.framework.ssh.controller.WebUtil.java

/**
 * ?response//from  w w w  .ja va 2  s  .  c o m
 *
 * @param contentType responsecontentType
 * @param object      
 * @throws IOException
 */
public static void write(String contentType, Object object) throws RuntimeException {
    try {
        HttpServletResponse response = ActionContext.getResp();
        //System.out.println("json object:" + object);
        response.setContentType(contentType + ";charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //            try {
        writer.print(object);
        //            } finally {
        writer.flush();
        //                writer.close();
        //            }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:gov.nih.nci.lmp.refExport.AnnotationExporterHelper.java

/**
 * Export file.// w  ww.  ja  v  a  2  s.com
 * 
 * @param file
 *            the file
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void export(File file) throws IOException {

    OutputStream output = new FileOutputStream(file);

    try {
        PrintWriter out = new PrintWriter(new FileWriter(file));
        out.print(annotations);
        out.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        output.close();
    }
}

From source file:Json.JsonWrite.java

public void jsonCreate(String patchName) {
    JSONObject obj = new JSONObject();
    obj.put("patch", this.patch);
    obj.put("page", this.page);
    obj.put("eddWay", this.eddWay);
    obj.put("proffName", this.proffName);
    obj.put("yearStart", this.YStart);
    obj.put("yearEnd", this.YEnd);
    obj.put("eddName", this.EddName);

    File file = new File(patchName);

    try {/*from   w w  w  .  ja va  2s. co m*/
        //?,  ?   ??  ? 
        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:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from   w  w  w. j a va2s.  c o m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

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

        // Parse the request
        try {

            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!(item.isFormField())) {

                    File eml = processUploadedFile(item);

                    DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
                    String xml = dpmClient.evaluateDataPackage(eml);

                    ReportUtility qrUtility = new ReportUtility(xml);
                    String htmlTable = qrUtility.xmlToHtmlTable(cwd + xslpath);

                    if (htmlTable == null) {
                        String msg = "The uploaded file could not be evaluated.";
                        throw new UserErrorException(msg);
                    } else {
                        html = HTMLHEAD + "<div class=\"qualityreport\">" + htmlTable + "</div>" + HTMLTAIL;
                    }

                }

            }

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print(html);
    out.flush();
    out.close();
}

From source file:functionaltests.dataspaces.TestGlobalSpace.java

/**
 * @param files Writes files: {{filename1, filecontent1},...,{filenameN, filecontentN}}
 * @param path in this director /*www  .j a va 2  s .c  o  m*/
 * @throws IOException
 */
private void writeFiles(String[][] files, String path) throws IOException {
    for (String[] file : files) {
        File f = new File(path + File.separator + file[0]);
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))));
        out.print(file[1]);
        out.close();
    }
}

From source file:com.mebigfatguy.polycasso.JavaSaver.java

private String getColorData(PolygonData[] data) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    String comma = "";
    for (PolygonData pd : data) {

        pw.println(comma);/* w ww .  ja va 2s. c  om*/
        pw.print(TABS);
        pw.print("{");

        Color color = pd.getColor();
        pw.print(color.getRed());
        pw.print(",");
        pw.print(color.getGreen());
        pw.print(",");
        pw.print(color.getBlue());
        pw.print("}");
        comma = ",";
    }

    pw.flush();
    return sw.toString();
}

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

public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String query = request.getParameter("q");
    if (query != null) {
        ServletContext context = getServlet().getServletContext();
        BeanFactory factory = (BeanFactory) context.getAttribute(Attributes.APPLICATION_CONTEXT_KEY);
        UserService us = (UserService) factory.getBean("UserService");
        Collection<User> users = us.search(query, 0, 10);

        //JSON/*from   ww w .j  ava 2  s .  co m*/
        StringBuffer json = new StringBuffer();
        boolean first = true;
        json.append("[");
        if (users != null) {
            for (User user : users) {
                if (!first) {
                    json.append(",");
                } else {
                    first = false;
                }
                json.append("{u:'" + user.getUmtId() + "'");
                json.append(", t:'" + user.getTrueName() + "'}");
            }
        }
        json.append("]");

        //?SON
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        PrintWriter writer = response.getWriter();
        writer.print(json.toString());
        writer.flush();
        writer.close();
    }
    return null;
}

From source file:com.farmafene.aurius.mngt.impl.DirectoryWorker.java

/**
 * {@inheritDoc}//w ww  . j  av  a2s .  c  om
 * 
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    if (logger.isInfoEnabled()) {
        logger.info(this + "<running>");
    }
    for (;;) {
        CallStatus status = null;
        if (logger.isDebugEnabled()) {
            logger.debug(this + "<waiting>");
        }
        try {
            status = queue.take();
        } catch (InterruptedException e) {
            logger.info(this + ": Interrumpido", e);
            break;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Procesando: " + status);
        }
        Date exDate = new Date(status.getInitTime());
        String fileName = Configuracion.getConfigPath();
        File f = new File(fileName);
        f = f.getParentFile();
        f = new File(f, "logs");
        File dirBase = new File(f, df.format(exDate));
        if (logger.isDebugEnabled()) {
            logger.debug("Log Base: " + f.getPath());
        }
        File logFile = null;
        if (!dirBase.exists()) {
            dirBase.mkdirs();
        }
        try {
            String dirNop = String.format(String.format("%1$08x", status.hashCode()));
            logFile = new File(dirBase, "tx");
            logFile = new File(logFile, dirNop.substring(0, 2));
            logFile = new File(logFile, dirNop.substring(2, 4));
            logFile = new File(logFile, dirNop.substring(4, 6));
            // logFile = new File(logFile, dirNop.substring(6));
            if (!logFile.exists()) {
                logFile.mkdirs();
            }
            String fff = status.getContexto().getId().toString();
            fff = fff + df2.format(exDate) + ".xml";

            logFile = new File(logFile, fff);
            FileOutputStream appendedFile = new FileOutputStream(
                    new File(dirBase, "listado." + df3.format(exDate).substring(0, 4) + "0.html"), true);
            FileWorker work = new FileWorker();
            work.setFile(logFile);
            work.setStatus(status);
            if (logger.isDebugEnabled()) {
                logger.debug("Enviando Status:" + work);
            }
            workManager.scheduleWork(work);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintWriter pf = new PrintWriter(baos);
            pf.print("<a href=\"");
            pf.print(makeRelative(logFile, dirBase.getPath()));
            pf.print("\">");
            pf.print(logFile.getName());
            pf.print("</a><br/>");
            pf.flush();
            baos.flush();
            appendedFile.write(baos.toString().getBytes());
            appendedFile.flush();
            appendedFile.close();
        } catch (FileNotFoundException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        } catch (WorkException e) {
            logger.error(e);
        }

    }

}

From source file:com.qwazr.webapps.exception.WebappException.java

private void sendQuietlyHTML(HttpServletResponse response) throws IOException {
    PrintWriter printWriter = response.getWriter();
    String message = StringEscapeUtils.escapeHtml4(error.message);
    response.setStatus(error.status);/*from  w w  w.  j  a  v  a 2 s. c  o  m*/
    response.setContentType("text/html");
    printWriter.print("<html><head><title>");
    printWriter.print(error.title.title);
    printWriter.println("</title></head>");
    printWriter.print("<body><h3>");
    printWriter.print(error.title.title);
    printWriter.println("</h3>");
    printWriter.print("<pre>");
    printWriter.print(message);
    printWriter.println("</pre></body></html>");
}

From source file:com.atlassian.clover.reporters.console.ConsoleReporter.java

public void report(PrintWriter out, CloverDatabase db) {
    out.print("Clover Coverage Report");
    if (cfg.getTitle() != null) {
        out.println(" - " + cfg.getTitle());
    } else {/*from ww w . j av a  2  s.com*/
        out.println();
    }
    out.println("Coverage Timestamp: " + new Date(db.getRecordingTimestamp()));
    out.println("Report for code   : " + cfg.getCodeType());

    List<? extends PackageInfo> packages = db.getModel(cfg.getCodeType()).getAllPackages();
    if (cfg.getLevel().isShowPackages()) {
        out.println();
        out.println("Package Summary - ");
    }

    for (PackageInfo aPackage : packages) {
        FullPackageInfo pkg = (FullPackageInfo) aPackage;
        if (cfg.getPackageSet() != null && !cfg.getPackageSet().contains(pkg.getName())) {
            continue;
        }
        if (cfg.getLevel().isShowPackages()) {
            out.println(
                    pkg.getName() + ": " + Formatting.getPercentStr(pkg.getMetrics().getPcCoveredElements()));
        }

        final List<? extends FileInfo> fileInfos = pkg.getFiles();
        for (FileInfo fileInfo : fileInfos) {
            final FullFileInfo fInfo = (FullFileInfo) fileInfo;

            if (cfg.getLevel().isShowClasses()) {
                out.println("---------------------------------------");
                out.println("File: " + fInfo.getPackagePath());

                final List<? extends ClassInfo> classes = fInfo.getClasses();
                for (ClassInfo cInfo : classes) {
                    final ClassMetrics metrics = (ClassMetrics) cInfo.getMetrics();
                    out.println("Package: " + cInfo.getPackage().getName());
                    printMetricsSummary(out, "Class: " + cInfo.getName(), metrics, cfg);
                }
            }

            if (cfg.getLevel().isShowMethods() || cfg.getLevel().isShowStatements()) {
                final LineInfo[] lines = fInfo.getLineInfo(cfg.isShowLambdaFunctions(),
                        cfg.isShowInnerFunctions());
                for (LineInfo info : lines) {
                    if (info != null) {
                        if (cfg.getLevel().isShowMethods()) {
                            reportMethodsForLine(out, fInfo, info);
                        }
                        if (cfg.getLevel().isShowStatements()) { // in this case means both statements and branches
                            reportStatementsForLine(out, fInfo, info);
                            reportBranchesForLine(out, fInfo, info);
                        }
                    }
                }
            }
        }
    }

    out.println();
    out.println();
    ProjectMetrics overview = (ProjectMetrics) db.getModel(cfg.getCodeType()).getMetrics();
    printMetricsSummary(out, "Coverage Overview -", overview, cfg);
    out.flush();
}