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:edu.utsa.sifter.IndexResource.java

@Path("exporthitsFeatures")
@GET//from   w  ww .  j  av a 2s  .c om
@Produces({ "text/csv" })
public StreamingOutput getHitExportFeatures(@QueryParam("id") final String searchID)
        throws IOException, InterruptedException, ExecutionException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;
    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<SearchHit> hits = results.getSearchHits();
        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Start,End,Snippet,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (SearchHit hit : hits) {
                        if (markStore != null) {
                            markStore.executeQuery(parseQuery(hit.ID(), "Docs"));
                            final ArrayList<Bookmark> marks = markStore.retrieve();
                            if (marks == null) {
                                writeHitRecord(hit, null, writer);
                                ++n;
                            } else {
                                for (Bookmark mark : marks) {
                                    writeHitRecord(hit, mark, writer);
                                    ++n;
                                }
                            }
                        } else {
                            writeHitRecord(hit, null, writer);
                            ++n;
                        }
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:org.apache.olingo.fit.AbstractServices.java

/**
 * Retrieve property sample.//from  w  w w  .j ava 2 s  .  com
 *
 * @param accept Accept header.
 * @param entitySetName Entity set name.
 * @param entityId entity id.
 * @param path path.
 * @param format format query option.
 * @return property.
 */
@GET
@Path("/{entitySetName}({entityId})/{path:.*}")
public Response getPath(@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @PathParam("entitySetName") final String entitySetName, @PathParam("entityId") final String entityId,
        @PathParam("path") final String path,
        @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

    // default utilities
    final AbstractUtilities utils = xml;

    try {
        if (utils.isMediaContent(entitySetName + "/" + path)) {
            return navigateStreamedEntity(entitySetName, entityId, path);
        } else {
            Accept acceptType = null;
            if (StringUtils.isNotBlank(format)) {
                acceptType = Accept.valueOf(format.toUpperCase());
            } else if (StringUtils.isNotBlank(accept)) {
                acceptType = Accept.parse(accept, version, null);
            }

            try {
                final LinkInfo linkInfo = xml.readLinks(entitySetName, entityId, path, Accept.XML);
                final Map.Entry<String, List<String>> links = xml.extractLinkURIs(linkInfo.getLinks());
                final InputStream stream = xml.readEntities(links.getValue(), path, links.getKey(),
                        linkInfo.isFeed());

                final ByteArrayOutputStream content = new ByteArrayOutputStream();
                final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);

                final ResWrap<?> container = linkInfo.isFeed() ? atomDeserializer.toEntitySet(stream)
                        : atomDeserializer.toEntity(stream);
                if (acceptType == Accept.ATOM) {
                    atomSerializer.write(writer, container);
                } else {
                    jsonSerializer.write(writer, container);
                }
                writer.flush();
                writer.close();

                final String basePath = Commons.getEntityBasePath(entitySetName, entityId);

                return xml.createResponse(null, new ByteArrayInputStream(content.toByteArray()),
                        Commons.getETag(basePath, version), acceptType);

            } catch (NotFoundException e) {
                // if the given path is not about any link then search for property
                return navigateProperty(acceptType, entitySetName, entityId, path, false);
            }
        }
    } catch (Exception e) {
        return utils.createFaultResponse(accept, e);
    }
}

From source file:edu.utsa.sifter.IndexResource.java

@Path("exportDocFeatures")
@GET//from  www. j a va 2s  . c o m
@Produces({ "text/csv" })
public StreamingOutput getDocExportFeatures(@QueryParam("id") final String searchID) throws IOException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;

    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<Result> docs = results.retrieve(0, results.TotalHits);

        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (Result doc : docs) {
                        for (double feat : feats) {
                            if (markStore != null) {
                                markStore.executeQuery(parseQuery(doc.ID, "Docs"));
                                final ArrayList<Bookmark> marks = markStore.retrieve();

                                if (marks == null) {
                                    writeDocRecordFeatures(doc, null, writer, feat);
                                    ++n;
                                } else {
                                    for (Bookmark mark : marks) {
                                        writeDocRecordFeatures(doc, mark, writer, feat);
                                        ++n;
                                    }
                                }
                            } else {
                                writeDocRecordFeatures(doc, null, writer, feat);
                                ++n;
                            }
                        } // feature loop
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:geotheme.servlet.wms.java

/**
 * @see HttpServlet#service(HttpServletRequest req, HttpServletResponse res)
 *//*from  w w  w  .  ja  v a2 s  . co  m*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    OutputStreamWriter wr = null;
    InputStream in = null;
    OutputStream out = null;

    //req.setCharacterEncoding("UTF-8");

    try {
        Map<String, Object> reqMap = new HashMap<String, Object>();

        Enumeration<?> en = req.getParameterNames();
        String key = new String();

        /**
         * Converting all Map Keys into Upper Case
         **/
        while (en.hasMoreElements()) {
            key = (String) en.nextElement();
            reqMap.put(key.toUpperCase(), req.getParameter(key));
        }

        wmsParamBean wmsBean = new wmsParamBean();
        BeanUtils.populate(wmsBean, reqMap);

        HttpSession session = req.getSession(true);

        /**
         * Reading the saved SLD
         **/
        String sessionName = wmsBean.getLAYER();

        if (sessionName.length() < 1)
            sessionName = wmsBean.getLAYERS();

        if (session.getAttribute(sessionName) != null) {

            wmsBean.setSLD_BODY((String) session.getAttribute(sessionName));
            wmsBean.setSLD("");
            wmsBean.setSTYLES("");
        }

        if (wmsBean.getREQUEST().compareToIgnoreCase("GetPDFGraphic") == 0) {
            /**
             * Generate PDF Request
             */
            generatePDF pdf = new generatePDF(this.pdfURL, this.pdfLayers);

            ByteArrayOutputStream baos = pdf.createPDFFromImage(wmsBean, this.geoserverURL);

            res.addHeader("Content-Type", "application/force-download");
            res.addHeader("Content-Disposition", "attachment; filename=\"MapOutput.pdf\"");

            res.getOutputStream().write(baos.toByteArray());
        } else {
            /**
             * Generating Map from GeoServer
             **/
            URL geoURL = new URL(this.geoserverURL);

            URLConnection geoConn = geoURL.openConnection();
            geoConn.setDoOutput(true);

            wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
            wr.write(wmsBean.getURL_PARAM());
            wr.flush();

            in = geoConn.getInputStream();
            out = res.getOutputStream();

            res.setContentType(wmsBean.getFORMAT());

            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
        if (wr != null) {
            wr.close();
        }
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventWriter writer = xof.createXMLEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3,
            false);//from   ww w.  j av a2s. c  om

    writer.flush();

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = getAtomElement(propertyReader, null, null);
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = xof.createXMLEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton(
                        new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

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

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = xof.createXMLEventWriter(bos);

    propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

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

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

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

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

    OutputStreamWriter w = new OutputStreamWriter(os);

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

    if (rId.equals("0")) {
        w.write("<item text=\"My Tasks\" " + "id=\"mytasks\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
        w.write("<item text=\"Shared Tasks\" " + "id=\"shared\" "
                + "im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                + " nocheckbox=\"1\" >");
        w.write("</item>");
    } else {
        User user = getUser(request);

        Collection<TrmTask> tasks = null;
        Long projectId = null;
        String strProject = request.getParameter("projectId");
        if (strProject != null) {
            projectId = Long.parseLong(strProject);
        }

        if (rId.equals("mytasks")) {
            tasks = trmDAO.getUserTasks(user.getId(), projectId);

        } else if (rId.equals("shared")) {
            Collection<User> users = trmDAO.getUsersWithSharedTasks(user.getId(), projectId);
            for (User u : users) {
                w.write("<item text=\"" + XmlUtils.escapeXml(u.getName()) + "\" " + "id=\"u" + u.getId() + "\" "
                        + "im0=\"workflow-icon-user.png\" im1=\"workflow-icon-user.png\" im2=\"workflow-icon-user.png\" child=\"1\" "
                        + " nocheckbox=\"1\" >");
                w.write("</item>");
            }
        } else if (rId.startsWith("u")) {
            Long userId = Long.parseLong(rId.substring(1));
            tasks = trmDAO.getUserSharedTasks(userId, projectId);
        }

        if (tasks != null) {
            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=\"0\" "
                        + " >");
                w.write("</item>");
            }
        }

    }

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

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

/**
 *
 * @param out//from   w  w  w.  j  a v a  2  s .  c  o  m
 * @param subjectUri
 * @param triples
 */
public static void triplesToHtml(OutputStream out, String subjectUri, List<SubjectDTO> triples) {

    OutputStreamWriter writer = new OutputStreamWriter(out);
    try {
        writer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-gb\">");
        writer.append("<head>");
        writer.append("<title>").append(subjectUri).append("</title>");
        writer.append("<link rel=\"alternate\" type=\"application/rdf+xml\" href=\"").append(subjectUri)
                .append("\" />");
        writer.append("<style type=\"text/css\">" + "/*<![CDATA[*/ "
                + "table { border: 1px solid black; border-collapse:collapse; } "
                + "td, th { border: 1px solid black; padding: 0.3em; } " + "/*]]>*/" + "</style>");
        writer.append("</head>");
        writer.append("<body>");
        writer.append("<h1>").append(subjectUri).append("</h1>");
        writer.append("<table>");
        writer.append("<tr><th>Subject</th><th>Predicate</th><th>Value</th></tr>");

        if (triples != null) {
            for (SubjectDTO subject : triples) {
                Map<String, Collection<ObjectDTO>> predicates = subject.getPredicates();
                if (predicates != null) {
                    for (String predicateUri : predicates.keySet()) {
                        Collection<ObjectDTO> objects = predicates.get(predicateUri);
                        if (objects != null) {
                            for (ObjectDTO object : objects) {
                                writer.append("<tr>");
                                writer.append("<td>");
                                writer.append("<a href=\"").append(subject.getUri()).append("\">");
                                writer.append(subject.getUri());
                                writer.append("</a>");
                                writer.append("</td>");
                                writer.append("<td>").append(predicateUri).append("</td>");
                                writer.append("<td>");
                                if (object.isLiteral()) {
                                    writer.append(object.getValue());
                                } else {
                                    writer.append("<a href=\"").append(object.getValue()).append("\">")
                                            .append(object.getValue()).append("</a>");
                                }
                                writer.append("</td>");
                                writer.append("</tr>");
                            }
                        }
                    }
                }
            }
            /*
             * for (TripleDTO triple : triples) { writer.append("<tr>");
             * writer.append("<td>").append(triple.getSubjectUri()).append("</td>");
             * writer.append("<td>").append(triple.getPredicateUri()).append("</td>");
             * writer.append("<td>").append(triple.getObject()).append("</td>"); writer.append("</tr>"); }
             */
        }
        writer.append("</table>");
        writer.append("</body>");
        writer.append("</html>");
        writer.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:openscience.crowdsource.experiments.MainActivity.java

/*************************************************************************/
/* read one string file */
private boolean save_one_string_file(String fname, String text) {

    FileOutputStream o = null;// w  w w.j a v a2s .  c  o  m
    try {
        o = new FileOutputStream(fname, false);
    } catch (FileNotFoundException e) {
        return false;
    }

    OutputStreamWriter oo = new OutputStreamWriter(o);

    try {
        oo.append(text);
        oo.flush();
        oo.close();
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:au.org.ala.names.search.ALANameSearcher.java

/**
 * Dumps a list of the species LSID's that are contained in the index.
 *//*from  ww  w.jav a  2s.c om*/
public void dumpSpecies() {
    try {
        OutputStreamWriter fileOut = new OutputStreamWriter(new FileOutputStream("/data/species.txt"), "UTF-8");
        Term term = new Term("rank", "species");
        TopDocs hits = cbSearcher.search(new TermQuery(term), 2000000);

        for (ScoreDoc sdoc : hits.scoreDocs) {
            Document doc = cbReader.document(sdoc.doc);

            if (doc.getField("synonym") == null) {
                String lsid = StringUtils.trimToNull(doc.getField("lsid").stringValue());
                if (lsid == null)
                    lsid = doc.getField("id").stringValue();
                fileOut.write(lsid + "\n");
            }

        }
        fileOut.flush();

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

}

From source file:com.cloud.bridge.service.EC2RestServlet.java

/**
* Send out an error response according to Amazon convention.
 *///w ww.  java 2 s .  co  m
private void faultResponse(HttpServletResponse response, String errorCode, String errorMessage) {
    try {
        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
        response.setContentType("text/xml; charset=UTF-8");
        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.write("<Response><Errors><Error><Code>");
        out.write(errorCode);
        out.write("</Code><Message>");
        out.write(errorMessage);
        out.write("</Message></Error></Errors><RequestID>");
        out.write(UUID.randomUUID().toString());
        out.write("</RequestID></Response>");
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.error("Unexpected exception " + e.getMessage(), e);
    }
}