Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:com.day.cq.wcm.foundation.forms.FieldHelper.java

/**
 * Write the client java script code to check a required field on
 * form submit.//  www .  j a v a 2 s.c o  m
 */
public static void writeClientRequiredCheck(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response, final FieldDescription desc) throws IOException {
    final String formId = FormsHelper.getFormId(request);
    if (desc.isRequired()) {
        final PrintWriter out = response.getWriter();
        final String qualifier = getClientFieldQualifier(request, desc);
        out.write("if (cq5forms_isEmpty(");
        out.write(qualifier);
        out.write(")) {cq5forms_showMsg('");
        out.write(StringEscapeUtils.escapeEcmaScript(formId));
        out.write("','");
        out.write(StringEscapeUtils.escapeEcmaScript(desc.getName()));
        out.write("','");
        out.write(StringEscapeUtils.escapeEcmaScript(desc.getRequiredMessage()));
        out.write("'); return false; }\n");
    }
}

From source file:com.day.cq.wcm.foundation.forms.FieldHelper.java

/**
 * Write the client java script code to check a constraint on
 * form submit./*from ww w  .  j  a  va  2s.c om*/
 */
public static void writeClientConstraintCheck(final SlingHttpServletRequest request,
        final SlingHttpServletResponse response, final FieldDescription desc)
        throws IOException, ServletException {
    if (desc.getConstraintType() != null) {
        final PrintWriter out = response.getWriter();
        final String qualifier = getClientFieldQualifier(request, desc);
        out.write("if (!cq5forms_isEmpty(");
        out.write(qualifier);
        out.write(")){");
        try {
            request.setAttribute(ATTR_DESC, desc);
            final Resource includeResource = new ResourceWrapper(desc.getFieldResource(),
                    desc.getConstraintType(), FormsConstants.RST_FORM_CONSTRAINT);

            FormsHelper.includeResource(request, response, includeResource,
                    FormsConstants.SCRIPT_CLIENT_VALIDATION);
            out.write("}");
        } finally {
            request.removeAttribute(ATTR_DESC);
        }
    }
}

From source file:cn.vlabs.umt.ui.servlet.AddClientServlet.java

public static void writeJSONObject(HttpServletResponse response, Object object) {
    PrintWriter writer = null;
    try {/*from   w  ww .jav  a  2 s  .c  o  m*/
        //IE???text/html?
        response.setContentType("text/html");
        writer = response.getWriter();
        writer.write(object.toString());
    } catch (IOException e) {
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}

From source file:modnlp.capte.AlignerUtils.java

public static void convertLineEndings(String inputfile, String outputfile) {
    /* This is a quick hackaround to convert the line endings from
     *  Windows files into Unix line endings so that the sentence splitter will work
     *  Seems to work, but hasn't been extensively tested.
     *///  w ww  .  ja v  a  2s. com
    try {
        File input = new File(inputfile);
        File output = new File(outputfile);
        BufferedReader bb = new BufferedReader(new InputStreamReader(new FileInputStream(inputfile), "UTF8"));
        PrintWriter bv = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputfile), "UTF8"));
        String l = "";
        while (bb.ready()) {
            l = bb.readLine();
            bv.write(l + "\n");
        }

        bb.close();
        bv.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:eu.trentorise.opendata.jackan.test.ckan.CkanTestReporter.java

public static void saveToDirectory(File outputDirectory, String indexContent, RunSuite runSuite) {

    outputDirectory.mkdirs();//from   www .  j a  v a  2 s .  c  o  m

    PrintWriter outIndex;
    try {
        outIndex = new PrintWriter(outputDirectory + "/index.html");
        outIndex.write(indexContent);
        outIndex.close();

        for (TestResult result : runSuite.getResults()) {
            PrintWriter outResult;
            String resultHtml = renderTestResult(result);
            outResult = new PrintWriter(outputDirectory + "/" + TEST_RESULT_PREFIX + result.getId() + ".html");
            outResult.write(resultHtml);
            outResult.close();
        }

        logger.log(Level.INFO, "Report is now available at {0}{1}index.html",
                new Object[] { outputDirectory.getAbsolutePath(), File.separator });
    } catch (FileNotFoundException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
}

From source file:com.threecrickets.sincerity.util.IoUtil.java

/**
 * Writes JVM primitives and collection/map instances to a JSON UTF-8 file.
 * /*w w w  .j  a  v  a 2  s.  c om*/
 * @param file
 *        The file
 * @param object
 *        The object (JVM primitives and collection instances)
 * @param expand
 *        Whether to expand the JSON with newlines, indents, and spaces
 * @throws IOException
 *         In case of an I/O error
 */
public static void writeJson(File file, Object object, boolean expand) throws IOException {
    String content = Json.to(object, expand).toString();
    FileOutputStream stream = new FileOutputStream(file);
    PrintWriter writer = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8), BUFFER_SIZE));
    try {
        writer.write(content);
    } finally {
        writer.close();
    }
}

From source file:Main.java

public static String post(String url, Map<String, String> params) {
    try {/*from   w  w  w .  j a v a 2s  . co m*/
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        PrintWriter pw = new PrintWriter(connection.getOutputStream());
        StringBuilder sbParams = new StringBuilder();
        if (params != null) {
            for (String key : params.keySet()) {
                sbParams.append(key + "=" + params.get(key) + "&");
            }
        }
        if (sbParams.length() > 0) {
            String strParams = sbParams.substring(0, sbParams.length() - 1);
            Log.e("cat", "strParams:" + strParams);
            pw.write(strParams);
            pw.flush();
            pw.close();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer response = new StringBuffer();
        String readLine = "";
        while ((readLine = br.readLine()) != null) {
            response.append(readLine);
        }
        br.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:controller.file.FileUploader.java

public static void fileDownloader(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;
    try {/* w ww .  j a v a 2s  . c  om*/
        String filename = "foo.xml";
        String filepath = "/tmp/";
        out = response.getWriter();
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
        int i;
        while ((i = fileInputStream.read()) != -1) {
            out.write(i);
        }
        fileInputStream.close();
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(FileUploader.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:de.rub.syssec.saaf.Main.java

/**
 * Prints the usage/help message.//w ww. j  a  v a 2s  .  com
 * 
 * @author Hanno Lemoine <Hanno.Lemoine@gdata.de> Thanks to Ben Gruver
 *         (JesusFreke)
 */
private static void usage(boolean printHeadlessGuiOptions) {
    SmaliHelpFormatter formatter = new SmaliHelpFormatter();
    int consoleWidth = ConsoleUtil.getConsoleWidth();
    formatter.setWidth(consoleWidth);

    PrintWriter writer = new PrintWriter(System.out);

    writer.write("SAAF  Copyright (C) 2013  syssec.rub.de\n");
    writer.write("This program comes with ABSOLUTELY NO WARRANTY.\n");
    writer.write("This is free software, and you are welcome to redistribute it\n");
    writer.write("under certain conditions.");

    writer.write("\n\n#########################################\n");
    writer.write("# SAAF: A static analyzer for APK files #\n");
    writer.write("#########################################\n");
    writer.write("\nUsage: java -jar saaf.jar [options] [file/directory]");
    writer.write("\nIf no options are set, SAAF will start in GUI mode.\n");

    writer.write("\nBasic Options:\n");
    formatter.printOptions(writer, consoleWidth, basicOptions, 1, 3);

    if (printHeadlessGuiOptions) {
        writer.write("\nHeadless Options:\n");
        formatter.printOptions(writer, consoleWidth, headlessOptions, 1, 3);

        writer.write("\nGUI Options:\n");
        formatter.printOptions(writer, consoleWidth, guiOptions, 1, 3);

        writer.write("\nReport, DB and Log Options:\n");
        formatter.printOptions(writer, consoleWidth, reportDbLogOptions, 1, 3);
    }
    writer.flush();
    // Do not close writer, otherwise System.out would be dead.
}

From source file:com.mgmtp.jfunk.web.util.HtmlValidatorUtil.java

/**
 * Validates an HTML file against the W3C markup validation service.
 * /*from  w  ww.j a  v a  2  s. c o m*/
 * @param validationResultDir
 *            target directory for validation result file
 * @param props
 *            properties must include the keys {@link WebConstants#W3C_MARKUP_VALIDATION_URL}
 *            and {@link WebConstants#W3C_MARKUP_VALIDATION_LEVEL}
 * @param file
 *            HTML file which will be validated
 */
public static void validateHtml(final File validationResultDir, final Configuration props, final File file)
        throws IOException {
    Preconditions.checkArgument(StringUtils.isNotBlank(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL)));
    InputStream is = null;
    BufferedReader br = null;
    InputStream fis = null;
    try {
        // Post HTML file to markup validation service as multipart/form-data
        URL url = new URL(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL));
        URLConnection uc = url.openConnection();
        MultipartPostRequest request = new MultipartPostRequest(uc);
        fis = new FileInputStream(file);
        /*
         * See http://validator.w3.org/docs/api.html#requestformat for a description of all
         * parameters
         */
        request.setParameter("uploaded_file", file.getPath(), fis);
        is = request.post();

        // Summary of validation is available in the HTTP headers
        String status = uc.getHeaderField(STATUS);
        int errors = Integer.parseInt(uc.getHeaderField(ERRORS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation errors=" + errors);
        int warnings = Integer.parseInt(uc.getHeaderField(WARNINGS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation warnings=" + warnings);

        // Check if result file has to be written
        String level = props.get(WebConstants.W3C_MARKUP_VALIDATION_LEVEL, "ERROR");
        boolean validate = false;
        if (StringUtils.equalsIgnoreCase(level, "WARNING") && (warnings > 0 || errors > 0)) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase(level, "ERROR") && errors > 0) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase("Invalid", status)) {
            validate = true;
        }

        if (validate) {
            br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            PrintWriter writer = null;
            String fileName = file.getName().substring(0, file.getName().length() - 5)
                    + "_validation_result.html";
            FileUtils.forceMkdir(validationResultDir);
            File validationResultFile = new File(validationResultDir, fileName);
            try {
                writer = new PrintWriter(validationResultFile, "UTF-8");
                writer.write(sb.toString());
                LOG.info("Validation result saved in file " + validationResultFile.getName());
            } catch (IOException ex) {
                LOG.error("Could not write HTML file " + validationResultFile.getName() + "to directory", ex);
            } finally {
                IOUtils.closeQuietly(writer);
            }
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(fis);
    }
}