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.gbif.portal.web.controller.dataset.LogQuery.java

/**
 * Output log stats to the supplied output stream.
 * /*from  w w w  .  j ava2s  . c o  m*/
 * @param outputStream
 * @param logStats
 * @throws ServiceException
 * @throws ResourceNotFoundException
 * @throws ParseErrorException
 * @throws Exception
 * @throws MethodInvocationException
 * @throws IOException
 */
public void outputLogStats(OutputStream outputStream, List<LogStatsDTO> logStats) throws ServiceException,
        ResourceNotFoundException, ParseErrorException, Exception, MethodInvocationException, IOException {
    if (outputStream instanceof ZipOutputStream) {
        //FIXME 
        ((ZipOutputStream) outputStream).putNextEntry(new ZipEntry(getFileName()));
    }

    DataProviderDTO dataProvider = null;
    //get totals for providers
    if (providerKey != null) {
        dataProvider = dataResourceManager.getDataProviderFor(providerKey);
    }
    Map<Integer, LogStatsDTO> eventIdProviderStats = new HashMap<Integer, LogStatsDTO>();
    for (LogStatsDTO logStat : logStats) {
        LogStatsDTO providerLogStats = eventIdProviderStats.get(logStat.getEventId());
        if (providerLogStats == null) {
            providerLogStats = new LogStatsDTO();
            //get the provider for this key
            if (dataProvider == null) {
                DataResourceDTO dataResource = dataResourceManager.getDataResourceFor(logStat.getEntityKey());
                providerLogStats.setEntityKey(dataResource.getDataProviderKey());
                providerLogStats.setEntityName(dataResource.getDataProviderName());
            } else {
                providerLogStats.setEntityKey(dataProvider.getKey());
                providerLogStats.setEntityName(dataProvider.getName());
            }
            providerLogStats.setEventId(logStat.getEventId());
            providerLogStats.setEventName(logStat.getEventName());
            providerLogStats.setEventCount(new Integer(0));
            eventIdProviderStats.put(providerLogStats.getEventId(), providerLogStats);
        }
        if (logStat.getEventCount() != null) {
            providerLogStats.setEventCount(providerLogStats.getEventCount() + logStat.getEventCount());
        }
        if (logStat.getCount() != null) {
            if (providerLogStats.getCount() == null) {
                providerLogStats.setCount(logStat.getCount());
            } else {
                providerLogStats.setCount(providerLogStats.getCount() + logStat.getCount());
            }
        }
    }

    //write out log stats
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("logQuery", this);
    velocityContext.put("date", new DateFormatUtils());
    if (eventIdProviderStats != null) {
        List<LogStatsDTO> providerStats = new ArrayList<LogStatsDTO>();
        for (Integer key : eventIdProviderStats.keySet()) {
            providerStats.add(eventIdProviderStats.get(key));
        }

        //sort by event id
        Collections.sort(providerStats, new Comparator<LogStatsDTO>() {
            public int compare(LogStatsDTO ls1, LogStatsDTO ls2) {
                if (!ls1.getEntityName().equals(ls2.getEntityName())) {
                    return ls1.getEntityKey().compareTo(ls2.getEntityName());
                } else {
                    return ls1.getEventId().compareTo(ls2.getEventId());
                }
            }

        });
        velocityContext.put("dataProviderStats", providerStats);
    }

    //provider key
    if (dataProvider != null) {
        velocityContext.put("dataProvider", dataProvider);
    }

    velocityContext.put("dataResourceStats", logStats);
    Template template = Velocity.getTemplate("org/gbif/portal/io/logMessageStats.vm");
    template.initDocument();

    //add formatter
    LogEventField lef = new LogEventField();
    lef.setFieldName("record.eventId");
    List<Field> downloadFields = new ArrayList<Field>();
    downloadFields.add(lef);
    FieldFormatter ff = new FieldFormatter(downloadFields, messageSource, null, null);
    velocityContext.put("propertyFormatter", ff);

    TemplateUtils tu = new TemplateUtils();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    tu.merge(template, velocityContext, writer);
    writer.flush();

    //FIXME this is cheating....
    if (outputStream instanceof ZipOutputStream) {
        addTemplate(outputStream, velocityContext, tu, "org/gbif/portal/io/logMessageStatsHTML.vm",
                "log-statistics.html");
        addTemplate(outputStream, velocityContext, tu, "org/gbif/portal/io/logMessageReadme.vm", "README.txt");
    }
}

From source file:org.exist.xquery.modules.httpclient.POSTFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;/*w  w w .  j av  a 2  s . c  om*/

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the payload

    Item payload = args[1].itemAt(0);

    //get the persist state
    boolean persistState = args[2].effectiveBooleanValue();

    PostMethod post = new PostMethod(url);

    if (isCalledAs("post")) {
        RequestEntity entity = null;

        if (Type.subTypeOf(payload.getType(), Type.NODE)) {

            //serialize the node to SAX
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStreamWriter osw = null;

            try {
                osw = new OutputStreamWriter(baos, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw (new XPathException(this, e.getMessage()));
            }

            SAXSerializer sax = new SAXSerializer(osw, new Properties());

            try {
                payload.toSAX(context.getBroker(), sax, new Properties());
                osw.flush();
                osw.close();
            } catch (Exception e) {
                throw (new XPathException(this, e.getMessage()));
            }

            byte[] reqPayload = baos.toByteArray();
            entity = new ByteArrayRequestEntity(reqPayload, "application/xml; charset=utf-8");
        } else {

            try {
                entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8");
            } catch (UnsupportedEncodingException uee) {
                uee.printStackTrace();
            }
        }

        post.setRequestEntity(entity);
    } else if (isCalledAs("post-form")) {
        Node nPayload = ((NodeValue) payload).getNode();

        if ((nPayload instanceof Element) && nPayload.getNamespaceURI().equals(HTTPClientModule.NAMESPACE_URI)
                && nPayload.getLocalName().equals("fields")) {
            Part[] parts = parseFields((Element) nPayload);
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        } else {
            throw (new XPathException(this, "fields must be provided"));
        }

    } else {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //setup POST Request Headers
    if (!args[3].isEmpty()) {
        setHeaders(post, ((NodeValue) args[3].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, post, persistState, null, null);

    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        post.releaseConnection();
    }

    return (response);
}

From source file:org.spiffyui.server.AuthServlet.java

private void doLogout(HttpServletRequest request, HttpServletResponse response, String token, String tsUrl)
        throws ServletException, IOException {
    if (token == null || tsUrl == null) {
        returnError(response, "Logout requires a token and a token server URL",
                RESTAuthConstants.INVALID_LOGOUT_REQUEST);
        return;/*from  w ww. j  ava 2s. com*/
    }

    LOGGER.info("Making logout request for " + token + " to server " + tsUrl);

    try {
        validateURI(request, tsUrl);
    } catch (IllegalArgumentException iae) {
        returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL);
        return;
    }

    HttpClient httpclient = new DefaultHttpClient();

    URI.create(tsUrl);
    URL url = new URL(tsUrl);

    LOGGER.info("url: " + url);

    if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("https")) {
        setupClientSSL(httpclient, url.getPort());
    }

    HttpDelete httpdel = new HttpDelete(tsUrl + "/" + URLEncoder.encode(token, "UTF-8"));

    httpdel.setHeader("Accept", "application/json");
    httpdel.setHeader("Accept-Charset", "UTF-8");
    httpdel.setHeader("Authorization", request.getHeader("Authorization"));
    httpdel.setHeader("TS-URL", request.getHeader("TS-URL"));

    // Execute the request
    HttpResponse authResponse = httpclient.execute(httpdel);

    int status = authResponse.getStatusLine().getStatusCode();
    if (status == 404) {
        LOGGER.info("The authentication server " + tsUrl + " was not found.");
        returnError(response, "The token server URL was not found", RESTAuthConstants.NOTFOUND_TS_URL);
        return;
    }

    // Get hold of the response entity
    HttpEntity entity = authResponse.getEntity();

    StringBuffer authResponseData = new StringBuffer();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(instream));

            // do something useful with the response
            authResponseData.append(reader.readLine());
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpdel.abort();
            LOGGER.throwing(AuthServlet.class.getName(), "doLogout", ex);
            throw ex;
        } finally {
            // Closing the input stream will trigger connection release
            if (reader != null) {
                reader.close();
            }
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    //Now we write the response back to our client.
    response.setStatus(status);
    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
    out.write(authResponseData.toString());

    out.flush();
    out.close();
}

From source file:org.apache.maven.plugin.surefire.report.StatelessXmlReporter.java

private void addOutputStreamElement(OutputStreamWriter outputStreamWriter, OutputStream fw,
        EncodingOutputStream eos, XMLWriter xmlWriter, DeferredFileOutputStream stdOut, String name) {
    if (stdOut != null && stdOut.getByteCount() > 0) {

        xmlWriter.startElement(name);//  w  w  w .j a  v  a 2  s.c o  m

        try {
            xmlWriter.writeText(""); // Cheat sax to emit element
            outputStreamWriter.flush();
            stdOut.close();
            eos.getUnderlying().write("<![CDATA[".getBytes()); // emit cdata
            stdOut.writeTo(eos);
            eos.getUnderlying().write("]]>".getBytes());
            eos.flush();
        } catch (IOException e) {
            throw new ReporterException("When writing xml report stdout/stderr", e);
        }
        xmlWriter.endElement();
    }
}

From source file:com.cloudbees.jenkins.support.api.FileContent.java

@Override
public void writeTo(OutputStream os) throws IOException {
    try {//from   w  w  w  .j  ava  2 s . c  o m
        InputStream is = getInputStream();
        if (maxSize == -1) {
            IOUtils.copy(is, os);
        } else {
            try {
                IOUtils.copy(new TruncatedInputStream(is, maxSize), os);
            } finally {
                is.close();
            }
        }
    } catch (FileNotFoundException e) {
        OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING);
        try {
            PrintWriter pw = new PrintWriter(osw, true);
            try {
                pw.println("--- WARNING: Could not attach " + file + " as it cannot currently be found ---");
                pw.println();
                SupportLogFormatter.printStackTrace(e, pw);
            } finally {
                pw.flush();
            }
        } finally {
            osw.flush();
        }
    }
}

From source file:com.ibm.BestSellerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*w  w w  . j a v  a2s  .  c o  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/json");
    response.setCharacterEncoding("UTF-8");

    OutputStream stream = response.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");

    String listName = request.getParameter("list");
    String date = request.getParameter("date");

    logger.debug("Requested list {} and requested date {}", listName, date);

    NewYorkTimes times = new NewYorkTimes(listName, date);

    try {
        BestSellerList bestSellers = times.getList();
        ObjectMapper mapper = new ObjectMapper();

        String listContents = mapper.writeValueAsString(bestSellers.getBooks());
        logger.debug("Booklist is {}", listContents);
        writer.write(listContents);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error("New York times list unavailable");
        throw new IOException("Could not get book list from ny times");
    }

}

From source file:org.artifactory.traffic.read.TrafficReader.java

/**
 * Writes the entire content of the traffic entry log files which are relevant to the given time window, into the
 * given output stream// w w  w. ja  va  2s  .  co m
 *
 * @param outputStream Stream to write log file contents to
 * @param startDate    Time window start date
 * @param endDate      Time window end date
 * @return long - Total amount of characters written to the output stream
 */
public long writeFileToStream(OutputStream outputStream, Date startDate, Date endDate) {
    validateDateRange(startDate, endDate);

    if (outputStream == null) {
        throw new IllegalArgumentException("Output stream cannot be null.");
    }

    Collection<File> trafficLogs = readFiles(startDate, endDate);
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, Charsets.UTF_8);
    long totalCharsWritten = 0;

    for (File trafficLog : trafficLogs) {
        Reader fileReader = null;
        try {
            fileReader = new InputStreamReader(new FileInputStream(trafficLog), Charsets.UTF_8);
            int charsCopied = IOUtils.copy(fileReader, writer);
            totalCharsWritten += charsCopied;
            writer.flush();
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(fileReader);
        }
    }

    return totalCharsWritten;
}

From source file:com.cloudbees.jenkins.support.api.FileContent.java

@Override
public void writeTo(OutputStream os, ContentFilter filter) throws IOException {
    if (isBinary || filter == null) {
        writeTo(os);//w  w  w. j av a2 s  .  com
    }

    try {
        if (maxSize == -1) {
            for (String s : Files.readAllLines(file.toPath())) {
                String filtered = filter.filter(s);
                IOUtils.write(filtered, os);
            }
        } else {
            try (TruncatedFileReader reader = new TruncatedFileReader(file, maxSize)) {
                String s;
                while ((s = reader.readLine()) != null) {
                    String filtered = filter.filter(s);
                    IOUtils.write(filtered, os);
                }
            }
        }
    } catch (FileNotFoundException | NoSuchFileException e) {
        OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING);
        try {
            PrintWriter pw = new PrintWriter(osw, true);
            try {
                pw.println("--- WARNING: Could not attach " + file + " as it cannot currently be found ---");
                pw.println();
                SupportLogFormatter.printStackTrace(e, pw);
            } finally {
                pw.flush();
            }
        } finally {
            osw.flush();
        }
    }
}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response.//w w  w . ja va2  s .  com
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    //TODO: Multi-thread this
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket");
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket");
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:org.archive.crawler.framework.CrawlScope.java

/**
 * Add a new seed to scope. By default, simply appends
 * to seeds file, though subclasses may handle differently.
 *
 * <p>This method is *not* sufficient to get the new seed 
 * scheduled in the Frontier for crawling -- it only 
 * affects the Scope's seed record (and decisions which
 * flow from seeds). //from ww w. j  a v  a 2  s  .  co  m
 *
 * @param curi CandidateUri to add
 * @return true if successful, false if add failed for any reason
 */
public boolean addSeed(final CandidateURI curi) {
    File f = getSeedfile();
    if (f != null) {
        try {
            OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(f, true), "UTF-8");
            // Write to new (last) line the URL.
            fw.write("\n");
            fw.write("# Heritrix added seed ");
            fw.write((curi.getVia() != null) ? "redirect from " + curi.getVia() : "(JMX)");
            fw.write(" " + ArchiveUtils.get17DigitDate() + ".\n");
            fw.write(curi.toString());
            fw.flush();
            fw.close();
            Iterator iter = seedListeners.iterator();
            while (iter.hasNext()) {
                ((SeedListener) iter.next()).addedSeed(curi);
            }
            return true;
        } catch (IOException e) {
            DevUtils.warnHandle(e, "problem writing new seed");
        }
    }
    return false;
}