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:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * // w  ww .  jav a  2 s .c  om
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.close();
        uc.getOutputStream().close();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:com.cloudera.knittingboar.conf.cmdline.ModelTrainerCmdLineDriver.java

static void mainToOutput(String[] args, PrintWriter output) throws Exception {
    if (parseArgs(args)) {

        output.write("Parse:correct");

    } // if//from   w w  w  .jav  a 2s  .com
}

From source file:com.delmar.core.web.filter.ExportDelegate.java

/**
 * Actually writes exported data. Extracts content from the Map stored in request with the
 * <code>TableTag.FILTER_CONTENT_OVERRIDE_BODY</code> key.
 * @param wrapper BufferedResponseWrapper implementation
 * @param response HttpServletResponse/*  w  ww.j a  v a  2  s .c o  m*/
 * @param request ServletRequest
 * @throws java.io.IOException exception thrown by response writer/outputStream
 */
public static void writeExport(HttpServletResponse response, ServletRequest request,
        BufferedResponseWrapper wrapper) throws IOException {

    if (wrapper.isOutRequested()) {
        // data already written
        log.debug("Filter operating in unbuffered mode. Everything done, exiting");
        return;
    }

    // if you reach this point the PARAMETER_EXPORTING has been found, but the special header has never been set in
    // response (this is the signal from table tag that it is going to write exported data)
    log.debug("Filter operating in buffered mode. ");

    Map bean = (Map) request.getAttribute(TableTag.FILTER_CONTENT_OVERRIDE_BODY);

    if (log.isDebugEnabled()) {
        log.debug(bean);
    }

    Object pageContent = bean.get(TableTagParameters.BEAN_BODY);

    if (pageContent == null) {
        if (log.isDebugEnabled()) {
            log.debug("Filter is enabled but exported content has not been found. Maybe an error occurred?");
        }

        response.setContentType(wrapper.getContentType());
        PrintWriter out = response.getWriter();

        out.write(wrapper.getContentAsString());
        out.flush();
        return;
    }

    // clear headers
    if (!response.isCommitted()) {
        response.reset();
    }

    String filename = (String) bean.get(TableTagParameters.BEAN_FILENAME);
    String contentType = (String) bean.get(TableTagParameters.BEAN_CONTENTTYPE);

    if (StringUtils.isNotBlank(filename)) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    }

    String characterEncoding = wrapper.getCharacterEncoding();
    String wrappedContentType = wrapper.getContentType();

    if (wrappedContentType != null && wrappedContentType.indexOf("charset") > -1) {
        // charset is already specified (see #921811)
        characterEncoding = StringUtils.substringAfter(wrappedContentType, "charset=");
    }

    if (characterEncoding != null && contentType.indexOf("charset") == -1) //$NON-NLS-1$
    {
        contentType += "; charset=" + characterEncoding; //$NON-NLS-1$
    }

    response.setContentType(contentType);

    if (pageContent instanceof String) {
        // text content
        if (characterEncoding != null) {
            response.setContentLength(((String) pageContent).getBytes(characterEncoding).length);
        } else {
            //FIXME  Reliance on default encoding
            // Found a call to a method which will perform a byte to String (or String to byte) conversion,
            // and will assume that the default platform encoding is suitable.
            // This will cause the application behaviour to vary between platforms.
            // Use an alternative API and specify a charset name or Charset object explicitly.
            response.setContentLength(((String) pageContent).getBytes().length);
        }

        PrintWriter out = response.getWriter();
        out.write((String) pageContent);
        out.flush();
    } else {
        // dealing with binary content
        byte[] content = (byte[]) pageContent;
        response.setContentLength(content.length);
        OutputStream out = response.getOutputStream();
        out.write(content);
        out.flush();
    }
}

From source file:com.ibm.ids.example.ShowResult.java

public static void writeToVulnerableSink(String str) throws java.io.FileNotFoundException {
    FileOutputStream fos = new FileOutputStream(str);
    PrintWriter writer = new PrintWriter(fos);
    //STATIC SCAN 
    //to remove this vulnerability issue use writer.append rather than writer.write 
    writer.write(str);
    //writer.append(str);
    writer.close();/*from www  .j  av a  2s  .c o m*/
}

From source file:de.cgarbs.lib.json.JSONDataModel.java

/**
 * Converts the DataModel to JSON format and writes the JSON data to the
 * specified file.// ww  w  . j  av a 2  s  .  co  m
 *
 * @param model the DataModel to be converted to JSON
 * @param file the File to be written to
 * @throws DataException either IO errors or errors during the JSON conversion
 */
public static void writeToFile(final DataModel model, final File file) throws DataException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(file);
        out.write(convertToJSON(model));
        out.close();
    } catch (FileNotFoundException e) {
        throw wrappedAsDataException(DataException.ERROR.IO_ERROR, e);
    } catch (JSONException e) {
        throw wrappedAsDataException(DataException.ERROR.JSON_CONVERSION_ERROR, e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
    if (out.checkError()) {
        // FIXME: PrintWriter throws no IOExceptions?!  how to find out what happened?
        throw new DataException(DataException.ERROR.IO_ERROR, "error writing to file");
    }
}

From source file:com.plugin.autoflox.invarscope.aji.executiontracer.JSExecutionTracer.java

/**
 * Retrieves the JavaScript instrumentation array from the webbrowser and
 * writes its contents in Daikon format to a file.
 * /*from  w  w w.j a v  a 2s . co m*/
 * @param session
 *            The crawling session.
 * @param candidateElements
 *            The candidate clickable elements.
 */
public static void generateTrace(String state, String outputFolder) {

    currentState = state;

    String filename = outputFolder + EXECUTIONTRACEDIRECTORY + "jsexecutiontrace-";
    filename += state;

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date();
    filename += dateFormat.format(date) + ".dtrace";

    traceVector.addElement(filename);
    System.out.println("traceVector size: " + traceVector.size());

    try {

        /*
         * FIXME: Frank, hack to send last buffer items and wait for them to
         * arrive
         */
        //session.getBrowser().executeJavaScript("sendReally();");

        Trace trace = Trace.parse(points);

        PrintWriter file = new PrintWriter(filename);
        file.write(trace.getDeclaration());
        file.write('\n');
        file.write(trace.getData(points));
        file.close();

        System.out.println("Points before cleaned: \n" + points.toString());
        // Justin: We dont need empty points array now since we want to trace multiple errors
        //points = new JSONArray();

    } catch (Exception e) {
        e.printStackTrace();
    }

    /* FROLIN - TRY TO RETRIEVE DOM */
    /*
    try {
       NodeList nlist = session.getCurrentState().getDocument()
       .getElementsByTagName("*");
       System.out.println("State IDs");
       for (int i = 0; i < nlist.getLength(); i++) {
    Element e = (Element) nlist.item(i);
    if (e.hasAttribute("id")) {
       System.out.println(e.getAttribute("id"));
    }
       }
       System.out.println("\n");
    } catch (Exception ee) {
       System.out.println("Error: Exception when retrieving document");
       System.exit(-1);
    }
    */
    /* END TRY TO RETRIEVE DOM */
}

From source file:index.IncrementIndex.java

/**
 * id//ww w .j  av  a  2  s.c o  m
 * @param path
 * @param storeId
 * @return 
 */
public static boolean writeStoreId(String path, String storeId) {
    boolean b = false;
    try {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(path);
        PrintWriter out = new PrintWriter(fw);
        out.write(storeId);
        out.close();
        fw.close();
        b = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return b;
}

From source file:io.proleap.vb6.TestGenerator.java

public static void generateTestClass(final File vb6InputFile, final File outputDirectory,
        final String packageName) throws IOException {
    final String inputFilename = getInputFilename(vb6InputFile);
    final File outputFile = new File(
            outputDirectory + "/" + inputFilename + OUTPUT_FILE_SUFFIX + JAVA_EXTENSION);

    final boolean createdNewFile = outputFile.createNewFile();

    if (createdNewFile) {
        LOG.info("Creating unit test {}.", outputFile);

        final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile));
        final String vb6InputFileName = vb6InputFile.getPath().replace("\\", "/");

        pWriter.write("package " + packageName + ";\n");
        pWriter.write("\n");
        pWriter.write("import java.io.File;\n");
        pWriter.write("\n");
        pWriter.write("import org.junit.Test;\n");
        pWriter.write("import io.proleap.vb6.runner.VbParseTestRunner;\n");
        pWriter.write("import io.proleap.vb6.runner.impl.VbParseTestRunnerImpl;\n");
        pWriter.write("\n");
        pWriter.write("public class " + inputFilename + "Test {\n");
        pWriter.write("\n");
        pWriter.write("   @Test\n");
        pWriter.write("   public void test() throws Exception {\n");
        pWriter.write("      final File inputFile = new File(\"" + vb6InputFileName + "\");\n");
        pWriter.write("      final VbParseTestRunner runner = new VbParseTestRunnerImpl();\n");
        pWriter.write("      runner.parseFile(inputFile);\n");
        pWriter.write("   }\n");
        pWriter.write("}");

        pWriter.flush();/*from w ww. j  av a2s .  com*/
        pWriter.close();
    }
}

From source file:com.frostwire.gui.library.M3UPlaylist.java

/**
 * Call this when you want to save the contents of the playlist.
 * NOTE: only local files can be saved in M3U format, filters out URLs 
 * that are not part of the local filesystem
 * @exception IOException Throw when save failed.
 * @exception IOException Throw when save failed.
 *//*from ww  w . jav a2 s .  co m*/
public static void save(String fileName, List<File> files) throws IOException {
    File playListFile = new File(fileName);
    // if all songs are new, just get rid of the old file.  this may
    // happen if a delete was done....
    if (files.size() == 0) {
        //            if (playListFile.exists()) {
        //                playListFile.delete();
        //            }
        return;
    }

    PrintWriter m3uFile = null;
    try {
        m3uFile = new PrintWriter(new FileWriter(playListFile.getCanonicalPath(), false));

        m3uFile.write(M3U_HEADER);
        m3uFile.println();

        for (File currFile : files) {
            // only save files that are local to the file system
            if (currFile.isFile()) {
                File locFile;
                locFile = new File(currFile.toURI());

                // first line of song description...
                m3uFile.write(SONG_DELIM);
                m3uFile.write(SEC_DELIM);
                // try to write out seconds info....
                //if( currFile.getProperty(PlayListItem.LENGTH) != null )
                //    m3uFile.write("" + currFile.getProperty(PlayListItem.LENGTH) + ",");
                //else
                m3uFile.write("" + -1 + ",");
                m3uFile.write(currFile.getName());
                m3uFile.println();
                // canonical path follows...
                m3uFile.write(locFile.getCanonicalPath());
                m3uFile.println();
            }
        }
    } finally {
        IOUtils.closeQuietly(m3uFile);
    }
}

From source file:com.yuga.common.web.Servlets.java

public static void print(HttpServletResponse resp, String msg) {
    PrintWriter pw;
    try {/*from  w w  w. jav a 2  s .co  m*/
        pw = resp.getWriter();
        pw.write(msg);
        pw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}