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.isecpartners.gizmo.ThirdIdea.java

private void executeCommand(final String text) {
    final InputStream procInput;
    new Thread(new Runnable() {

        public void run() {
            try {
                temp_files_to_clean_up.add(buffer_file.getCanonicalPath());
                PrintWriter out = new PrintWriter(new FileOutputStream(buffer_file));
                if (jTextPane1.getSelectedText() != null && jTextPane1.getSelectedText().length() > 0) {
                    out.write(jTextPane1.getSelectedText());
                } else {
                    out.write(jTextPane1.getText());
                }//from  w  w w.  j  ava2s  . c  o  m
                out.close();
                String env[] = getenv(1);
                env[0] = "BUF=" + buffer_file.getCanonicalPath();

                String output = exec(text, env);
                ThirdIdea.this.shell_output_area.setText(shell_output_area.getText() + output);
                ThirdIdea.this.shell_output_area.getCaret().setVisible(true);
                ThirdIdea.this.shell_output_area.setCaretPosition(shell_output_area.getText().length() - 1);
            } catch (IOException ex) {
                Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);

            } finally {
                if (jTextPane1.getSelectedText() != null && jTextPane1.getSelectedText().length() > 0) {
                    jTextPane1.replaceSelection(readWholeFile(buffer_file));
                } else {
                    ThirdIdea.this.jTextPane1.setText(readWholeFile(buffer_file));
                }
            }

        }

        private String readWholeFile(File file) {
            InputStream in = null;
            String ret = "";
            try {
                in = new FileInputStream(file);
                int file_size = Integer.MAX_VALUE;
                if (file.length() < Integer.MAX_VALUE) {
                    file_size = (int) file.length();
                }
                byte[] buf = new byte[file_size];
                // truncated because for some reason, a byte array is initialized with an int instead of a long
                // so this's a bit awful, but if you're editing a request bigger than 2G in size, then don't
                in.read(buf);
                ret = new String(buf);
            } catch (IOException ex) {
                Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return ret;
        }
    }).start();

}

From source file:com.isecpartners.gizmo.ThirdIdea.java

private String process_req_variable(String text) {
    PrintWriter out = null;
    String ret = text;//from   w w w.  ja va2 s  .  c  om
    try {
        File tmp2 = File.createTempFile("tmp", "end");
        temp_files_to_clean_up.add(tmp2.getCanonicalPath());
        out = new PrintWriter(new FileOutputStream(tmp2));
        out.write(reqText);
        out.close();
        ret = ret.replace("$REQ", "\"" + tmp2.getCanonicalPath() + "\"");
    } catch (IOException ex) {
        Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
    return ret;
}

From source file:com.funambol.json.gui.GuiServlet.java

private void sendHtmlPage(HttpServletResponse response, String result) throws IOException {

    response.setContentType("text/html");

    PrintWriter writer = response.getWriter();
    writer.write(result);
    writer.flush();/*www.j ava  2 s.  c  o  m*/
}

From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java

private void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession(false);
    Particular demandante = (Particular) session.getAttribute("usuario");

    StringBuilder sb = new StringBuilder();
    sb.append("<response>");

    if (request.getContentLengthLong() > 104857600) {
        response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        sb.append("<message>");
        sb.append(new Messages().getClientMessage("error", 7));
        sb.append("</message>");
    } else {/*  w  w w. jav a2  s . c  o m*/
        // Campos formulario
        UploadFile uf = new UploadFile(request);

        String numeroDemanda = ToolBox.createNumeroDemanda();
        String nombre = uf.getFormField("nombre");
        String descripcion = uf.getFormField("descripcion");
        int estado = 1;
        System.out.println("Archivos: " + uf.getFiles().size());
        // Validamos datos
        if (numeroDemanda == null || numeroDemanda.equals("") || nombre == null || nombre.equals("")
                || descripcion == null || descripcion.equals("") || uf.getFiles().size() < 1) {

            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sb.append("<message>");
            sb.append(new Messages().getClientMessage("error", 1));
            sb.append("</message>");
        } else {
            // Tiempo
            Date fechaCreacion = ToolBox.dateFormat(new Date());

            // Obtenemos 3 magistrados con menos demandas asignadas
            MagistradoDAO madao = new MagistradoDAO();
            Set<Magistrado> magistrados = madao.get3Magistrado();

            if (magistrados == null || magistrados.size() < 3) {
                magistrados = madao.readAll3();
            }

            // Objetos de TIEMPO
            Tiempo tiempo = new Tiempo();
            tiempo.setFechaCreacion(fechaCreacion);
            TiempoDAO tidao = new TiempoDAO();

            // Objeto de DEMANDA
            Demanda demanda = new Demanda();
            demanda.setParticularByIdParticularDemandante(demandante);
            demanda.setTiempo(tiempo);
            demanda.setNumeroDemanda(numeroDemanda);
            demanda.setNombreDemanda(nombre);
            demanda.setDescripcion(descripcion);
            demanda.setEstado(estado);
            demanda.setMagistrados(magistrados);

            DemandaDAO dedao = new DemandaDAO();
            if (!tidao.create(tiempo) || !dedao.create(demanda)) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                sb.append("<message>");
                sb.append(new Messages().getClientMessage("error", 4));
                sb.append("</message>");
            } else {
                // Guardamos los documentos
                String sala = "s1";
                String uri = request.getScheme() + "://" + request.getServerName() + ":"
                        + request.getServerPort() + "/" + this.getServletContext().getContextPath();

                for (FileItem fi : uf.getFiles()) {
                    // Documentos
                    Documento documento = new Documento();
                    documento.setDemanda(demanda);
                    documento.setParticular(demandante);
                    documento.setFechaCarga(ToolBox.dateFormat(new Date()));
                    documento.setRuta(
                            uf.saveFile(fi, this.getServletContext().getRealPath(""), sala, numeroDemanda));
                    documento.setEstado(1);
                    documento.setNombre(fi.getName());

                    DocumentoDAO dodao = new DocumentoDAO();

                    if (!dodao.create(documento)) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        sb.append("<message>");
                        sb.append(new Messages().getClientMessage("error", 7));
                        sb.append("</message>");
                        break;
                    }
                }

                //Mail mail = new Mail(demandante.getCatalogousuarios().getCorreo(), "Demanda creada", "Nmero de demanda: " + numeroDemanda);
                Mail mail = new Mail("eddy_wallace@hotmail.com", "Demanda creada",
                        "Nmero de demanda: " + numeroDemanda);

                if (!mail.sendMail()) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("error", 8));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                } else {
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("ok", 5));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                }
            }
        }
    }

    sb.append("</response>");
    PrintWriter pw = response.getWriter();
    pw.write(sb.toString());
}

From source file:com.symbian.driver.core.controller.tasks.ExecuteTransferSet.java

/**
 * Create a SIS file with a PKG file.//from ww  w. j a v  a  2s.co m
 * 
 * @param aEpocRoot
 *            The EPOCROOT directory to use when creating the SIS files
 * @param aSisPcPath
 *            The location of where to start the SIS files to
 * @param aCert
 *            The Certificate location to sign the SIS file with.
 * @param aKey
 *            The Key location to encrypt the SIS file with.
 * @param aSisPackage
 *            The package file to be used to create the SIS file.
 * @throws IOException
 * @throws TimeLimitExceededException
 * @throws FileNotFoundException
 */
public void createSis(final File aEpocRoot, final File aSisPcPath, final File aCert, final File aKey)
        throws IOException, TimeLimitExceededException, FileNotFoundException {
    LOGGER.fine("Creating SIS File: " + aSisPcPath);

    File lCreateSis = new File(aEpocRoot, "epoc32/tools/createsis.bat");
    File lMakeSis = new File(aEpocRoot, "epoc32/tools/makesis.exe");
    File lSignSis = new File(aEpocRoot, "epoc32/tools/signsis.exe");

    // Create the SIS file
    if (false && lCreateSis.exists()) {
        //  never enter this if statement... defect with createsis on
        // the security team.

        // Use the CreateSIS batch script
        new ExecuteOnHost(aEpocRoot, lCreateSis.getCanonicalPath() + " create -key " + aKey.getAbsolutePath()
                + " -cert " + aCert.getAbsolutePath() + iPkgFile.getCanonicalPath()).doTask(true, 0, false);

        //  change -tmp.sis to just .sis when signing works
        // (new File((aSisPackage.getPath()).replaceFirst("\\.pkg",
        // "-tmp\\.sis"))).renameTo(aHostPath);

    } else if (lMakeSis.exists()) {

        // Run MakeSIS
        ExecuteOnHost lPacker = new ExecuteOnHost(aEpocRoot, lMakeSis.getCanonicalPath() + " \""
                + iPkgFile.getCanonicalPath() + "\" \"" + aSisPcPath.getCanonicalPath() + "\"");

        if (lPacker.doTask(true, 0, true)) {
            String lOutput = lPacker.getOutput();
            if (lOutput.contains("error")) {
                throw new IOException("Creating sis file for " + iPkgFile.getCanonicalPath() + "  failed.");
            }
        } else {
            throw new IOException("Creating sis file for " + iPkgFile.getCanonicalPath() + "  failed.");
        }

        if (lSignSis.exists()) {

            File lPassPhrase = TDConfig.getInstance().getCertPass();
            String lPassString = lPassPhrase == null ? "" : " \"" + lPassPhrase.getAbsolutePath() + "\" ";

            String lAlgo = " -cr ";
            try {
                lAlgo = TDConfig.getInstance().getPreference(TDConfig.SIGN_ALGORITHM).equalsIgnoreCase("RSA")
                        ? " -cr "
                        : " -cd ";
            } catch (ParseException lParseException) {
                LOGGER.log(Level.SEVERE, "Could not get signing algorith type from config. defaulting to RSA");
            }

            // Run SignSIS
            ExecuteOnHost lExecuteOnHost = new ExecuteOnHost(aEpocRoot,
                    lSignSis.getCanonicalPath() + lAlgo + " -s \"" + aSisPcPath.getCanonicalPath() + "\" \""
                            + aSisPcPath.getCanonicalPath() + "\" \"" + aCert.getCanonicalPath() + "\" \""
                            + aKey.getCanonicalPath() + "\"" + lPassString);
            if (lExecuteOnHost.doTask(true, 0, true)) {
                String lOutput = lExecuteOnHost.getOutput();
                if (lOutput.contains("error")) {
                    throw new IOException("Signing sis file " + aSisPcPath.getCanonicalPath() + " failed.");
                }
            } else {
                throw new IOException("Signing sis file " + aSisPcPath.getCanonicalPath() + " failed.");
            }

        } else {
            throw new IOException("signsis.exe does not exist in the /epoc32/tools/ folder");
        }

    } else {
        throw new IOException("makesis.exe does not exist in the /epoc32/tools/ folder");
    }

    // Rewrite the package file with variables for PlatSec OFF remoting

    // Get the repository path in a string and get rid of traling \
    String lReposPath = iRepository.getCanonicalPath();
    if (lReposPath.endsWith("\\")) {
        lReposPath = lReposPath.substring(0, lReposPath.length() - 1);
    }

    // Replace all repository paths with the repository variable
    BufferedReader lSisPackageReader = new BufferedReader(new FileReader(iPkgFile));
    String lReadLine = null;
    StringBuffer lChangedPackage = new StringBuffer();
    while ((lReadLine = lSisPackageReader.readLine()) != null) {
        lChangedPackage.append(lReadLine.toLowerCase().replaceAll("\\Q" + lReposPath.toLowerCase() + "\\E",
                "\\" + REPOS_VARIABLE_LITERAL) + "\n");
    }
    lSisPackageReader.close();

    // Write the new result to a buffer
    PrintWriter lPrintWriter = new PrintWriter(new FileOutputStream(iPkgFile));
    lPrintWriter.write(lChangedPackage.toString());
    lPrintWriter.flush();
    lPrintWriter.close();

    // Confirm that the Sis package was created
    if (!aSisPcPath.isFile()) {
        throw new IOException("Could not create SIS file: " + aSisPcPath);
    }
}

From source file:org.chtijbug.drools.platform.web.filter.DynamicBaseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug(">> doFilterInternal()");
    try {//from  ww  w  .  j  a  v a 2 s  .c o m
        PrintWriter out = response.getWriter();
        CharResponseWrapper wrapper = new CharResponseWrapper(response);
        filterChain.doFilter(request, wrapper);

        String baseHref = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/";
        logger.debug("About to replace the base href element with {}", baseHref);
        String modifiedHtml = baseElementPattern.matcher(wrapper.toString())
                .replaceAll("<base href=\"" + baseHref + "\"");
        logger.debug("Modified HTML content : {}", modifiedHtml);
        // Write our modified text to the real response
        response.setContentLength(modifiedHtml.getBytes().length);
        out.write(modifiedHtml);
        out.close();
    } catch (Throwable t) {
        logger.error(t.getMessage());
    } finally {
        logger.debug("<< doFilterInternal()");
    }
}

From source file:com.sshdemo.common.report.manage.web.ParameterSetAction.java

private void buildChart() {
    PrintWriter pw = null;
    InputStream in = null;/*from   w  ww  .j a v  a 2s  . c o m*/
    try {
        ChartReport chart = reportFac.findChartReportById(reportId);

        HttpServletResponse response = ServletActionContext.getResponse();
        pw = response.getWriter();

        response.reset();// 
        response.setContentLength(0);
        byte[] bytes = chartFactory.export(chart, paraMap);
        response.setContentLength(bytes.length);
        response.setHeader("Content-Type", "image/png");
        in = new ByteArrayInputStream(bytes);
        int len = 0;
        while ((len = in.read()) > -1) {
            pw.write(len);
        }
        pw.flush();
    } catch (Exception e) {
        // log.error(e.toString());
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.isecpartners.gizmo.FourthIdea.java

private String process_req_variable(String text) {
    PrintWriter out = null;
    String ret = text;//from   w ww . java  2 s.c  o m
    try {
        File tmp2 = File.createTempFile("tmp", "end");
        temp_files_to_clean_up.add(tmp2.getCanonicalPath());
        out = new PrintWriter(new FileOutputStream(tmp2));
        out.write(reqText);
        out.close();
        ret = ret.replace("$REQ", "\"" + tmp2.getCanonicalPath() + "\"");
    } catch (IOException ex) {
        Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
    return ret;
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Handles a SPARQL query. /*from  ww  w .j  a  v a  2 s . c  o  m*/
 * The endpoint supports the <code>SELECT</code>, <code>CONSTRUCT</code> and
 * <code>DESCRIBE</code> query forms; triple serialization is limited to the <code>RDF/XML<code> format.
 * The indication of graphs using the <code>defaultgraphuri</code> and <code>namedgraphuri</code>
 * elements is not supported; however graphs may be indicated in the query text using
 * <code>FROM</code> and <code>FROM NAMED</code> keywords
 * 
 * @param request
 * @param response
 * @param outputStream
 */
private void sparqlQuery(HttpServletRequest request, HttpServletResponse response, OutputStream outputStream) {
    RepositoryConnection conn = null;
    String query = request.getParameter("query");

    try {
        conn = dataRepository.getConnection();
        Query q = conn.prepareQuery(QueryLanguage.SPARQL, query);

        if (q instanceof TupleQuery) {
            /* <code>SELECT</code> form */
            response.setContentType("application/sparql-results+xml");
            SPARQLResultsXMLWriter sparqlWriter = new SPARQLResultsXMLWriter(outputStream);
            ((TupleQuery) q).evaluate(sparqlWriter);
        } else if (q instanceof GraphQuery) {
            /* <code>CONSTRUCT</code> and <code>DESCRIBE</code> forms */
            response.setContentType("application/rdf+xml");
            RDFXMLWriterUnique rdfXmlWriter = new RDFXMLWriterUnique(outputStream);
            ((GraphQuery) q).evaluate(rdfXmlWriter);
        }
    } catch (MalformedQueryException e) {
        /* Report errors using HTTP 400 Bad Request and provide error details */
        //response.setStatus(400);
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.write("Unable to parse query: " + e.getMessage());
        printWriter.close();
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (RepositoryException e) {
                e.printStackTrace();
            }
    }
}

From source file:gate.crowdsource.rest.CrowdFlowerClient.java

protected JsonElement request(String method, String uri, String... formData) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("URI: " + uri + ", formData: " + Arrays.toString(formData));
    }/*from  ww w . j  a  va2 s.  c om*/
    URL cfUrl = new URL(CF_ENDPOINT + uri + "?key=" + apiKey);
    HttpURLConnection connection = (HttpURLConnection) cfUrl.openConnection();
    connection.setRequestMethod(method);
    connection.setRequestProperty("Accept", "application/json");
    if (formData != null && formData.length > 0) {
        // send the form data, URL encoded
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // annoyingly CrowdFlower doesn't support chunked streaming of
        // POSTs so we have to accumulate the content in a buffer, work
        // out its size and then POST with a Content-Length header
        ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8"));
        try {
            for (int i = 0; i < formData.length; i++) {
                String fieldName = formData[i];
                String fieldValue = formData[++i];
                if (i > 0) {
                    writer.write("&");
                }
                writer.write(URLEncoder.encode(fieldName, "UTF-8"));
                writer.write("=");
                writer.write(URLEncoder.encode(fieldValue, "UTF-8"));
            }
        } finally {
            writer.close();
        }

        connection.setFixedLengthStreamingMode(buffer.size());
        OutputStream connectionStream = connection.getOutputStream();
        buffer.writeTo(connectionStream);
        connectionStream.close();
    }

    // parse the response as JSON
    JsonParser parser = new JsonParser();
    Reader responseReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
    try {
        return parser.parse(responseReader);
    } finally {
        responseReader.close();
    }
}