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.exist.xquery.xproc.ProcessFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }/*from  ww w.  j  a  v  a  2  s . co m*/

    //        Sequence input = getArgument(0).eval(contextSequence, contextItem);

    UserArgs userArgs = new UserArgs();

    Sequence pipe = args[0];

    if (Type.subTypeOf(pipe.getItemType(), Type.NODE)) {

        if (pipe.getItemCount() != 1) {
            throw new XPathException(this, "Pipeline must have just ONE and only ONE element.");
        }

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

        XMLWriter xmlWriter = new XMLWriter(osw);

        SAXSerializer sax = new SAXSerializer();

        sax.setReceiver(xmlWriter);

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

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        userArgs.setPipeline(bais, XmldbURI.LOCAL_DB + "/");

    } else {
        userArgs.setPipeline(pipe.getStringValue());
    }

    InputStream defaultIn = null;

    //prepare primary input
    if (args.length > 2) {
        Sequence input = args[1];

        if (Type.subTypeOf(input.getItemType(), Type.NODE)) {

            if (input.getItemCount() != 1) {
                throw new XPathException(this, "Primary input must have just ONE and only ONE element.");
            }

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

            XMLWriter xmlWriter = new XMLWriter(osw);

            SAXSerializer sax = new SAXSerializer();

            sax.setReceiver(xmlWriter);

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

            defaultIn = new ByteArrayInputStream(baos.toByteArray());

        } else {
            defaultIn = new ByteArrayInputStream(input.getStringValue().getBytes());
        }
    }

    //parse options
    if (args.length > 2) {
        parseOptions(userArgs, args[2]);
    } else if (args.length > 1) {
        parseOptions(userArgs, args[1]);
    }

    String outputResult;
    try {

        //getContext().getModuleLoadPath();

        URI staticBaseURI = null;

        Object key = getContext().getSource().getKey();
        if (key instanceof XmldbURI) {

            String uri = ((XmldbURI) key).removeLastSegment().toString();

            if (!uri.endsWith("/")) {
                uri += "/";
            }

            staticBaseURI = new URI("xmldb", "", uri, null);

        } else {

            String uri = getContext().getModuleLoadPath();
            if (uri == null || uri.isEmpty()) {
                staticBaseURI = new URI(XmldbURI.LOCAL_DB + "/");

            } else {

                if (uri.startsWith(XmldbURI.EMBEDDED_SERVER_URI_PREFIX)) {
                    uri = uri.substring(XmldbURI.EMBEDDED_SERVER_URI_PREFIX.length());
                }
                if (!uri.endsWith("/")) {
                    uri += "/";
                }

                staticBaseURI = new URI("xmldb", "", uri, null);
            }
        }

        outputResult = XProcRunner.run(staticBaseURI, context.getBroker(), userArgs, defaultIn);

    } catch (Exception e) {
        e.printStackTrace();
        throw new XPathException(this, e);
    }

    if (outputResult == null || outputResult.isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }

    StringReader reader = new StringReader(outputResult);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        InputSource src = new InputSource(reader);

        XMLReader xr = null;

        if (xr == null) {
            SAXParser parser = factory.newSAXParser();
            xr = parser.getXMLReader();
        }

        SAXAdapter adapter = new SAXAdapter(context);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
        xr.parse(src);

        return (DocumentImpl) adapter.getDocument();
    } catch (ParserConfigurationException e) {
        throw new XPathException(this, "Error while constructing XML parser: " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new XPathException(this, "Error while parsing XML: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XPathException(this, "Error while parsing XML: " + e.getMessage(), e);
    }
}

From source file:com.omertron.themoviedbapi.tools.WebBrowser.java

public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException {

    StringWriter content = null;//from   w  w  w .  j  a va2s  . co m

    try {
        content = new StringWriter();

        BufferedReader in = null;
        HttpURLConnection cnx = null;
        OutputStreamWriter wr = null;
        try {
            cnx = (HttpURLConnection) openProxiedConnection(url);

            // If we get a null connection, then throw an exception
            if (cnx == null) {
                throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR,
                        "No HTTP connection could be made.", url);
            }

            if (isDeleteRequest) {
                cnx.setDoOutput(true);
                cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                cnx.setRequestMethod("DELETE");
            }

            sendHeader(cnx);

            if (StringUtils.isNotBlank(jsonBody)) {
                cnx.setDoOutput(true);
                wr = new OutputStreamWriter(cnx.getOutputStream());
                wr.write(jsonBody);
            }

            readHeader(cnx);

            // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error
            if (cnx.getResponseCode() >= 400) {
                in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx)));
            } else {
                in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
            }

            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (wr != null) {
                wr.flush();
                wr.close();
            }

            if (in != null) {
                in.close();
            }

            if (cnx instanceof HttpURLConnection) {
                ((HttpURLConnection) cnx).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                LOG.debug("Failed to close connection: " + ex.getMessage());
            }
        }
    }
}

From source file:biblivre3.cataloging.holding.HoldingBO.java

private File createIsoFile(Database database) {
    try {//from  w ww.  j ava2s .  c  om
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        HoldingDAO holdingDao = new HoldingDAO();
        int limit = 100;
        int recordCount = holdingDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            List<HoldingDTO> records = holdingDao.list(database, offset, limit);
            for (HoldingDTO dto : records) {
                writer.write(dto.getIso2709());
                writer.write(ApplicationConstants.LINE_BREAK);
            }
        }
        writer.flush();
        writer.close();
        return file;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Generic post method for the luke api.
 * @param urlString Url to send the request to
 * @param params Parameters to send with the request as a String
 * @return boolean indicating the success of the request
 *//*from  ww w.  j ava  2s .  c  o m*/
private boolean postMethod(String urlString, String params) {
    try {
        HttpURLConnection conn;
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty(context.getString(R.string.authorization),
                context.getString(R.string.bearer) + SessionSingleton.getInstance().getIdToken());
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);

        //get the output stream of the connection
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        //write the JSONobject to the connections output
        writer.write(params);

        //flush and close the writer
        writer.flush();
        writer.close();

        //get the response, if successfull, get inputstream, if unsuccessful get errorStream
        BufferedReader bufferedReader;
        Log.e(TAG, "updateUserImage call: RESPONSE CODE:" + conn.getResponseCode());
        if (conn.getResponseCode() != 200) {
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));

        } else {
            // TODO: 25/11/2016 check for authorization error, respond accordingly
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }
        String jsonString;
        StringBuilder stringBuilder = new StringBuilder();
        String line2;
        while ((line2 = bufferedReader.readLine()) != null) {
            stringBuilder.append(line2).append("\n");
        }
        bufferedReader.close();
        jsonString = stringBuilder.toString();
        Log.e(TAG, "updateUserImage run: Result : " + jsonString);
        conn.disconnect();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "postMethod: ", e);
        return false;
    }
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

private void fillExecutionReqBody() throws IOException, SrfException {
    _con.setDoOutput(true);//from  w  ww  .j a v  a 2s.  co m
    JSONObject data = new JSONObject();
    JSONObject testParams = new JSONObject();
    JSONObject ciParameters = new JSONObject();
    if (srfTestId != null && srfTestId.length() > 0) {
        data.put("testYac", applyJobParams(srfTestId));
    } else if (srfTagNames != null && !srfTagNames.isEmpty()) {
        String[] tagNames = normalizeTags();
        data.put("tags", tagNames);
    } else
        throw new SrfException("Both test id and test tags are empty");

    if (srfTunnelName != null && srfTunnelName.length() > 0) {
        data.put("tunnelName", srfTunnelName);
    }

    if (data.size() == 0) {
        throw new IOException("Wrong filter");
    }

    testParams.put("filter", data);
    Properties ciProps = new Properties();
    Properties props = new Properties();
    String buildNumber = applyJobParams(srfBuildNumber);
    String releaseNumber = applyJobParams(srfReleaseNumber);
    if (buildNumber != null && buildNumber.length() > 0) {
        data.put("build", buildNumber);
    }
    if (releaseNumber != null && releaseNumber.length() > 0)
        data.put("release", releaseNumber);

    this.logger.print(String.format("Required build & release: %1s %2s\n\r", buildNumber, releaseNumber));
    HashMap<String, String> paramObj = new HashMap<String, String>();
    int cnt = 0;

    if (srfTestParameters != null && !srfTestParameters.isEmpty()) {
        cnt = srfTestParameters.size();
        if (cnt > 0)
            logger.print("Parameters: \n\r");
        for (int i = 0; i < cnt; i++) {
            String name = srfTestParameters.get(i).getName();
            String val = applyJobParams(srfTestParameters.get(i).getValue());
            paramObj.put(name, val);
            logger.print(String.format("%1s : %2s\n\r", name, val));
        }
    }

    if (cnt > 0)
        data.put("params", paramObj);
    //add request header

    //     con.setRequestProperty("session-context", context);
    try {
        OutputStream out = _con.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(data.toString());
        writer.flush();
        out.flush();
        out.close();
    } catch (ProtocolException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    }
}

From source file:org.deidentifier.arx.gui.worker.WorkerSave.java

/**
 * Writes the meta data to the file.//  ww w. j  a  va  2 s.c om
 *
 * @param model
 * @param zip
 * @throws IOException
 */
private void writeMetadata(final Model model, final ZipOutputStream zip) throws IOException {

    // Write metadata
    zip.putNextEntry(new ZipEntry("metadata.xml")); //$NON-NLS-1$
    final OutputStreamWriter w = new OutputStreamWriter(zip);
    XMLWriter writer = new XMLWriter(new FileBuilder(w));
    writer.indent(vocabulary.getMetadata());
    writer.write(vocabulary.getVersion(), Resources.getVersion());
    writer.write(vocabulary.getVocabulary(), vocabulary.getVocabularyVersion());
    writer.unindent();
    w.flush();

}

From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsCSVInterceptor.java

private void writeExchange(Exchange exc) throws Exception {
    synchronized (fileName) {
        FileOutputStream fos = new FileOutputStream(fileName, true);
        try {/*  ww  w .ja va2s.  c om*/
            OutputStreamWriter w = new OutputStreamWriter(fos, Constants.UTF_8_CHARSET);

            writeCSV(ExchangesUtil.getStatusCode(exc), w);
            writeCSV(ExchangesUtil.getTime(exc), w);
            writeCSV(exc.getRule().toString(), w);
            writeCSV(exc.getRequest().getMethod(), w);
            writeCSV(exc.getRequest().getUri(), w);
            writeCSV(exc.getRemoteAddr(), w);
            writeCSV(exc.getServer(), w);
            writeCSV(exc.getRequestContentType(), w);
            writeCSV(ExchangesUtil.getRequestContentLength(exc), w);
            writeCSV(ExchangesUtil.getResponseContentType(exc), w);
            writeCSV(ExchangesUtil.getResponseContentLength(exc), w);
            writeCSV(ExchangesUtil.getTimeDifference(exc), w);
            writeNewLine(w);
            w.flush();
        } finally {
            fos.close();
        }
    }
}

From source file:com.cellbots.httpserver.HttpCommandServer.java

public void handle(final HttpServerConnection conn, final HttpContext context)
        throws HttpException, IOException {
    HttpRequest request = conn.receiveRequestHeader();
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//  ww  w.  j av a 2s  .  c o  m

    // Get the requested target. This is the string after the domain name in
    // the URL. If the full URL was http://mydomain.com/test.html, target
    // will be /test.html.
    String target = request.getRequestLine().getUri();
    //Log.w(TAG, "*** Request target: " + target);

    // Gets the requested resource name. For example, if the full URL was
    // http://mydomain.com/test.html?x=1&y=2, resource name will be
    // test.html
    final String resName = getResourceNameFromTarget(target);
    UrlParams params = new UrlParams(target);
    //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString());
    //Log.w(TAG, "*** Request resource: " + resName);
    if (method.equals("POST") || method.equals("PUT")) {
        byte[] entityContent = null;
        // Gets the content if the request has an entity.
        if (request instanceof HttpEntityEnclosingRequest) {
            conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entityContent = EntityUtils.toByteArray(entity);
            }
        }
        response.setStatusCode(HttpStatus.SC_OK);
        if (serverListener != null) {
            serverListener.onRequest(resName, params.keys, params.values, entityContent);
        }
    } else if (dataMap.containsKey(resName)) { // The requested resource is
                                               // a byte array
        response.setStatusCode(HttpStatus.SC_OK);
        response.setHeader("Content-Type", dataMap.get(resName).contentType);
        response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
    } else { // Resource is a file recognized by the app
        String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName;
        String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType
                : "text/html";
        Log.d(TAG, "*** mapped resource: " + fileName);
        Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        response.setStatusCode(HttpStatus.SC_OK);
        final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
        if (file.exists() && !file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName));
            response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName));
            response.setEntity(body);
        } else if (file.isDirectory()) {
            response.setStatusCode(HttpStatus.SC_OK);
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    ArrayList<String> fileList = getDirListing(file);
                    String resp = "{ \"list\": [";
                    for (String fl : fileList) {
                        resp += "\"" + fl + "\",";
                    }
                    resp = resp.substring(0, resp.length() - 1);
                    resp += "]}";
                    writer.write(resp);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else if (resourceMap.containsKey(resName)) {
            EntityTemplate body = new EntityTemplate(new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                    writer.write(resourceMap.get(resName).resource);
                    writer.flush();
                }
            });
            body.setContentType(contentType);
            response.setEntity(body);
        } else {
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            response.setEntity(new StringEntity("Not Found"));
        }
    }
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    conn.shutdown();
}

From source file:CloudManagerAPI.java

private void writePayload(HttpURLConnection connection, final String payload) throws IOException {
    OutputStreamWriter writer = null;
    try {/*from   w w  w  . j a v  a  2s.c  om*/
        final String contentLength = String.valueOf(payload.length());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", contentLength);

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload);
        writer.flush();
    } finally {
        closeStream(writer);
    }
}

From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java

public String getUI(String xmlUI) throws GWTServiceException {
    String url = null;/*  w ww  .j av  a 2 s .  c om*/
    if (service.isValidXML(xmlUI)) {
        logger.fine("XML Send by client : \n" + xmlUI);

        try {

            String urlBase = ApplicationCluster.getInstance()
                    .getConfigurationItem(Configuration.FLEX_DEMO_WAR_URL);
            if (urlBase == null || urlBase.length() == 0) {
                urlBase = getThreadLocalRequest().getScheme() + "://" + getThreadLocalRequest().getServerName()
                        + ":" + getThreadLocalRequest().getServerPort() + "/qafe-web-flex";
            }

            String urlStore = urlBase + "/store";
            logger.fine("URL Store is =" + urlStore);

            OutputStreamWriter wr = null;
            BufferedReader rd = null;

            try {
                // Send data
                URL requestURL = new URL(urlStore);
                URLConnection conn = requestURL.openConnection();
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                String data = "xml" + "=" + xmlUI;
                wr.write(data);
                wr.flush();

                // Get the response
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    url = urlBase + "/index.jsp?uuid=" + line;
                    logger.fine(url);
                }
            } finally {
                wr.close();
                rd.close();
            }
        } catch (Exception e) {
            throw handleException(e);
        }
    } else {
        try {
            service.getUIFromXML(xmlUI, null, null, getLocale());
        } catch (Exception e) {
            throw handleException(e);
        }
    }
    return url;
}