Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

In this page you can find the example usage for java.io OutputStreamWriter flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

public XMLElement getXmlElement(final StartElement start, final XMLEventReader reader) throws Exception {

    final XMLElement res = new XMLElement();
    res.setStart(start);//from   w  w  w  .j  a  v  a  2  s .  com

    final Charset encoding = Charset.forName(org.apache.olingo.commons.api.Constants.UTF8);
    final ByteArrayOutputStream content = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(content, encoding);

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            depth--;
        }

        if (depth == 0) {
            res.setEnd(event.asEndElement());
        } else {
            event.writeAsEncodedUnicode(writer);
        }
    }

    writer.flush();
    writer.close();

    res.setContent(new ByteArrayInputStream(content.toByteArray()));

    return res;
}

From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java

ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points,
        IntersectCallback callback) {//from  w w w  . ja v a  2 s .c  o m
    logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount()
            + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length);

    ArrayList<String> output = null;

    try {
        long start = System.currentTimeMillis();
        URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch");
        URLConnection c = url.openConnection();
        c.setDoOutput(true);

        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(c.getOutputStream());
            out.write("fids=");
            for (int i = 0; i < intersectionFiles.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(intersectionFiles[i].getFieldId());
            }
            out.write("&points=");
            for (int i = 0; i < points.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(String.valueOf(points[i][1]));
                out.write(",");
                out.write(String.valueOf(points[i][0]));
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream()));

        String checkUrl = jo.getString("statusUrl");

        //check status
        boolean notFinished = true;
        String downloadUrl = null;
        while (notFinished) {
            //wait 5s before querying status
            Thread.sleep(5000);

            jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream()));

            if (jo.containsKey("error")) {
                notFinished = false;
            } else if (jo.containsKey("status")) {
                String status = jo.getString("status");

                if ("finished".equals(status)) {
                    downloadUrl = jo.getString("downloadUrl");
                    notFinished = false;
                } else if ("cancelled".equals(status) || "error".equals(status)) {
                    notFinished = false;
                }
            }
        }

        ZipInputStream zis = null;
        CSVReader csv = null;
        InputStream is = null;
        ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>();
        long mid = System.currentTimeMillis();
        try {
            is = new URI(downloadUrl).toURL().openStream();
            zis = new ZipInputStream(is);
            ZipEntry ze = zis.getNextEntry();
            csv = new CSVReader(new InputStreamReader(zis));

            for (int i = 0; i < intersectionFiles.length; i++) {
                tmpOutput.add(new StringBuilder());
            }
            String[] line;
            int row = 0;
            csv.readNext(); //discard header
            while ((line = csv.readNext()) != null) {
                //order is consistent with request
                for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) {
                    if (row > 0) {
                        tmpOutput.get(i - 2).append("\n");
                    }
                    tmpOutput.get(i - 2).append(line[i]);
                }
                row++;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (csv != null) {
                try {
                    csv.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        output = new ArrayList<String>();
        for (int i = 0; i < tmpOutput.size(); i++) {
            output.add(tmpOutput.get(i).toString());
            tmpOutput.set(i, null);
        }

        long end = System.currentTimeMillis();

        logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start)
                + "ms, write response=" + (end - mid) + "ms");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return output;
}

From source file:com.sun.faces.systest.ant.SystestClient.java

/**
 * Validate the response against the golden file (if any), skipping the
 * comparison on any golden file line that is also in the ignore file
 * (if any).  Return <code>null</code> for no problems, or an error
 * message./*from   w  w  w  . j  av a 2 s  . co  m*/
 */
protected String validateGolden() {

    if (golden == null) {
        return (null);
    }
    boolean ok = true;
    if (saveGolden.size() != saveResponse.size()) {
        ok = false;
    }
    if (ok) {
        for (int i = 0, size = saveGolden.size(); i < size; i++) {
            String golden = (String) saveGolden.get(i);
            String response = (String) saveResponse.get(i);
            if (!validateIgnore(golden) && !golden.equals(response)) {
                response = stripJsessionidFromLine(response);
                golden = stripJsessionidFromLine(golden);
                if (!golden.equals(response)) {
                    ok = false;
                    break;
                }
            }
        }
    }
    if (ok) {
        return (null);
    }
    System.out.println("EXPECTED: ======================================");
    for (int i = 0, size = saveGolden.size(); i < size; i++) {
        System.out.println((String) saveGolden.get(i));
    }
    System.out.println("================================================");
    if (saveIgnore.size() >= 1) {
        System.out.println("IGNORED: =======================================");
        for (int i = 0, size = saveIgnore.size(); i < size; i++) {
            System.out.println((String) saveIgnore.get(i));
        }
        System.out.println("================================================");
    }
    System.out.println("RECEIVED: ======================================");
    for (int i = 0, size = saveResponse.size(); i < size; i++) {
        System.out.println((String) saveResponse.get(i));
    }
    System.out.println("================================================");

    // write the goldenfile if the GF size from the server was 0
    // and the goldenfile doesn't already exist on the local filesystem.
    if (recordGolden != null) {
        File gf = new File(recordGolden);
        if (!gf.exists()) {
            System.out.println("[INFO] RECORDING GOLDENFILE: " + recordGolden);
            // write the goldenfile using the encoding specified in the response.
            // if there is no encoding available, default to ISO-8859-1
            String encoding = "ISO-8859-1";
            if (saveHeaders.containsKey("content-type")) {
                List vals = (List) saveHeaders.get("content-type");
                if (vals != null) {
                    String val = (String) vals.get(0);
                    int charIdx = val.indexOf('=');
                    if (charIdx > -1) {
                        encoding = val.substring(charIdx + 1).trim();
                    }
                }
            }
            OutputStreamWriter out = null;
            try {
                out = new OutputStreamWriter(new FileOutputStream(gf), encoding);
                for (int i = 0, size = saveResponse.size(); i < size; i++) {
                    out.write((String) saveResponse.get(i));
                    out.write('\n');
                }
                out.flush();
            } catch (Throwable t) {
                System.out.println("[WARNING] Unable to write goldenfile: " + t.toString());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ioe) {
                    ; // do nothing
                }
            }
        }
    }
    return ("Failed Golden File Comparison");

}

From source file:launcher.net.CustomIOUtils.java

/**
 * Copy chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code> using the specified character encoding, and
 * calling flush.//from   www . j av a 2 s .co m
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * </p>
 * <p>
 * Due to the implementation of OutputStreamWriter, this method performs a
 * flush.
 * </p>
 * <p>
 * This method uses {@link OutputStreamWriter}.
 * </p>
 *
 * @param input  the <code>Reader</code> to read from
 * @param output  the <code>OutputStream</code> to write to
 * @param encoding  the encoding to use, null means platform default
 * @throws NullPointerException if the input or output is null
 * @throws IOException if an I/O error occurs
 * @since 2.3
 */
public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(output, Charsets.toCharset(encoding));
    copy(input, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter,
    // we have to flush here.
    out.flush();
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

public MemoryFileDTO createFileLabelsTXT(final Collection<LabelDTO> labels) {
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName(new Date().getTime() + ".txt");
    try {//from w ww  .jav  a 2 s.  c  o  m
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        PrintWriter out = new PrintWriter(writer, true);
        for (LabelDTO ldto : labels) {
            out.println("Tombo");
            out.println(ldto.getAssetHolding());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Autor");
            out.println(ldto.getAuthor());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Titulo");
            out.println(ldto.getTitle());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Loc. A");
            out.println(ldto.getLocationA());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Loc. B");
            out.println(ldto.getLocationB());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Loc. C");
            out.println(ldto.getLocationC());
            writer.write(ApplicationConstants.LINE_BREAK);
            out.println("Loc. D");
            out.println(ldto.getLocationD());
            out.println("---------------------------------|");
        }
        writer.flush();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception e) {
        e.getMessage();
    }
    return file;
}

From source file:eionet.cr.web.util.TriplesToOutputStream.java

/**
 *
 * @param out//from  w  w w .  ja v a  2 s  .c  o m
 * @param subjectUri
 * @param triples
 */
public static void triplesToRdf(OutputStream out, String subjectUri, List<SubjectDTO> triples) {
    OutputStreamWriter writer = new OutputStreamWriter(out);
    try {
        if (triples != null) {
            writer.append(RDF_HEADER);
            writer.append("<rdf:RDF xmlns=\"").append(subjectUri + "#").append("\" xmlns:rdf=\"")
                    .append(RDF_NAMESPACE).append("\" ").append("xmlns:rdfs=\"").append(RDFS_NAMESPACE)
                    .append("\">");
            for (SubjectDTO subject : triples) {

                writer.append("<rdf:Description rdf:about=\"")
                        .append(StringEscapeUtils.escapeXml(subject.getUri())).append("\">");
                Map<String, Collection<ObjectDTO>> predicates = subject.getPredicates();
                if (predicates != null) {
                    for (String predicateUri : predicates.keySet()) {
                        Collection<ObjectDTO> objects = predicates.get(predicateUri);

                        // Shorten predicate URIs
                        if (predicateUri.startsWith(RDF_NAMESPACE)) {
                            predicateUri = predicateUri.replace(RDF_NAMESPACE, "rdf:");
                        } else if (predicateUri.startsWith(RDFS_NAMESPACE)) {
                            predicateUri = predicateUri.replace(RDFS_NAMESPACE, "rdfs:");
                        } else if (predicateUri.startsWith(subjectUri)) {
                            predicateUri = predicateUri.replace(subjectUri + "#", "");
                        }

                        if (objects != null) {
                            for (ObjectDTO object : objects) {
                                if (object.isLiteral()) {
                                    writer.append("<").append(predicateUri).append(">")
                                            .append(StringEscapeUtils.escapeXml(object.getValue())).append("</")
                                            .append(predicateUri).append(">");
                                } else {
                                    writer.append("<").append(predicateUri).append(" rdf:resource=\"")
                                            .append(StringEscapeUtils.escapeXml(object.getValue()))
                                            .append("\"/>");
                                }
                            }
                        }
                    }
                }
                writer.append("</rdf:Description>");
            }
            writer.append("</rdf:RDF>");
            writer.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.trm.tasks.AjaxSuiteSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyPermissions(request);/*from ww w.j  a v  a  2  s .  c om*/

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    String rootId = rId;
    if (rId.equals("mytasks0"))
        rootId = "0";

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rootId + "\" >");

    User user = getUser(request);

    List<TrmSuite> suites = null;
    if (rId.startsWith("mytasks")) {
        Long projectId = null;
        String strProjectId = request.getParameter("projectId");
        if (strProjectId != null) {
            projectId = Long.parseLong(strProjectId);
        }

        // Displaying a list of all user tasks
        List<TrmTask> tasks = trmDAO.getUserTasks(user.getId(), projectId);
        for (TrmTask task : tasks) {
            w.write("<item text=\"" + XmlUtils.escapeXml(task.getName()) + "\" " + "id=\"t" + task.getId()
                    + "\" " + "im0=\"iconTask.png\" im1=\"iconTask.png\" im2=\"iconTask.png\" child=\"1\" "
                    + " nocheckbox=\"1\" >");
            w.write("</item>");
        }
    } else if (rId.startsWith("t")) {
        Long taskId = Long.parseLong(rId.substring(1));
        suites = trmDAO.getTaskSuites(taskId);
    }

    if (suites != null) {
        for (TrmSuite suite : suites) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(suite.getName()) + "\" ");
            w.write("id=\"suite" + suite.getId() + "\" ");
            w.write("im0=\"workflow-icon-suite.png\" im1=\"workflow-icon-suite.png\" im2=\"workflow-icon-suite.png\" ");

            w.write(">");
            w.write("</item>");
        }
    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) {
    HttpURLConnection urlConnection = null;
    URL myurl = null;//  w ww  .  j a  v a 2 s .  c o  m
    OutputStreamWriter wr = null;
    int responseCode = 0;
    String id = null;
    int error = 0;

    try {
        myurl = new URL(url_str + command);
        urlConnection = (HttpURLConnection) myurl.openConnection();
        urlConnection.setRequestMethod(msgtype);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
        urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76");
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

        wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
        wr.write(payload);
        wr.flush();

        responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn(
                    "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype);
            error = 1;
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e);
        error = 1;
    } finally {
        if (urlConnection != null) {
            try {
                if (error > 0) {
                    InputStream err = urlConnection.getErrorStream();
                    String errString = convertStreamToString(err);
                    logger.warn("Reported error : " + errString);
                    IoUtils2.closeQuietly(err);
                } else {
                    InputStream in = urlConnection.getInputStream();
                    String theString = convertStreamToString(in);
                    id = jparse(theString, ExpectInt);
                    IoUtils2.closeQuietly(in);
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command : flushing http connection " + e);
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command: closing OutputWriter " + e);
            }
        }
    }
    return (id);
}

From source file:com.tomagoyaky.jdwp.IOUtils.java

/**
 * Copies chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code> using the specified character encoding, and
 * calling flush.//  w  w  w. j  a va 2s.com
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * </p>
 * <p>
 * Due to the implementation of OutputStreamWriter, this method performs a
 * flush.
 * </p>
 * <p>
 * This method uses {@link OutputStreamWriter}.
 * </p>
 *
 * @param input the <code>Reader</code> to read from
 * @param output the <code>OutputStream</code> to write to
 * @param outputEncoding the encoding to use for the OutputStream, null means platform default
 * @throws NullPointerException if the input or output is null
 * @throws IOException          if an I/O error occurs
 * @since 2.3
 */
public static void copy(final Reader input, final OutputStream output, final Charset outputEncoding)
        throws IOException {
    final OutputStreamWriter out = new OutputStreamWriter(output, Charsets.toCharset(outputEncoding));
    copy(input, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter,
    // we have to flush here.
    out.flush();
}

From source file:com.fluidops.iwb.widget.ImportRDFWidget.java

private FButton createRefineButton(final FTextInput2 context, final FTextInput2 baseURI, final FContainer stat,
        final FTextInput2 project, final FTextInput2 refineFormat, final FTextInput2 refineURL,
        final FTextInput2 engine, final FCheckBox keepSourceCtx, final FCheckBox contextEditable) {
    return new FButton("refineButton", "Import RDF Data") {
        @Override//from  w ww .  j a  va2s . c o m
        public void onClick() {

            try {
                getBasicInput(context, baseURI);
            } catch (Exception e) {
                stat.hide(true);
                logger.info(e.getMessage());
                return;
            }

            if (engine.getInput().length() > 0 && project.getInput().length() > 0
                    && refineFormat.getInput().length() > 0 && refineURL.getInput().length() > 0) {
                Map<String, String> parameter = new HashMap<String, String>();
                parameter.put(engine.getName(), engine.getInput());
                parameter.put(project.getName(), project.getInput());
                parameter.put(refineFormat.getName(), refineFormat.getInput());
                URL urlValue = null;
                try {
                    urlValue = new URL(refineURL.getInput());
                } catch (MalformedURLException e) {
                    stat.hide(true);

                    getPage().getPopupWindowInstance().showError(refineURL.getInput() + " is not a valid URL");
                    logger.error(e.getMessage(), e);
                    return;
                }
                OutputStreamWriter wr = null;
                InputStream input = null;
                try {
                    // Collect the request parameters
                    StringBuilder params = new StringBuilder();
                    for (Entry<String, String> entry : parameter.entrySet())
                        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                                .append(StringUtil.urlEncode(entry.getValue())).append("&");

                    // Send data
                    URLConnection urlcon = urlValue.openConnection();
                    urlcon.setDoOutput(true);
                    wr = new OutputStreamWriter(urlcon.getOutputStream());
                    wr.write(params.toString());
                    wr.flush();

                    // Get the response
                    input = urlcon.getInputStream();
                    importData(this, input, baseUri, RDFFormat.RDFXML, contextUri, "Open Refine",
                            keepSourceCtx.getChecked(), contextEditable.getChecked());

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    getPage().getPopupWindowInstance().showError(e.getMessage());

                } finally {
                    stat.hide(true);
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(wr);
                }
            } else {
                stat.hide(true);
                getPage().getPopupWindowInstance().showError("All marked fields should be filled out");
            }
        }
    };
}