Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

In this page you can find the example usage for java.io BufferedWriter flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

public static void main(String[] args) throws Exception {

    List<String> params = new ArrayList<>();
    // System.out.println(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    Path path = Paths.get(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) {
        // System.out.println(reader.readLine().length());
        String line;/* w w w .  ja va2  s  . co m*/
        while ((line = reader.readLine()) != null) {
            // System.out.println("TEXT LINE:" + line);
            params.add(line);
        }
    }

    Path succeededFile = Paths.get(SuperPassQueryTest.class.getResource("/succeeded.dat").toURI());
    BufferedWriter succeededWriter = Files.newBufferedWriter(succeededFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);
    Path failedFile = Paths.get(SuperPassQueryTest.class.getResource("/failed.dat").toURI());
    BufferedWriter failedWriter = Files.newBufferedWriter(failedFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);

    for (String param : params) {
        try {
            /*
            StringTokenizer stringTokenizer = new StringTokenizer(param, ",");
            while(stringTokenizer.hasMoreTokens()){
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            System.out.println("VALUE:" + stringTokenizer.nextToken());
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            }
            */

            System.out.println("QUERY PARAMS:" + param);
            String[] paramArray = param.split(",");
            // System.out.println("VALUE:" + paramArray[0]);
            // System.out.println("VALUE:" + paramArray[1]);
            // System.out.println("VALUE:" + paramArray[2]);

            String value_1 = paramArray[0];
            String value_2 = paramArray[1];
            String value_3 = paramArray[2];

            String serviceName = "eport.superpass.spdec.DecQueryListService";
            byte[] requestContext = ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n"
                    + "<RequestContext>\n" + "    <Group name=\"SystemInfo\">\n"
                    + "        <Key name=\"NAME_FULL\">???</Key>\n"
                    + "        <Key name=\"ClientId\">5300001976914</Key>\n"
                    + "        <Key name=\"CertNo\">df630b</Key>\n"
                    + "        <Key name=\"SaicSysNo\">766350979</Key>\n"
                    + "        <Key name=\"DEP_IN_CODE\">5300</Key>\n"
                    + "        <Key name=\"REG_CO_CGAC\">4403180237</Key>\n"
                    + "        <Key name=\"ENT_SEQ_NO\">000000000000315537</Key>\n"
                    + "        <Key name=\"ENT_TYPE\">3</Key>\n"
                    + "        <Key name=\"IcCode\">8930000011040</Key>\n"
                    + "        <Key name=\"OperatorName\">?</Key>\n"
                    + "        <Key name=\"DEP_CODE_CHG\">5305</Key>\n"
                    + "        <Key name=\"SessionId\">AE2533938D521A9972186B07BBBEB244</Key>\n"
                    + "    </Group>\n" + "    <Group name=\"DataPresentation\">\n"
                    + "        <Key name=\"SignatureAlgorithm\"/>\n"
                    + "        <Key name=\"EncryptAlgorithm\"/>\n"
                    + "        <Key name=\"CompressAlgorithm\"/>\n" + "    </Group>\n"
                    + "    <Group name=\"Default\">\n"
                    + "        <Key name=\"clientSystemId\">0400620001</Key>\n"
                    + "        <Key name=\"needWebInvoke\">True</Key>\n" + "    </Group>\n"
                    + "</RequestContext>").getBytes();

            byte[] requestData = ("<?xml version=\"1.0\"?>\n"
                    + "<DecQueryListRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"
                    + "  <OperType>0</OperType>\n" + "  <DecType>\n" + "    <TrnType>0</TrnType>\n"
                    + "    <IEFlag>" + value_3 + "</IEFlag>\n" + "    <DecSubType />\n" + "  </DecType>\n"
                    + "  <CopeCode>766350979</CopeCode>\n" + "  <AgentCode>4403180237</AgentCode>\n"
                    + "  <SeqNo>" + value_1 + "</SeqNo>\n" + "  <UserType>0</UserType>\n"
                    + "</DecQueryListRequest>").getBytes();

            Holder<byte[]> responseData = new Holder<>();

            // <?xml version="1.0" encoding="UTF-8" standalone="no"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name="DataPresentation"><Key name="CompressAlgorithm"/><Key name="SignatureAlgorithm"/><Key name="EncryptAlgorithm"/></Group></ResponseContext>
            // <?xml version="1.0" encoding="UTF-8" standalone="yes"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>
            // String responseContext = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name=\"DataPresentation\"><Key name=\"CompressAlgorithm\"/><Key name=\"SignatureAlgorithm\"/><Key name=\"EncryptAlgorithm\"/></Group></ResponseContext>";
            // String queryListResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>";

            String responseContext = new String(
                    superPass.service(serviceName, requestContext, requestData, responseData));
            String queryListResponse = new String(responseData.value);
            System.out.println("RESPONSE_CONTEXT:" + responseContext);
            System.out.println("QUERY_LIST_RESPONSE:" + queryListResponse);

            String serviceResponseCode = parsingReceiptStatus(responseContext);
            System.out.println("SERVICE_RESPONSE_CODE:" + serviceResponseCode);
            if (serviceResponseCode.equals("0")) {
                String data = parsingReceiptData(queryListResponse);
                System.out.println("DATA:" + data);
                succeededWriter.write(data);
                succeededWriter.flush();
            } else {
                failedWriter.write(param + "\n");
                failedWriter.flush();
            }
            Thread.sleep(6 * 1000);
        } catch (Exception e) {
            failedWriter.write(param + "\n");
            failedWriter.flush();
        }
    }
    succeededWriter.close();
    failedWriter.close();
}

From source file:json_to_xml_1.java

public static void main(String args[]) {
    System.out.print("json_to_xml_1 workflow Copyright (C) 2016 Stephan Kreutzer\n"
            + "This program comes with ABSOLUTELY NO WARRANTY.\n"
            + "This is free software, and you are welcome to redistribute it\n"
            + "under certain conditions. See the GNU Affero General Public License 3\n"
            + "or any later version for details. Also, see the source code repository\n"
            + "https://github.com/publishing-systems/digital_publishing_workflow_tools/ and\n"
            + "the project website http://www.publishing-systems.org.\n\n");

    json_to_xml_1 converter = json_to_xml_1.getInstance();

    converter.getInfoMessages().clear();

    try {//from   ww w.  j  av a  2s  .  c  o m
        converter.execute(args);
    } catch (ProgramTerminationException ex) {
        converter.handleTermination(ex);
    }

    if (converter.resultInfoFile != null) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(converter.resultInfoFile), "UTF-8"));

            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write(
                    "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n");
            writer.write("<json-to-xml-1-result-information>\n");

            if (converter.getInfoMessages().size() <= 0) {
                writer.write("  <success/>\n");
            } else {
                writer.write("  <success>\n");
                writer.write("    <info-messages>\n");

                for (int i = 0, max = converter.getInfoMessages().size(); i < max; i++) {
                    InfoMessage infoMessage = converter.getInfoMessages().get(i);

                    writer.write("      <info-message number=\"" + i + "\">\n");
                    writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                    String infoMessageText = infoMessage.getMessage();
                    String infoMessageId = infoMessage.getId();
                    String infoMessageBundle = infoMessage.getBundle();
                    Object[] infoMessageArguments = infoMessage.getArguments();

                    if (infoMessageBundle != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                        infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                        infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                        writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                    }

                    if (infoMessageId != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                        infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                        infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                        writer.write("        <id>" + infoMessageId + "</id>\n");
                    }

                    if (infoMessageText != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                        infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                        infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                        writer.write("        <message>" + infoMessageText + "</message>\n");
                    }

                    if (infoMessageArguments != null) {
                        writer.write("        <arguments>\n");

                        int argumentCount = infoMessageArguments.length;

                        for (int j = 0; j < argumentCount; j++) {
                            if (infoMessageArguments[j] == null) {
                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class></class>\n");
                                writer.write("            <value>null</value>\n");
                                writer.write("          </argument>\n");

                                continue;
                            }

                            String className = infoMessageArguments[j].getClass().getName();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            className = className.replaceAll("&", "&amp;");
                            className = className.replaceAll("<", "&lt;");
                            className = className.replaceAll(">", "&gt;");

                            String value = infoMessageArguments[j].toString();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            value = value.replaceAll("&", "&amp;");
                            value = value.replaceAll("<", "&lt;");
                            value = value.replaceAll(">", "&gt;");

                            writer.write("          <argument number=\"" + j + "\">\n");
                            writer.write("            <class>" + className + "</class>\n");
                            writer.write("            <value>" + value + "</value>\n");
                            writer.write("          </argument>\n");
                        }

                        writer.write("        </arguments>\n");
                    }

                    Exception exception = infoMessage.getException();

                    if (exception != null) {
                        writer.write("        <exception>\n");

                        String className = exception.getClass().getName();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        className = className.replaceAll("&", "&amp;");
                        className = className.replaceAll("<", "&lt;");
                        className = className.replaceAll(">", "&gt;");

                        writer.write("          <class>" + className + "</class>\n");

                        StringWriter stringWriter = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(stringWriter);
                        exception.printStackTrace(printWriter);
                        String stackTrace = stringWriter.toString();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        stackTrace = stackTrace.replaceAll("&", "&amp;");
                        stackTrace = stackTrace.replaceAll("<", "&lt;");
                        stackTrace = stackTrace.replaceAll(">", "&gt;");

                        writer.write("          <stack-trace>" + stackTrace + "</stack-trace>\n");
                        writer.write("        </exception>\n");
                    }

                    writer.write("      </info-message>\n");
                }

                writer.write("    </info-messages>\n");
                writer.write("  </success>\n");
            }

            writer.write("</json-to-xml-1-result-information>\n");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    converter.getInfoMessages().clear();
    converter.resultInfoFile = null;
}

From source file:Main.java

public static String getURLContent(String urlStr) throws Exception {
    URL url = new URL(urlStr);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);//from  w w  w .  j  a va 2s.c  o m
    connection.connect();
    OutputStream ous = connection.getOutputStream();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ous));
    bw.write("index.htm");
    bw.flush();
    bw.close();

    printRequestHeaders(connection);
    InputStream ins = connection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(ins));
    StringBuffer sb = new StringBuffer();
    String msg = null;
    while ((msg = br.readLine()) != null) {
        sb.append(msg);
        sb.append("\n"); // Append a new line
    }
    br.close();
    return sb.toString();
}

From source file:Main.java

public static void writeTextFile(File file, String text) {
    try {//from w  w  w.ja  v a2 s . c o  m
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(text);
        bw.flush();
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void writeToFile(Context context, String file, String content) throws IOException {
    FileOutputStream fos = context.openFileOutput(file, Context.MODE_PRIVATE);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    bw.write(content);/*from  www  .  j  av a2s.c o m*/
    bw.flush();
    bw.close();
    fos.close();
}

From source file:Main.java

/**
 * /*from  w  w  w .  ja  va  2  s  . c  o  m*/
 * @param os
 * @param request
 * @param charsetName
 * @throws IOException
 */
public static final void writeString(OutputStream os, String request, String charsetName) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(os, charsetName);
    BufferedWriter bw = new BufferedWriter(writer);
    bw.write(request);
    bw.write("\r\n");
    bw.flush();
}

From source file:Main.java

/**
 * Saves passed string to file//from ww  w. j ava  2  s. c  om
 *
 * @param filename      path to file
 * @param stringToWrite string to save
 */
public static void stringToFile(String filename, String stringToWrite) {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
        writer.write(stringToWrite);
        writer.flush();
        writer.close();
    } catch (Exception ignored) {
    }
}

From source file:com.reversemind.glia.test.go3.java

public static void save(String fileName, String string) throws Exception {

    BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)));
    bw.write(string + "\n");
    bw.flush();
    bw.close();//from w w  w .  j  a v a2 s  .  co  m

}

From source file:Main.java

public static void write(String text, File dst) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(dst));
    bufferedWriter.write(text);//from  ww w  . jav  a 2 s .  c  om
    bufferedWriter.flush();
    bufferedWriter.close();
}

From source file:Main.java

public static Process execute(String command) throws Exception {
    final Process process = new ProcessBuilder("sh").redirectErrorStream(true).start();

    BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

    stdOutput.write(command + "; exit\n");
    stdOutput.flush();
    stdOutput.close();//from w w  w . j a  va 2 s . co m

    return process;
}