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.apache.karaf.cave.server.storage.CaveRepositoryImpl.java

/**
 * Generate the repository.xml with the artifact at the given URL.
 *
 * @throws Exception in case of repository.xml update failure.
 *//*from w  ww .j  av  a  2  s  .  c o m*/
private void generateRepositoryXml() throws Exception {
    File repositoryXml = this.getRepositoryXmlFile();
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(repositoryXml));
    new DataModelHelperImpl().writeRepository(obrRepository, writer);
    writer.flush();
    writer.close();
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * @param key//  w w  w . ja  v a  2s .  com
 * @param value
 * @throws IOException
 */
private void send(final String key, final String value) throws IOException {

    final long start = System.currentTimeMillis();

    final StringBuilder message = new StringBuilder(head);
    message.append(encodeBase64(key));
    message.append(middle);
    message.append(encodeBase64(value == null ? "" : value));
    message.append(tail);

    logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value));
    logger.trace(bundle.getString("zabbix-sender-detailed-message", message));

    Socket socket = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

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

        in = socket.getInputStream();
        final int read = in.read(response);

        final String resp = new String(response);
        logger.debug(bundle.getString("zabbix-sender-received-response", resp));
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp));
        }

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

    final long elapsed = System.currentTimeMillis() - start;
    logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed));
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void loadBoards() {
    ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
        private List<NoticeListData> result = new ArrayList<NoticeListData>();

        @Override//from   w w w.j  av a  2  s  . c  om
        protected Boolean doInBackground(String... params) {
            URL obj = null;
            try {
                obj = new URL("http://165.194.104.22:5000/board_notice");
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                //implement below code if token is send to server
                con = ConnectServer.getInstance().setHeader(con);

                con.setDoOutput(true);

                OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                wr.flush();

                BufferedReader rd = null;

                if (con.getResponseCode() == 200) {
                    rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                    String tmpString = rd.readLine();

                    JSONArray jsonArray = new JSONArray(tmpString);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);

                        Integer num = (Integer) object.get("num");
                        String title = (String) object.get("title");
                        String content = (String) object.get("content");
                        String time = (String) object.get("time");
                        Boolean isSignNeed = ((Integer) object.get("isSignNeed") != 0);
                        Boolean isImportant = ((Integer) object.get("isImportant") != 0);
                        Boolean isSignFinished = ((Integer) object.get("isSignFinished") != 0);

                        result.add(new NoticeListData(title, time, content, isSignNeed, isImportant,
                                isSignFinished));
                    }
                    Log.d("---- success ----", tmpString);
                } else {
                    rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                    Log.d("---- failed ----", String.valueOf(rd.readLine()));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Boolean value) {
            notice_adapter = new ListViewAdapter(getContext());
            notice_listView.setAdapter(notice_adapter);
            for (int i = 0; i < result.size(); i++) {
                notice_adapter.addNotice(result.get(i).mTitle, result.get(i).mContent, result.get(i).mDate,
                        result.get(i).isSignNeed, result.get(i).isImportant, result.get(i).isSignFinished);
            }
            Log.d(TAG, "notify called");
            notice_adapter.notifyDataSetChanged();
        }

    });
    ConnectServer.getInstance().execute();
}

From source file:org.apache.hadoop.raid.TestHarIndexParser.java

protected void setUp() throws FileNotFoundException, IOException {
    LOG.info("TestHarIndexParser.setUp()");
    indexFile = File.createTempFile("harindex", ".tmp");
    indexFile.deleteOnExit();/*from ww w  . j av  a  2  s.c  om*/
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(indexFile), Charset.forName("UTF-8"));
    out.write("%2F dir 1282018162460+0+493+hadoop+hadoop 0 0 f1 f2 f3 f4\n");
    out.write("%2Ff1 file part-0 0 1024 1282018141145+1282018140822+420+hadoop+hadoop\n");
    out.write("%2Ff3 file part-0 2048 1024 1282018148590+1282018148255+420+hadoop+hadoop\n");
    out.write("%2Ff2 file part-0 1024 1024 1282018144198+1282018143852+420+hadoop+hadoop\n");
    out.write("%2Ff4 file part-1 0 1024000 1282018162959+1282018162460+420+hadoop+hadoop\n");
    out.flush();
    out.close();
}

From source file:musite.io.xml.ProteinResidueAnnotationWriter.java

public void write(OutputStream os, Map<String, MultiMap<Integer, Map<String, Object>>> residueAnnotations)
        throws IOException {
    if (os == null || residueAnnotations == null)
        return;/*from w  w  w .  j a v  a 2 s. co  m*/

    String prefix = StringUtils.repeat("\t", getIndent());

    OutputStreamWriter osw = new OutputStreamWriter(os);
    BufferedWriter bufWriter = new BufferedWriter(osw);

    for (Map.Entry<String, MultiMap<Integer, Map<String, Object>>> entry : residueAnnotations.entrySet()) {
        String type = entry.getKey();
        bufWriter.write(prefix + "<" + type + ">\n");
        writeMultiMap(os, bufWriter, entry.getValue(), prefix + "\t");
        bufWriter.write(prefix + "</" + type + ">\n");
    }

    bufWriter.flush();
    osw.flush();
}

From source file:clientserver.ServerThread.java

final void initClientData() {
    try {//from   w w w .  j a v a2 s .c o  m
        OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
        JSONObject jWriteobj = new JSONObject();
        jWriteobj.put("name1", "sp_on");
        jWriteobj.put("value1", 245);
        jWriteobj.put("name2", "sp_off");
        jWriteobj.put("value2", 45);
        jWriteobj.put("name3", "mc_on");
        jWriteobj.put("value3", 3455);
        jWriteobj.put("name4", "mc_off");
        jWriteobj.put("value4", 2045);
        os.write(jWriteobj.toString());
        os.flush();
    } catch (IOException e) {
        System.out.println("Write socket closing" + e.getMessage());
    }
}

From source file:com.tqlab.plugin.mybatis.maven.MyBatisGeneratorMojo.java

private MybatisExecutorCallback createMybatisExecutorCallback() {

    return new MybatisExecutorCallback() {

        private List<String> jdbcConfig = new ArrayList<String>();
        private List<String> springConfig = new ArrayList<String>();
        private List<String> osgiConfig = new ArrayList<String>();

        @Override//from   ww w.  j  av  a 2  s.  c o  m
        public void onWriteJdbcConfig(String str) {
            jdbcConfig.add(str);
        }

        @Override
        public void onWriteSpringConfig(String str) {
            springConfig.add(str);
        }

        @Override
        public void onWriteOsgiConfig(String str) {
            osgiConfig.add(str);
        }

        @Override
        public void onFinsh(boolean overwrite) throws IOException {

            if (jdbcConfig.size() > 0) {
                this.write(outputDirectory.getAbsolutePath() + File.separator + "src/main/resources/",
                        "jdbc.properties", "jdbc.template", "${jdbc}", getConfigStr(jdbcConfig), true);
            }

            if (springConfig.size() > 0) {
                this.write(
                        outputDirectory.getAbsolutePath() + File.separator
                                + "src/main/resources/META-INF/spring/",
                        "common-db-mapper.xml", "common-db-mapper.template", "${beans}",
                        getConfigStr(springConfig), overwrite);
            }

            if (osgiConfig.size() > 0) {
                this.write(
                        outputDirectory.getAbsolutePath() + File.separator
                                + "src/main/resources/META-INF/spring/",
                        "common-dal-osgi.xml", "common-dal-osgi.template", "${osgi}", getConfigStr(osgiConfig),
                        overwrite);
            }

        }

        @Override
        public String getJdbcConfigPostfix() {
            return jdbcConfig.size() == 0 ? "" : "." + jdbcConfig.size();
        }

        @Override
        public String getStringConfigPostfix() {
            return springConfig.size() == 0 ? "" : "." + springConfig.size();
        }

        @Override
        public String getOsgiConfigPostfix() {
            return osgiConfig.size() == 0 ? "" : "." + osgiConfig.size();
        }

        private String getConfigStr(List<String> list) {
            if (null == list) {
                return "";
            }
            String str = "";
            for (String s : list) {
                str += s + "\r\n";
            }
            return str;
        }

        private void write(String outDir, String fileName, String templateName, String replaceStr,
                String repalceValue, boolean overwrite) throws IOException {

            InputStream is = this.getClass().getResourceAsStream("/" + templateName);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer buf = new StringBuffer();
            while (null != (line = br.readLine())) {
                buf.append(line);
                buf.append(Constants.LINE_SEPARATOR);
            }

            String result = buf.toString().replace(replaceStr, repalceValue);
            File dir = new File(outDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String outputPath = dir + File.separator + fileName;

            if (!overwrite) {
                File file = new File(outputPath);
                while (file.exists()) {
                    String name = getFileName(file.getName());
                    outputPath = dir + File.separator + name;
                    file = new File(outputPath);
                }
            }

            this.write(outputPath, result);
        }

        private void write(String filePath, String str) throws IOException {
            File file = new File(filePath);

            if (file.getParentFile() != null && !file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            writer.write(str);
            writer.flush();
            writer.close();

            MyBatisGeneratorMojo.this.getLog().info(str);

        }

        private String getFileName(String name) {
            int index = name.lastIndexOf(".");
            if (index > 0) {
                String temp1 = name.substring(0, index);
                String temp2 = name.substring(index + 1);
                try {
                    Integer i = Integer.parseInt(temp2);
                    i++;
                    temp1 = temp1 + "." + i;
                    return temp1;
                } catch (Exception e) {
                    return name + ".1";
                }
            }
            return name + ".1";
        }

    };
}

From source file:org.broadleafcommerce.common.vendor.service.AbstractVendorService.java

protected InputStream postMessage(Map<String, String> content, URL destination, String encodeCharset)
        throws IOException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setDoInput(true);//w w w. j  ava 2s.c o m
    connection.setDoOutput(true);
    connection.setRequestMethod(POST_METHOD);

    OutputStreamWriter osw = null;
    try {
        osw = new OutputStreamWriter(connection.getOutputStream());
        boolean isFirst = true;
        for (String key : content.keySet()) {
            if (!isFirst) {
                osw.write("&");
            }
            isFirst = false;
            String value = content.get(key);
            osw.write(URLEncoder.encode(key, encodeCharset));
            osw.write("=");
            osw.write(URLEncoder.encode(value, encodeCharset));
        }
        osw.flush();
        osw.close();
    } catch (IOException e) {
        // We'll try to avoid stopping processing and just log the error if the OutputStream doesn't close
        LOG.error("Problem closing the OuputStream to destination: " + destination.toExternalForm(), e);
    } finally {
        if (osw != null) {
            try {
                osw.close();
            } catch (Throwable e) {
            }
        }
    }

    return new BufferedInputStream(connection.getInputStream());
}

From source file:markson.visuals.sitapp.settingActivity.java

public void WriteSettings(Context context, String data) {

    FileOutputStream fOut = null;

    OutputStreamWriter osw = null;

    try {//from ww w  . ja v  a  2s.c  o  m

        fOut = openFileOutput("settings.dat", MODE_PRIVATE);

        osw = new OutputStreamWriter(fOut);

        osw.write(data);

        osw.flush();

        //Toast.makeText(context, "Classes Saved",Toast.LENGTH_SHORT).show();

    }

    catch (Exception e) {

        e.printStackTrace();

        Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();

    }

    finally {

        try {

            osw.close();

            fOut.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

From source file:org.gbif.portal.web.controller.dataset.LogQuery.java

/**
 * Add template to output/*w ww.j av a 2  s  . com*/
 * 
 * @param outputStream
 * @param velocityContext
 * @param tu
 * @param templatePath
 * @param fileName
 * @throws IOException
 * @throws ResourceNotFoundException
 * @throws ParseErrorException
 * @throws Exception
 * @throws MethodInvocationException
 */
private void addTemplate(OutputStream outputStream, VelocityContext velocityContext, TemplateUtils tu,
        String templatePath, String fileName) throws IOException, ResourceNotFoundException,
        ParseErrorException, Exception, MethodInvocationException {
    ((ZipOutputStream) outputStream).closeEntry();
    ((ZipOutputStream) outputStream).putNextEntry(new ZipEntry(fileName));
    Template template = Velocity.getTemplate(templatePath);
    template = Velocity.getTemplate(templatePath);
    template.initDocument();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);
    tu.merge(template, velocityContext, writer);
    writer.flush();
}