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.amastigote.xdu.query.module.WaterAndElectricity.java

private Document getPage(String output_data, String host_suffix) throws IOException {
    URL url = new URL(HOST + host_suffix);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + ASP_dot_NET_SessionId);

    httpURLConnection.connect();//  w  ww .j a va 2  s .co  m
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(output_data);
    outputStreamWriter.flush();
    outputStreamWriter.close();
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection.getInputStream()));

    String temp;
    String htmlPage = "";
    while ((temp = bufferedReader.readLine()) != null)
        htmlPage += temp;

    bufferedReader.close();
    httpURLConnection.disconnect();

    htmlPage = htmlPage.replaceAll(" ", " ");

    return Jsoup.parse(htmlPage);
}

From source file:com.votingcentral.services.maxmind.MaxMindGeoLocationService.java

public MaxMindLocationTO getLocation(String ipAddress) {
    MaxMindLocationTO mto = new MaxMindLocationTO();
    String specificData = data + FastURLEncoder.encode(ipAddress, "UTF-8");
    URL url;/*w w  w .j a  v a2  s.co m*/
    OutputStreamWriter wr = null;
    BufferedReader rd = null;
    try {
        url = new URL(surl);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(specificData);
        wr.flush();
        // Get the response
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            String[] values = StringUtils.split(line, ",");
            int maxIndex = values.length - 1;
            if (maxIndex >= 0) {
                mto.setISO3166TwoLetterCountryCode(values[0]);
            }
            if (maxIndex >= 1) {
                mto.setRegionCode(values[1]);
            }
            if (maxIndex >= 2) {
                mto.setCity(values[2]);
            }
            if (maxIndex >= 3) {
                mto.setPostalCode(values[3]);
            }
            if (maxIndex >= 4) {
                mto.setLatitude(values[4]);
            }
            if (maxIndex >= 5) {
                mto.setLongitude(values[5]);
            }
            if (maxIndex >= 6) {
                mto.setMetropolitanCode(values[6]);
            }
            if (maxIndex >= 7) {
                mto.setAreaCode(values[7]);
            }
            if (maxIndex >= 8) {
                mto.setIsp(values[8]);
            }
            if (maxIndex >= 9) {
                mto.setOranization(values[9]);
            }
            if (maxIndex >= 10) {
                mto.setError(MaxMindErrorsEnum.get(values[10]));
            }
        }
    } catch (MalformedURLException e) {
        log.fatal("Issue calling Maxmind", e);
        mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
    } catch (IOException e) {
        log.fatal("Issue reading Maxmind", e);
        mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e1) {
                log.fatal("Issue closing Maxmind", e1);
                mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
            }
        }
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e1) {
                log.fatal("Issue closing Maxmind", e1);
                mto.setError(MaxMindErrorsEnum.VC_INTERNAL_ERROR);
            }
        }
    }
    return mto;
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("ftp")) {
        FTPClient client = null;//w  w  w.j  a  v a 2s.co m
        String host = url.getHost();

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);
        //               System.out.println( "Connected.");

        // After connection attempt, you should check the reply code to verify
        // success.
        int reply = client.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

        //               System.out.println( "Logging in ...");

        if (!client.login(username, password)) {
            //                  System.out.println( "Could not log in.");
            // TODO bring up login dialog?
            client.disconnect();

            throw new IOException("Could not login to FTP Server \"" + host + "\".");
        }

        //               System.out.println( "Logged in.");

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}

From source file:com.google.firebase.auth.migration.AuthMigrator.java

private Task<String> exchangeToken(final String legacyToken) {
    if (legacyToken == null) {
        return Tasks.forResult(null);
    }/* www  . j  av a2s.  com*/
    return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() {
        @Override
        public String call() throws Exception {
            JSONObject postBody = new JSONObject();
            postBody.put("token", legacyToken);
            HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            try {
                osw.write(postBody.toString());
                osw.flush();
            } finally {
                osw.close();
            }
            int responseCode = connection.getResponseCode();

            InputStream is;
            if (responseCode >= 400) {
                is = connection.getErrorStream();
            } else {
                is = connection.getInputStream();
            }
            try {
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int numRead = 0;
                while ((numRead = is.read(buffer)) >= 0) {
                    baos.write(buffer, 0, numRead);
                }
                JSONObject resultObject = new JSONObject(new String(baos.toByteArray()));
                if (responseCode != 200) {
                    throw new FirebaseWebRequestException(
                            resultObject.getJSONObject("error").getString("message"), responseCode);
                }
                return resultObject.getString("token");
            } finally {
                is.close();
            }
        }
    });
}

From source file:com.google.wave.api.AbstractRobotServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    this.req = req;
    // RobotMessageBundleImpl events = deserializeEvents(req);
    //    //  ww  w  .  j a  va2 s.c o  m
    // // Log All Events
    // for (Event event : events.getEvents()) {
    // log(event.getType().toString() + " [" +
    // event.getWavelet().getWaveId() + " " +
    // event.getWavelet().getWaveletId());
    // try {
    // log(" " + event.getBlip().getBlipId() + "] [" +
    // event.getBlip().getDocument().getText().replace("\n", "\\n") + "]");
    // } catch(NullPointerException npx) {
    // log("] [null]");
    // }
    // }

    // processEvents(events);
    // events.getOperations().setVersion(getVersion());
    // serializeOperations(events.getOperations(), resp);

    String events = getRequestBody(req);
    log("Events: " + events);

    JSONSerializer serializer = getJSONSerializer();
    EventMessageBundle eventsBundle = null;
    String proxyingFor = "";

    try {
        JSONObject jsonObject = new JSONObject(events);
        proxyingFor = jsonObject.getString("proxyingFor");
    } catch (JSONException jsonx) {
        jsonx.printStackTrace();
    }

    log(proxyingFor);

    String port = "";
    try {
        port = new JSONObject(proxyingFor).getString("port");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String data = "events=" + URLEncoder.encode(events, "UTF-8");
    // Send the request

    log("port = " + port);

    URL url = new URL("http://jem.thewe.net/" + port + "/wave");
    URLConnection conn = url.openConnection();
    log("no timeout");
    //conn.setReadTimeout(10000);
    //conn.setConnectTimeout(10000);
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    // write parameters
    log("Sending: " + data);
    writer.write(data);

    writer.flush();

    // Get the response
    StringBuffer answer = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        answer.append(line);
    }

    writer.close();
    reader.close();

    log("Answer: " + answer.toString());

    serializeOperations(answer.toString(), resp);
}

From source file:org.apache.flink.streaming.api.functions.source.SocketTextStreamFunctionTest.java

@Test
public void testSocketSourceSimpleOutput() throws Exception {
    ServerSocket server = new ServerSocket(0);
    Socket channel = null;/*from  w  w  w  . j  a  va 2  s .c o  m*/

    try {
        SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n",
                0);

        SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
        runner.start();

        channel = server.accept();
        OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());

        writer.write("test1\n");
        writer.write("check\n");
        writer.flush();
        runner.waitForNumElements(2);

        runner.cancel();
        runner.interrupt();

        runner.waitUntilDone();

        channel.close();
    } finally {
        if (channel != null) {
            IOUtils.closeQuietly(channel);
        }
        IOUtils.closeQuietly(server);
    }
}

From source file:com.personalserver.HomeCommandHandler.java

@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext)
        throws HttpException, IOException {

    this.mHost = httpRequest.getFirstHeader("Host").getValue();
    System.out.println("Host : " + mHost);
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String html = "<html><head></head>" + "<body><center><h1>Welcome to Personal Server<h1></center>"
                    + "<p>to browse file click <a href=\"http://" + mHost + "/dir\">here</a></p>"
                    + "</body></html>";

            // html = AssetsUtils.readHtmlForName(mContext, "home");

            writer.write(html);/* w w w  .  j a  va 2  s  .co  m*/
            writer.flush();
        }
    });

    httpResponse.setHeader("Content-Type", "text/html");
    httpResponse.setEntity(entity);
}

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);//from   w  w w.  j  a v  a2 s .c  o  m
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:com.cmput301w15t15.travelclaimsapp.FileManager.java

/**
 * Saves user to file and attempts to save online if there is an internet connection.
 * /* w  ww . ja  v a2s. c  o  m*/
 * @param User user
 */
public void saveUserInFile(User user) {
    Thread thread = new onlineSaveUserThread(user);
    thread.start();

    try {
        //openFileOutput is a Activity method
        FileOutputStream fos = context.openFileOutput(USERFILENAME, 0);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        gson.toJson(user, osw);
        osw.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        Log.d(TAG, "saveClaimLInFile could not find file: " + e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.d(TAG, "saveClaimLInFile could not find file: " + e.getMessage());
    }
}

From source file:org.elissa.server.AMLSupport.java

/**
 * The POST request.EPCUpload.java// www . j av a2s.  c om
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    PrintWriter out = null;

    FileItem fileItem = null;

    try {
        String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/";

        // Get the PrintWriter
        res.setContentType("text/plain");
        res.setCharacterEncoding("utf-8");

        out = res.getWriter();

        // No isMultipartContent => Error
        final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
        if (!isMultipartContent) {
            printError(out, "No Multipart Content transmitted.");
            return;
        }

        // Get the uploaded file
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        servletFileUpload.setSizeMax(-1);
        final List<?> items;

        items = servletFileUpload.parseRequest(req);
        if (items.size() != 1) {
            printError(out, "Not exactly one File.");
            return;
        }

        fileItem = (FileItem) items.get(0);

        // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd
        String amlStr = fileItem.getString("UTF-8");

        amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\"");

        FileOutputStream fileout = null;
        OutputStreamWriter outwriter = null;

        try {
            fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation());
            outwriter = new OutputStreamWriter(fileout, "UTF-8");
            outwriter.write(amlStr);
            outwriter.flush();

        } finally {
            if (outwriter != null)
                outwriter.close();
            if (fileout != null)
                fileout.close();
        }

        //parse AML file
        AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath());
        parser.parse();
        Collection<EPC> epcs = new HashSet<EPC>();
        Iterator<String> ids = parser.getModelIds().iterator();
        while (ids.hasNext()) {
            String modelId = ids.next();
            epcs.add(parser.getEPC(modelId));
        }

        // serialize epcs to eRDF oryx format
        OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl);
        oryxSerializer.parse();

        Document outputDocument = oryxSerializer.getDocument();

        // get document as string
        String docAsString = "";

        Source source = new DOMSource(outputDocument);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(source, result);
        docAsString = stringWriter.getBuffer().toString();

        // write response
        out.print("" + docAsString + "");

    } catch (Exception e) {
        handleException(out, e);
    } finally {
        if (fileItem != null) {
            fileItem.delete();
        }
    }
}