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:com.vaynberg.wicket.select2.AbstractSelect2Choice.java

@Override
public void onResourceRequested() {

    // this is the callback that retrieves matching choices used to populate the dropdown

    Request request = getRequestCycle().getRequest();
    IRequestParameters params = request.getRequestParameters();

    // retrieve choices matching the search term

    String term = params.getParameterValue("term").toOptionalString();

    int page = params.getParameterValue("page").toInt(1);
    // select2 uses 1-based paging, but in wicket world we are used to
    // 0-based//from   w w w . java2  s  .  c  o  m
    page -= 1;

    Response<T> response = new Response<T>();
    provider.query(term, page, response);

    // jsonize and write out the choices to the response

    WebResponse webResponse = (WebResponse) getRequestCycle().getResponse();
    webResponse.setContentType("application/json");

    OutputStreamWriter out = new OutputStreamWriter(webResponse.getOutputStream(), getRequest().getCharset());
    JSONWriter json = new JSONWriter(out);

    try {
        json.object();
        json.key("results").array();
        for (T item : response) {
            json.object();
            provider.toJson(item, json);
            json.endObject();
        }
        json.endArray();
        json.key("more").value(response.getHasMore()).endObject();
    } catch (JSONException e) {
        throw new RuntimeException("Could not write Json response", e);
    }

    try {
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException("Could not write Json to servlet response", e);
    }
}

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
 * Send an HTTP POST request//from w ww .j  a v  a  2s.co  m
 * @param connection Open connection
 * @param request Request to send
 * @throws ApiException
 */
private void sendHttpRequest(HttpURLConnection connection, String request) throws ApiException {
    try {
        LogUtils.LOGD(TAG, "Sending request via HTTP: " + request);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(request);
        out.flush();
        out.close();
    } catch (IOException e) {
        LogUtils.LOGW(TAG, "Failed to send HTTP request.", e);
        throw new ApiException(ApiException.IO_EXCEPTION_WHILE_SENDING_REQUEST, e);
    }

}

From source file:com.googlecode.CallerLookup.Main.java

public void saveUserLookupEntries() {
    try {//  w ww.  j a v a2 s . co m
        FileOutputStream file = getApplicationContext().openFileOutput(SAVED_FILE, MODE_PRIVATE);
        JSONArray userLookupEntries = new JSONArray();
        for (String lookupEntryName : mUserLookupEntries.keySet()) {
            try {
                userLookupEntries.put(mUserLookupEntries.get(lookupEntryName).toJSONObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        OutputStreamWriter content = new OutputStreamWriter(file);
        content.write(userLookupEntries.toString());
        content.flush();
        content.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.flink.streaming.api.functions.source.SocketTextStreamFunctionTest.java

@Test
public void testSocketSourceOutputAcrossRetries() throws Exception {
    ServerSocket server = new ServerSocket(0);
    Socket channel = null;//from   w  w  w .j av  a  2  s .  co  m

    try {
        SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n",
                10, 100);

        SocketSourceThread runner = new SocketSourceThread(source, "test1", "check1", "check2");
        runner.start();

        // first connection: nothing
        channel = server.accept();
        channel.close();

        // second connection: first string
        channel = server.accept();
        OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());
        writer.write("te");
        writer.close();
        channel.close();

        // third connection: nothing
        channel = server.accept();
        channel.close();

        // forth connection: second string
        channel = server.accept();
        writer = new OutputStreamWriter(channel.getOutputStream());
        writer.write("st1\n");
        writer.write("check1\n");
        writer.write("check2\n");
        writer.flush();

        runner.waitForNumElements(2);
        runner.cancel();
        runner.waitUntilDone();
    } finally {
        if (channel != null) {
            IOUtils.closeQuietly(channel);
        }
        IOUtils.closeQuietly(server);
    }
}

From source file:org.infoscoop.web.MultiRssServlet.java

private void mergeRssAnd2JSON(HttpServletRequest request, HttpServletResponse response, String uid,
        String widgetId, int pageSize, NodeList urlList) throws Exception {

    try {//from   w ww.j  a v  a 2  s .c  om
        RssJsonResultBuilder resultBuilder = new SortedRssJsonResultBuilder(pageSize);

        String dateTimeFormat = request.getHeader("X-IS-DATETIMEFORMAT");
        if (dateTimeFormat != null) {
            dateTimeFormat = URLDecoder.decode(dateTimeFormat, "UTF-8");
        }
        String freshTime = request.getHeader("X-IS-FRESHTIME");
        String maxCountString = request.getHeader("X-IS-RSSMAXCOUNT");
        int maxCount = 1000;
        if (maxCountString != null) {
            try {
                int paramMaxCount = Integer.parseInt(maxCountString);
                if (paramMaxCount >= 0) {
                    maxCount = paramMaxCount;
                }
            } catch (NumberFormatException e) {
                log.warn("rssmaxcount \"" + maxCountString + "\" isn't integer value.");
            }
        }

        // Norrowing
        String titleFilter = request.getHeader("X-IS-TITLEFILTER");
        if (titleFilter != null)
            titleFilter = URLDecoder.decode(titleFilter, "UTF-8");
        String creatorFilter = request.getHeader("X-IS-CREATORFILTER");
        if (creatorFilter != null)
            creatorFilter = URLDecoder.decode(creatorFilter, "UTF-8");
        String categoryFilter = request.getHeader("X-IS-CATEGORYFILTER");
        if (categoryFilter != null)
            categoryFilter = URLDecoder.decode(categoryFilter, "UTF-8");

        int DEFAULT_TIMEOUT = 15 * 1000;

        boolean modified = false;
        Map cacheHeaders = new HashMap();
        Map errorMap = new HashMap();
        List siteCacheHeaders = new ArrayList();
        for (int i = 0; i < urlList.getLength(); i++) {
            Element rssEl = (Element) urlList.item(i);
            String url = rssEl.getAttribute("url");

            ProxyRequest proxyRequest = new ProxyRequest(url, "NoOperation");
            proxyRequest.setLocales(request.getLocales());
            proxyRequest.setPortalUid(uid);

            int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
            proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);
            //proxyRequest.setTimeout(timeout);

            proxyRequest.addIgnoreHeader("user-agent");
            proxyRequest.addIgnoreHeader("X-IS-DATETIMEFORMAT");
            proxyRequest.addIgnoreHeader("X-IS-FRESHTIME");
            proxyRequest.addIgnoreHeader("X-IS-REFRESH");
            proxyRequest.addIgnoreHeader("X-IS-RSSMAXCOUNT");
            proxyRequest.addIgnoreHeader("X-IS-PAGESIZE");

            Enumeration headers = request.getHeaderNames();
            while (headers.hasMoreElements()) {
                String headerName = (String) headers.nextElement();
                proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
            }

            NodeList rssChildNodes = rssEl.getElementsByTagName("header");
            for (int j = 0; j < rssChildNodes.getLength(); j++) {
                Element header = (Element) rssChildNodes.item(j);
                if (header.getFirstChild() != null) {
                    String name = header.getAttribute("name");
                    String value = header.getFirstChild().getNodeValue();
                    if (name == null || name.trim().length() == 0 || value == null
                            || value.trim().length() == 0)
                        continue;

                    proxyRequest.putRequestHeader(name, value);
                }
            }

            int statusCode = 0;
            String methodType = rssEl.getAttribute("method");
            try {
                if ("post".equals(methodType)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } catch (SocketTimeoutException ex) {
                log.error("url: [" + url + "] socket timeout.", ex);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_TIMEOUT));
            } catch (ConnectTimeoutException ex) {
                log.error("url: [" + url + "] connection timeout.", ex);
                errorMap.put(url, new Integer(500));
            } catch (SocketException ex) {
                log.error("url: [" + url + "] socket error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (IOException ex) {
                log.error("url: [" + url + "] I/O error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (Exception ex) {
                log.error("url: [" + url + "]" + ex.getMessage(), ex);
                errorMap.put(url, new Integer(500));
            }

            BufferedInputStream bis = null;
            if (errorMap.containsKey(url)) {
                // nothing

            } else if (statusCode == 204) {
                log.warn("url:[" + url + "] is no content #" + statusCode);
                modified = true;
            } else if (statusCode == 304) {
                log.warn("url:[" + url + "] is not modified #" + statusCode);
            } else if (statusCode != 200) {
                log.error("url:[" + url + "] had error status code #" + statusCode);
                errorMap.put(url, new Integer(statusCode));
            } else {
                log.info("url:[" + url + "] is succed #" + statusCode);

                try {
                    modified = true;

                    bis = new BufferedInputStream(proxyRequest.getResponseBody());

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[10240];
                    int c;
                    while ((c = bis.read(buf)) != -1) {
                        baos.write(buf, 0, c);
                        baos.flush();
                    }
                    bis.close();

                    byte[] data = baos.toByteArray();
                    baos.close();

                    //RssCacheDAO.newInstance().insertCache(uid, widgetId+url, -1,data );

                    Map responseHeaders = proxyRequest.getResponseHeaders();
                    String lastModifiedName = "Last-Modified".toLowerCase();
                    if (responseHeaders.containsKey(lastModifiedName)) {
                        siteCacheHeaders.add(lastModifiedName);
                        siteCacheHeaders.add(responseHeaders.get(lastModifiedName));
                    }

                    String etagName = "ETag".toLowerCase();
                    if (responseHeaders.containsKey(etagName)) {
                        siteCacheHeaders.add(etagName);
                        siteCacheHeaders.add(responseHeaders.get(etagName));
                    }

                    if (siteCacheHeaders.size() > 0) {
                        cacheHeaders.put(url, siteCacheHeaders.toArray());
                        siteCacheHeaders.clear();
                    }

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                } catch (IOException ex) {
                    log.error("rss reading " + url + " is failed.", ex);
                    cacheHeaders.remove(url);
                    errorMap.put(url, new Integer(500));

                    bis.close();
                    bis = null;
                }
            }

            if (bis == null)
                continue;

            RssHandler handler;

            boolean isAtom = RssFilter.isAtom(bis);

            XMLFilter.skipEmptyLine(bis);
            if (isAtom) {
                handler = new AtomHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            } else {
                handler = new RssHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            }

            try {
                XMLReader reader = factory.newSAXParser().getXMLReader();
                reader.setEntityResolver(NoOpEntityResolver.getInstance());
                reader.setContentHandler(handler);
                reader.parse(new InputSource(bis));
            } catch (SAXException e) {
                log.info("Parsing rss " + url + " is failed.", e);
                cacheHeaders.remove(url);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_CONTENT_PARSE_ERROR));
            }
        }

        if (!modified && errorMap.isEmpty()) {
            log.warn("multi rss is not modified.");
            response.setStatus(304);

            return;
        } else {
            try {
                long freshTimeLong = new Date().getTime();
                if (freshTime != null)
                    freshTimeLong = Long.parseLong(freshTime.trim());
                setOldData(resultBuilder, uid, widgetId, freshTimeLong, titleFilter, creatorFilter,
                        categoryFilter);

            } catch (NumberFormatException e) {
                log.error("", e);
            }

            //}

            int pageCount = resultBuilder.getPageCount();
            // We create the result cash by all means.
            //if( pageCount > 1 ) {
            for (int pageNum = 0; pageNum < pageCount; pageNum++) {
                RssCacheDAO.newInstance().insertCache(uid, widgetId, pageNum, resultBuilder.getResult(pageNum));
            }
            //}
        }

        response.addHeader("Content-Type", "text/plain; charset=UTF-8");

        String result = resultBuilder.getResult();

        if (!errorMap.isEmpty()) {
            JSONObject errors = new JSONObject(errorMap);
            result = "{errors:" + errors.toString() + "," + result.substring(result.indexOf("{") + 1);
        }
        if (!cacheHeaders.isEmpty()) {
            StringBuffer cacheHeadersBuf = new StringBuffer();
            cacheHeadersBuf.append("cacheHeaders : {");
            for (Iterator keys = cacheHeaders.keySet().iterator(); keys.hasNext();) {
                String url = (String) keys.next();
                Object[] headers = (Object[]) cacheHeaders.get(url);

                cacheHeadersBuf.append("\"").append(url).append("\" : {");
                for (int i = 0; i < headers.length; i += 2) {
                    cacheHeadersBuf.append("\"").append(headers[i]).append("\"");
                    cacheHeadersBuf.append(" : '").append(headers[i + 1]).append("'");
                    if (i + 2 < headers.length)
                        cacheHeadersBuf.append(",");
                }
                cacheHeadersBuf.append("}");
                if (keys.hasNext())
                    cacheHeadersBuf.append(",");
            }
            cacheHeadersBuf.append("}");

            result = "{" + cacheHeadersBuf.toString() + "," + result.substring(result.indexOf("{") + 1);
        }

        response.setContentLength(result.getBytes("UTF-8").length);

        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        try {
            out.write(result);

            out.flush();
        } catch (SocketException ex) {
            // ignore client abort exception
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (Exception e) {
        log.error("unexpected error occurred.", e);
        response.sendError(500, e.getMessage());
    }

}

From source file:com.hqme.cm.cache.StreamingServer.java

public void run() {
    if (UntenCacheService.sIsDebugMode) {
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
        Thread.currentThread().setName(getClass().getName());
    }/*from  w w  w .  ja  v  a 2  s .c om*/

    isStopping = false;
    serverSocket = null;
    serverPortPrefs = new File(UntenCacheService.sPluginContext.getFilesDir(), tag_PlaybackPortNumber);
    try {
        String text = new BufferedReader(new InputStreamReader(new FileInputStream(serverPortPrefs), "UTF16"),
                1 << 10).readLine();
        serverPortNumber = Integer.valueOf(text.trim());
    } catch (Throwable ignore) {
        serverPortNumber = 0;
    }

    int retries = 2;
    while (retries-- > 0) {
        try {
            serverSocket = new ServerSocket(serverPortNumber);
            if (serverPortNumber == 0) {
                serverPortNumber = serverSocket.getLocalPort();
                try {
                    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(serverPortPrefs),
                            "UTF16");
                    writer.write(serverPortNumber + "\r\n");
                    writer.flush();
                    writer.close();
                } catch (Throwable ignore) {
                }
            }
            clientBox = new ClientBox[MAX_CLIENTS];
            retries = 0;

            UntenCacheService.debugLog(sTag, "run: Streaming Media Server is now active on TCP port # %d",
                    serverPortNumber);
            handleRequests();
        } catch (IOException fault) {
            fault.printStackTrace();
            try {
                serverPortPrefs.delete();
            } catch (Throwable ignore) {
            }
        }
    }
}

From source file:it.infn.ct.ToscaIDCInterface.java

/**
 * Submit template to the orchestrator a template.
 * @return TOSCA UUID//from  w w w  .j a v a2s  .  c o m
 */
public final String submitOrchestrator() {

    StringBuilder orchestratorResult = new StringBuilder("");
    StringBuilder postData = new StringBuilder();
    String toscParametersValues = "";
    String toscaParametersJson = "";
    String tUUID = "";
    String[] toscaParams = toscaParameters.split("&");
    String tParams = "";
    for (int i = 0; i < toscaParams.length; i++) {
        String[] paramArgs = toscaParams[i].split("=");
        if (paramArgs[0].trim().equals("params")) {
            toscaParametersJson = toscaCommand.getActionInfo() + FS + paramArgs[1].trim();
            LOG.debug("Loading params json file: '" + toscaParametersJson + "'");
            try {
                String paramsJson = new String(Files.readAllBytes(Paths.get(toscaParametersJson)));
                LOG.debug("params JSON: '" + paramsJson + "'");
                toscParametersValues = getDocumentValue(paramsJson, "parameters");
                LOG.debug("extracted parameters: '" + tParams + "'");
            } catch (IOException ex) {
                LOG.error("Parameters json file '" + toscaParametersJson + "' is not readable");
                LOG.error(ex);
            } catch (ParseException ex) {
                LOG.error("Parameters json file '" + toscaParametersJson + "' is not parseable");
                LOG.error(ex);
            }
            LOG.debug("Parameters json file '" + toscaParametersJson + "' successfully parsed");
            break;
        }
    }
    if (toscParametersValues.length() > 0) {
        tParams = "\"parameters\": " + toscParametersValues + ", ";
    }
    postData.append("{ " + tParams + "\"template\": \"");
    String toscaTemplateContent = "";
    LOG.debug("Escaping toscaTemplate file '" + toscaTemplate + "'");
    try {
        toscaTemplateContent = new String(Files.readAllBytes(Paths.get(toscaTemplate))).replace("\n", "\\n");
    } catch (IOException ex) {
        LOG.error("Template '" + toscaTemplate + "'is not readable");
        LOG.error(ex);
    }
    postData.append(toscaTemplateContent);
    postData.append("\" }");
    LOG.debug("JSON Data (begin):\n" + postData + "\nJSON Data (end)");

    HttpURLConnection conn;
    String orchestratorDoc = "";
    try {
        conn = (HttpURLConnection) toscaEndPoint.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + toscaToken);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData.toString());
        wr.flush();
        wr.close();
        LOG.debug("Orchestrator status code: " + conn.getResponseCode());
        LOG.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == HTTP_201) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            orchestratorResult = new StringBuilder();
            String ln;
            while ((ln = br.readLine()) != null) {
                orchestratorResult.append(ln);
            }
            LOG.debug("Orchestrator result: " + orchestratorResult);
            orchestratorDoc = orchestratorResult.toString();
            tUUID = getDocumentValue(orchestratorDoc, "uuid");
            LOG.debug("Created resource has UUID: '" + tUUID + "'");
        } else {
            LOG.warn("Orchestrator return code is: " + conn.getResponseCode());
        }
    } catch (IOException ex) {
        LOG.error("Connection error with the service at " + toscaEndPoint.toString());
        LOG.error(ex);
    } catch (ParseException ex) {
        LOG.error("Error parsing JSON:" + orchestratorDoc);
        LOG.error(ex);
    }
    return tUUID;
}

From source file:org.envirocar.aggregation.AggregatedTracksServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), Charset.forName("UTF-8"));

    resp.setContentType("application/json");

    String uri = req.getRequestURI();
    String subPath = uri.substring(uri.indexOf(PATH) + PATH.length());

    String trackId = null;/*ww  w. j  a v a2  s  .  c om*/
    if (!subPath.isEmpty() && !(subPath.length() == 1 && subPath.equals("/"))) {
        trackId = subPath.startsWith("/") ? subPath.substring(1) : subPath;
    }

    String json;
    try {
        if (trackId != null) {
            json = createTrackExists(trackId);
        } else {
            json = createAggregatedTracksList();
        }
    } catch (SQLException e) {
        throw new IOException(e);
    }

    writer.append(json);

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

    resp.setStatus(200);
}

From source file:debrepo.teamcity.web.DebDownloadController.java

/**
 * Creates a new {@link GZIPOutputStream} and streams the stringToGzip through it to the provided {@link OutputStream}
 * @param stringToGzip - String of text which needs gzipping.
 * @param outputStream - {@link OutputStream} to write gzip'd string to.
 * @throws IOException// w w  w .ja v  a  2  s  .  co  m
 */
private void gzip(String stringToGzip, OutputStream outputStream) throws IOException {
    GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
    OutputStreamWriter osw = new OutputStreamWriter(gzip, StandardCharsets.UTF_8);
    osw.write(stringToGzip);
    osw.flush();
    osw.close();
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, MaalrQuery query, File dest) throws IOException, InvalidQueryException,
        NoIndexAvailableException, BrokenIndexException, InvalidTokenOffsetsException {
    query.setPageNr(0);/*w  ww.  j  a v  a2s  .c om*/
    query.setPageSize(50);
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        QueryResult result = index.query(query, false);
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        List<LemmaVersion> entries = result.getEntries();
        for (LemmaVersion version : entries) {
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setPageNr(query.getPageNr() + 1);
    }
    writer.flush();
    zout.closeEntry();
    writer.close();

}