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.paramedic.mobshaman.activities.ActualizarInformacionActivity.java

private void updateFile(String fileName, ArrayList<String> inputs) {

    FileOutputStream outputStream;

    try {//from  w  w  w . ja v a2  s  .  co m
        String separator = System.getProperty("line.separator");
        outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
        OutputStreamWriter osw = new OutputStreamWriter(outputStream);

        for (String input : inputs) {
            osw.append(input);
            osw.append(separator);
        }

        osw.flush();
        osw.close();
        outputStream.close();

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

}

From source file:org.gbif.portal.web.download.VelocityFileWriter.java

/**
 * Write out the supplied template./* w w w  .ja  v a2s.c  om*/
 * 
 * @param templatePath
 * @param outputStream
 * @throws Exception
 */
protected void writeTemplate(String templatePath, OutputStream outputStream) throws Exception {
    if (StringUtils.isNotEmpty(templatePath)) {
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("hostUrl", hostUrl);
        Template template = Velocity.getTemplate(templatePath);
        template.initDocument();
        TemplateUtils tu = new TemplateUtils();
        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        tu.merge(template, velocityContext, writer);
        writer.flush();
    }
}

From source file:com.support.android.designlibdemo.DetailContactActivity.java

public String postData(String sURL, String sData) {
    try {//from w  w w.  ja  v  a  2s . co m
        String data = URLEncoder.encode("jsonString", "UTF-8") + "=" + URLEncoder.encode(sData, "UTF-8");
        URL url = new URL(sURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");
        }

        return sb.toString();

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

From source file:org.eclipse.orion.server.docker.server.DockerFile.java

/**
 * Get the tar file containing the Dockerfile that can be sent to the Docker 
 * build API to create an image. //w  ww.j ava2s  .c  o m
 * 
 * @return The tar file.
 */
public File getTarFile() {
    try {
        // get the temporary folder location.
        String tmpDirName = System.getProperty("java.io.tmpdir");
        File tmpDir = new File(tmpDirName);
        if (!tmpDir.exists() || !tmpDir.isDirectory()) {
            if (logger.isDebugEnabled()) {
                logger.error("Cannot find the default temporary-file directory: " + tmpDirName);
            }
            return null;
        }

        // get a temporary folder name
        long n = random.nextLong();
        n = (n == Long.MIN_VALUE) ? 0 : Math.abs(n);
        String tmpDirStr = Long.toString(n);
        tempFolder = new File(tmpDir, tmpDirStr);
        if (!tempFolder.mkdir()) {
            if (logger.isDebugEnabled()) {
                logger.error("Cannot create a temporary directory at " + tempFolder.toString());
            }
            return null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Dockerfile: Created a temporary directory at " + tempFolder.toString());
        }

        // create the Dockerfile
        dockerfile = new File(tempFolder, "Dockerfile");
        FileOutputStream fileOutputStream = new FileOutputStream(dockerfile);
        Charset utf8 = Charset.forName("UTF-8");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, utf8);
        outputStreamWriter.write(getDockerfileContent());
        outputStreamWriter.flush();
        outputStreamWriter.close();
        fileOutputStream.close();

        dockerTarFile = new File(tempFolder, "Dockerfile.tar");

        TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(
                new FileOutputStream(dockerTarFile));
        tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

        TarArchiveEntry tarEntry = new TarArchiveEntry(dockerfile);
        tarEntry.setName(dockerfile.getName());
        tarArchiveOutputStream.putArchiveEntry(tarEntry);

        FileInputStream fileInputStream = new FileInputStream(dockerfile);
        BufferedInputStream inputStream = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = inputStream.read(buffer)) != -1) {
            tarArchiveOutputStream.write(buffer, 0, bytes_read);
        }
        inputStream.close();

        tarArchiveOutputStream.closeArchiveEntry();
        tarArchiveOutputStream.close();

        if (logger.isDebugEnabled()) {
            logger.debug("Dockerfile: Created a docker tar file at " + dockerTarFile.toString());
        }
        return dockerTarFile;
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
    }
    return null;
}

From source file:org.geoserver.wms.featureinfo.GeoJSONFeatureInfoOutputFormat.java

private void writeJSONP(OutputStream out, FeatureCollectionType features, Operation opDescriptor,
        GeoJSONOutputFormat format) throws IOException {
    OutputStreamWriter outWriter = null;
    try {/*w  ww.j  a v  a  2s.c  o m*/
        outWriter = new OutputStreamWriter(out, wms.getGeoServer().getSettings().getCharset());

        // preamble
        outWriter.write(getCallbackFunction() + "(");
        outWriter.flush();

        // call regular format
        format.write(features, out, opDescriptor);

        // postamble
        outWriter.write(")");
        outWriter.flush();
    } finally {
        IOUtils.closeQuietly(outWriter);
    }
}

From source file:org.ala.preprocess.ColFamilyNamesProcessor.java

/**
 * Copy the raw file into the repository.
 * /*from   w ww.j  a v  a2  s.c om*/
 * @param filePath
 * @param uri
 * @param infosourceUri
 * @param mimeType
 * @return
 * @throws FileNotFoundException
 * @throws Exception
 * @throws IOException
 */
private int copyRawFileToRepo(String filePath, String uri, String infosourceUri, String mimeType)
        throws FileNotFoundException, Exception, IOException {
    InfoSource infoSource = infoSourceDAO.getByUri(infosourceUri);

    Reader ir = new FileReader(filePath);
    DocumentOutputStream dos = repository.getDocumentOutputStream(infoSource.getId(), uri, mimeType);

    //write the file to RAW file in the repository
    OutputStreamWriter w = new OutputStreamWriter(dos.getOutputStream());

    //read into buffer
    char[] buff = new char[1000];
    int read = 0;
    while ((read = ir.read(buff)) > 0) {
        w.write(buff, 0, read);
    }
    w.flush();
    w.close();
    return dos.getId();
}

From source file:org.aselect.authspserver.authsp.delegator.HTTPSTrustAllDelegate.java

public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters)
        throws DelegateException {
    String sMethod = "authenticate";
    int iReturnCode = -1;

    AuthSPSystemLogger _systemLogger;//from  w ww.  j av  a  2  s  . c  om
    _systemLogger = AuthSPSystemLogger.getHandle();

    _systemLogger.log(Level.FINEST, sModule, sMethod,
            "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters);
    StringBuffer data = new StringBuffer();
    String sResult = "";
    ;

    try {
        final String EQUAL_SIGN = "=";
        final String AMPERSAND = "&";
        final String NEWLINE = "\n";
        for (String key : requestparameters.keySet()) {
            data.append(URLEncoder.encode(key, "UTF-8"));
            data.append(EQUAL_SIGN).append(URLEncoder.encode(
                    ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key),
                    "UTF-8"));
            data.append(AMPERSAND);
        }

        if (data.length() > 0)
            data.deleteCharAt(data.length() - 1); // remove last AMPERSAND
        //         data.append(NEWLINE).append(NEWLINE);
        //         _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}");   // no data shown in production environment

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Tell the url connection object to use our socket factory which bypasses security checks
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

        // Basic authentication
        if (this.delegateuser != null) {
            byte[] bEncoded = Base64
                    .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword))
                            .getBytes("UTF-8"));
            String encoded = new String(bEncoded, "UTF-8");
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            _systemLogger.log(Level.FINEST, sModule, sMethod,
                    "Using basic authentication, user=" + this.delegateuser);
        }
        //         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !!
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());

        wr.flush();
        wr.close();

        // Get the response
        iReturnCode = conn.getResponseCode();
        Map<String, List<String>> hFields = conn.getHeaderFields();

        _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        // Still to decide on response protocol
        while ((line = rd.readLine()) != null) {
            sResult += line;
        }
        _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult);
        // Parse response  here
        // For test return request parameters
        //         responseparameters.putAll(requestparameters);
        responseparameters.putAll(hFields);

        rd.close();
    } catch (IOException e) {
        _systemLogger.log(Level.INFO, sModule, sMethod,
                "Error while reading sResult data, maybe no data at all. sResult=" + sResult);
    }

    catch (NumberFormatException e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed due to number format exception! " + e.getMessage(), e);
    } catch (Exception e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e);
    }
    return iReturnCode;
}

From source file:com.cubusmail.server.services.CubusmailServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String fileName = request.getSession().getServletContext().getRealPath(request.getServletPath());
    BufferedReader reader = new BufferedReader(new FileReader(fileName));

    OutputStream outputStream = response.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    char[] inBuf = new char[1024];
    int len = 0;//from ww  w. j  a  v a 2 s. c om
    try {
        while ((len = reader.read(inBuf)) > 0) {
            writer.write(inBuf, 0, len);
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
    }

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

From source file:com.tomcat.monitor.zabbix.ZabbixSender.java

public void send(final String zabbixServer, final int zabbixPort, int zabbixTimeout, final String host,
        final String key, final String value) throws IOException {

    final byte[] response = new byte[1024];

    final long start = System.currentTimeMillis();

    final int TIMEOUT = zabbixTimeout * 1000;

    final StringBuilder message = new StringBuilder("<req><host>");
    message.append(new String(Base64.encodeBase64(host.getBytes())));
    message.append("</host><key>");
    message.append(new String(Base64.encodeBase64(key.getBytes())));
    message.append("</key><data>");
    message.append(new String(Base64.encodeBase64(value.getBytes())));
    message.append("</data></req>");

    if (log.isDebugEnabled()) {
        log.debug("sending " + message);
    }/*from   www  .j  a va 2 s .c o m*/

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    try {
        zabbix = new Socket(zabbixServer, zabbixPort);
        zabbix.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(zabbix.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = zabbix.getInputStream();
        final int read = in.read(response);
        if (log.isDebugEnabled()) {
            log.debug("received " + new String(response));
        }
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            log.warn("received unexpected response '" + new String(response) + "' for key '" + key + "'");
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (zabbix != null) {
            zabbix.close();
        }
    }
    log.info("send() " + (System.currentTimeMillis() - start) + " ms");
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override/*from  w  ww  . j  a v  a 2s . c o  m*/
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}