Example usage for java.io PrintWriter flush

List of usage examples for java.io PrintWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:io.mindmaps.graql.GraqlShell.java

public static void runShell(String[] args, String version, GraqlClient client) {

    Options options = new Options();
    options.addOption("n", "name", true, "name of the graph");
    options.addOption("e", "execute", true, "query to execute");
    options.addOption("f", "file", true, "graql file path to execute");
    options.addOption("u", "uri", true, "uri to connect to engine");
    options.addOption("h", "help", false, "print usage message");
    options.addOption("v", "version", false, "print version");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//  w  ww  .ja va 2 s. c om

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return;
    }

    String query = cmd.getOptionValue("e");
    String filePath = cmd.getOptionValue("f");

    // Print usage message if requested or if invalid arguments provided
    if (cmd.hasOption("h") || !cmd.getArgList().isEmpty()) {
        HelpFormatter helpFormatter = new HelpFormatter();
        PrintWriter printWriter = new PrintWriter(System.out);
        int width = helpFormatter.getWidth();
        int leftPadding = helpFormatter.getLeftPadding();
        int descPadding = helpFormatter.getDescPadding();
        helpFormatter.printHelp(printWriter, width, "graql.sh", null, options, leftPadding, descPadding, null);
        printWriter.flush();
        return;
    }

    if (cmd.hasOption("v")) {
        System.out.println(version);
        return;
    }

    String namespace = cmd.getOptionValue("n", DEFAULT_NAMESPACE);
    String uriString = cmd.getOptionValue("u", DEFAULT_URI);

    try (GraqlShell shell = new GraqlShell(namespace)) {
        client.connect(shell, new URI("ws://" + uriString + REMOTE_SHELL_URI));

        if (filePath != null) {
            query = loadQuery(filePath);
        }

        if (query != null) {
            shell.executeQuery(query);
            shell.commit();
        } else {
            shell.executeRepl();
        }
    } catch (IOException | InterruptedException | ExecutionException | URISyntaxException e) {
        System.err.println(e.toString());
    } finally {
        client.close();
    }
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void deleteActivityTemplates(Object caller) throws IOException, InterruptedException {
    String[] cmd = null;//from  w w w  .ja  v  a  2s .  c  om

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    String tmpdir = getTempLocation();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
    unZip(bufferedInputStream, tmpdir);

    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            if (mobileTemplate != null)
                mobileTemplate.delete(caller);

            if (officeTemplate != null)
                officeTemplate.delete(caller);
        } catch (IOException ex) {
            PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
            printWriter.println("@echo off");
            printWriter.println("del \"" + templatePath + mobileServicesTemplateName + "\" /Q /S");
            printWriter.println("del \"" + templatePath + officeTemplateName + "\" /Q /S");
            printWriter.flush();
            printWriter.close();

            String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

            cmd = tmpcmd;

            ArrayList<String> tempenvlist = new ArrayList<String>();
            for (String envval : System.getenv().keySet())
                tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

            tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
            env = new String[tempenvlist.size()];
            tempenvlist.toArray(env);

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd, env, new File(tmpdir));
            proc.waitFor();
        }
    } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
        VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
        VirtualFile officeTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + officeTemplateName));

        if (mobileTemplate != null && officeTemplate != null) {
            exec(new String[] { "osascript", "-e",
                    "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                    "-e", "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\"" },
                    tmpdir);
        }
    } else {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            mobileTemplate.delete(caller);
            officeTemplate.delete(caller);
        } catch (IOException ex) {

            JPasswordField pf = new JPasswordField();
            int okCxl = JOptionPane.showConfirmDialog(null, pf,
                    "To copy Microsoft Services templates, the plugin needs your password:",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (okCxl == JOptionPane.OK_OPTION) {
                String password = new String(pf.getPassword());

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName },
                        tmpdir);

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
            }
        }
    }
}

From source file:com.tractionsoftware.reshoot.Reshoot.java

private static void showUsageAndExit(org.apache.commons.cli.Options options) {
    PrintWriter pw = new PrintWriter(System.out);

    pw.println("Reshoot uses Selenium WebDriver to automate shooting product screenshots");
    pw.println();//from w w w.jav  a  2 s  . c  om
    pw.println("  Usage:");
    pw.println("    java -jar Reshoot.jar [options] [files...]");
    pw.println();
    pw.println("  Options:");

    HelpFormatter formatter = new HelpFormatter();
    formatter.printOptions(pw, 74, options, 1, 2);

    pw.println();
    pw.println("  Documentation:");
    pw.println("    https://github.com/tractionsoftware/reshoot");
    pw.println();

    pw.flush();
    System.exit(1);
}

From source file:eu.annocultor.converters.europeana.EuropeanaSolrDocumentTagger.java

public static void start(String solrServerFrom, String solrServerTo, String query, int start)
        throws MalformedURLException, Exception {

    Environment environment = new EnvironmentImpl();

    PrintWriter log = new PrintWriter(
            new FileWriter(new File(environment.getAnnoCultorHome(), "enrichment.log")));
    try {//w ww  .j  a  va2s .  c o  m
        EuropeanaSolrDocumentTagger tagger = new EuropeanaSolrDocumentTagger(query, solrServerFrom,
                solrServerTo, start, log);
        tagger.init("Europeana");
        if (start == 0) {
            tagger.clearDestination(query);
        }
        tagger.tag();
        tagger.report();
        ReportPresenter.generateReport(environment.getAnnoCultorHome());
    } catch (Exception e) {
        e.printStackTrace(new PrintWriter(log));
    } finally {
        log.write("SEMANTIC ENRICHMENT COMPLETED");
        log.flush();
        log.close();
    }
}

From source file:Main.java

/**
 *  This method is used to send a XML request file to web server to process the request and return
 *  xml response containing event id./*from w  w  w.ja  va 2  s . co  m*/
 */
public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception {

    System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server .......");

    InputStream in = null;
    BufferedReader bufferedReader = null;
    OutputStream out = null;
    PrintWriter printWriter = null;
    StringBuffer responseMessageBuffer = new StringBuffer("");

    try {
        URL url = new URL(postUrl);
        URLConnection con = url.openConnection();

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "text/xml");
        con.setReadTimeout(readTimeout);
        out = con.getOutputStream();
        // Write the arguments as post data
        printWriter = new PrintWriter(out);

        printWriter.println(xml);
        printWriter.flush();

        //Process response and return back to caller function
        in = con.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        String tempStr = null;

        int tempClearResponseMessageBufferCounter = 0;
        while ((tempStr = bufferedReader.readLine()) != null) {
            tempClearResponseMessageBufferCounter++;
            //clear the buffer for the first time
            if (tempClearResponseMessageBufferCounter == 1)
                responseMessageBuffer.setLength(0);
            responseMessageBuffer.append(tempStr);
        }

    } catch (Exception ex) {
        throw ex;
    } finally {
        System.out.println("Calling finally in POSTXML");
        try {
            if (in != null)
                in.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Input Stream in try");
        }
        try {
            if (out != null)
                out.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Output Stream in try");
        }

    }
    System.out.println("XMLUtils.postXMLWithTimeout: end .......");
    return responseMessageBuffer.toString();
}

From source file:com.ms.commons.test.tool.GenerateTestCase.java

private static void writeAddedMembersToTestFile(File testFile, List<MethodDeclaration> addedMethods,
        StringBuilder testUnitReadEncoding) {
    try {//www  .j av a2 s. c om
        String code = readCodeFromFile(testFile, new StringBuilder());

        String codePart1 = code.substring(0, code.lastIndexOf('}'));
        String codePart2 = code.substring(code.lastIndexOf('}'));

        StringWriter sw = new StringWriter();
        PrintWriter newMethodsCode = new PrintWriter(sw);

        for (MethodDeclaration method : addedMethods) {
            newMethodsCode.println();
            String me = method.toString();
            BufferedReader br = new BufferedReader(new StringReader(me));
            for (String l; (l = br.readLine()) != null;) {
                newMethodsCode.println("    " + l);
            }
        }
        newMethodsCode.flush();

        String newCode = codePart1 + sw + codePart2;

        // check if have syntax error
        JavaParser.parse(convertStringToInputstream(newCode, "UTF-8"), "UTF-8");

        FileUtils.writeStringToFile(testFile, newCode, testUnitReadEncoding.toString());
    } catch (Exception e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static HttpResp response(HttpResponse response) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter printer = new PrintWriter(baos);

    printer.print(response.getStatusLine() + "");
    printer.print("\n");

    Map<String, String> headers = U.map();

    for (Header hdr : response.getAllHeaders()) {
        printer.print(hdr.getName());//from   www  .  jav  a 2  s  . c  om
        printer.print(": ");
        printer.print(hdr.getValue());
        printer.print("\n");

        headers.put(hdr.getName(), hdr.getValue());
    }

    printer.print("\n");
    printer.flush();

    HttpEntity entity = response.getEntity();
    byte[] body = entity != null ? IO.loadBytes(response.getEntity().getContent()) : new byte[0];

    baos.write(body);
    byte[] raw = baos.toByteArray();

    return new HttpResp(raw, response.getStatusLine().getStatusCode(), headers, body);
}

From source file:at.tuwien.ifs.somtoolbox.data.InputDataWriter.java

public static void writeAsSOMLib(TemplateVector tv, String fileName) throws IOException {
    Logger.getLogger("at.tuwien.ifs.somtoolbox")
            .info("Start writing new  template vector to '" + fileName + "'.");
    PrintWriter writer = FileUtils.openFileForWriting("Template Vector", fileName, fileName.endsWith(".gz"));
    writeTempplateHeaderToFile(writer, fileName, tv.numVectors(), tv.dim(), tv.numinfo());
    for (int i = 0; i < tv.dim(); i++) {
        writeElementToFile(writer, i, tv.getElement(i));
    }//ww w.j  a v  a  2 s .  c  o  m
    writer.flush();
    writer.close();
    Logger.getLogger("at.tuwien.ifs.somtoolbox").info("Finished.");
}

From source file:expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>.//from w ww  . j  a v  a 2 s .  c o m
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        System.out.println("Request sent");

        System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            System.out.println(line);
        System.out.println("Received response");
        if (line == null)
            System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}

From source file:com.quattroresearch.helm.HlConfigEntry.java

public static void handleInputOutputFiles(String ifilename, String ofilename)
        throws IOException, JDOMException {
    BufferedReader br = new BufferedReader(new FileReader(ifilename));
    PrintWriter pw = new PrintWriter(ofilename);
    String helmString;// w w w . java  2 s  .  c om

    // initialize the output HTML file:
    pw.println("<html>\n<head>\n<meta charset=\"UTF-8\">\n<font style=\"font-size: "
            + defaultFontsizeEntry.value + "pt\">\n</head>\n<body>");

    while ((helmString = br.readLine()) != null) { // read and process all HELM2-Strings from the input file
        processHelmString(helmString, pw);
    }
    br.close();

    pw.println("</body>\n</html>"); // write out the closing HTML sequence
    pw.flush();
    pw.close();
}