Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:com.example.jarida.http.AsyncConnection.java

@Override
public String doInBackground(String... params) {
    final String method = params[0];
    final String urlString = params[1];

    final StringBuilder builder = new StringBuilder();

    try {// w w  w.  ja  va2s.c om
        final URL url = new URL(urlString);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);

        if (method.equals(METHOD_POST)) {
            final String urlParams = params[2];
            conn.setRequestProperty(HTTP.CONTENT_LEN, "" + Integer.toString(urlParams.getBytes().length));
            System.out.println(urlParams);
            // Send request
            final DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(urlParams);
            wr.flush();
            wr.close();
        }

        // Get Response
        final InputStream is = conn.getInputStream();
        final BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
        rd.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return builder.toString();
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** returns an oauth token for the user's CSE. returns null if login failed. */
public static String authenticate(String login, String password) {
    //System.out.println("About to post\nURL: "+target+ "content: " + content);
    String authToken = null;/*from  w w w.java2s.co  m*/
    String response = "";
    try {
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        URLConnection conn = url.openConnection();
        // Set connection parameters.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        // Make server believe we are form data...

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        // TODO: escape password, we'll fail if password has &
        // login = "musetestlogin1";
        // password = "whowonthelottery";
        String content = "accountType=HOSTED_OR_GOOGLE&Email=" + login + "&Passwd=" + password
                + "&service=cprose&source=muse.chrome.extension";
        out.writeBytes(content);
        out.flush();
        out.close();

        // Read response from the input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        temp = null;
        in.close();
        log.info("Obtaining auth token: Server response:\n'" + response + "'");

        String delimiter = "Auth=";
        /* given string will be split by the argument delimiter provided. */
        String[] token = response.split(delimiter);
        authToken = token[1];
        authToken = authToken.trim();
        authToken = authToken.replaceAll("(\\r|\\n)", "");
        log.info("auth token: " + authToken);
        return authToken;
    } catch (Exception e) {
        log.warn("Unable to authorize: " + e.getMessage());
        return null;
    }
}

From source file:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {/*from   www. ja  v a  2 s  . c om*/
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

private void sendRequest(String urlParameters, HttpURLConnection connection) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("sending the request: " + urlParameters);
    }/* w ww.  j  a v a 2  s .c  o m*/
    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
}

From source file:com.acc.util.InstagramClient.java

public String getProfilePicOfUser(final String code) {

    String profilePic = null;/*from  w  w w  .  j  a  v  a  2s.  com*/
    //      final String inputJson = "client_id=e580d04d0687403189f86d49545b69a4&client_secret=a2943297f601402d894f8d21400bdfd5&grant_type=authorization_code&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage&code="
    //            + code;

    //String inputJson1 = "{\"Identities\": [{\"Score\": \"99.99986\",\"IdentityDetails\": {\"BiographicData\": [{\"Key\": \"Name\",\"Value\": \"Ravi\"},{\"Key\": \"ID\",\"Value\": \"DRIVING_LICENSE_ID\"}],\"BiometricDatas\": [{\"Base64Data\": \"/9j/4AAQSkZJ\",\"Modality\": \"Face_Face2D\",\"Type\": \"Image\"}],\"IdentityId\": \"BiometricDev[1:S:58840];\"}}],\"InWatchList\": false}";
    //      System.out.println(inputJson);

    // Make Web Service Call

    //      final Client client = ClientBuilder.newClient();
    //      final String instagramOutputJson = client.target("https://api.instagram.com/oauth/access_token").request()
    //            .method("POST", Entity.entity(inputJson, MediaType.APPLICATION_JSON), String.class);

    try {
        final URL url = new URL("https://api.instagram.com/oauth/access_token");
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        final String urlParameters = "client_id=e580d04d0687403189f86d49545b69a4"
                + "&client_secret=a2943297f601402d894f8d21400bdfd5" + "&grant_type=authorization_code"
                + "&redirect_uri=http://electronics.local:9001/yacceleratorstorefront/electronics/en/facerecognitionpage"
                + "&code=" + code;

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        final BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result.toString());
        System.out.println("Output Json from Instagram is " + result);
        profilePic = processJson(result.toString());
    } catch (final MalformedURLException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // YTODO Auto-generated catch block
        e.printStackTrace();
    }
    return profilePic;

}

From source file:com.nokia.dempsy.messagetransport.tcp.TcpSender.java

@Override
public synchronized void send(byte[] messageBytes) throws MessageTransportException {
    try {//from   w w w  .  j  a  v  a  2 s .  c  o m
        DataOutputStream localDataOutputStream = getDataOutputStream();

        localDataOutputStream.writeInt(messageBytes.length);
        localDataOutputStream.flush();
        localDataOutputStream.write(messageBytes);
        localDataOutputStream.flush();
    } catch (IOException ioe) {
        close();
        throw new MessageTransportException(
                "It appears the client " + destination + " is no longer taking calls.", ioe);
    }
}

From source file:ja.lingo.engine.searchindex.NodeSerializer.java

public void close() throws IOException {
    tempDos.close();//w ww  .  ja v a  2s. com

    LOG.info("calculateSize(...) spent " + timeMeasurer);

    long size = Files.length(tempFileName);
    if (size > Integer.MAX_VALUE) {
        States.doThrow("File is \"" + fileName + "\"to large. Maximum allowed size is " + Integer.MAX_VALUE
                + ". Actual size is " + size);
    }

    FileOutputStream fos = new FileOutputStream(fileName);

    DataOutputStream dos = new DataOutputStream(fos);
    serializeNodeHeader(dos, (int) size, firstLevelNodesCount, '\u0000', 0);
    dos.flush();

    EngineFiles.appendFileAndDelete(tempFileName, fos);
    fos.close();
}

From source file:junit.org.rapidpm.microservice.demo.ServletTest.java

@Test
public void testServletPostRequest() throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);//  w  w  w .j a  v  a 2  s. com
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    Assert.assertEquals("Hello World CDI Service", response.toString());

}

From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java

@Override
public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException {

    StringBuilder sb = new StringBuilder();
    sb.append("grant_type=authorization_code");
    sb.append(format("&code=%s", code));
    sb.append(format("&client_id=%s", clientId));
    sb.append(format("&client_secret=%s", clientSecret));
    sb.append(format("&redirect_uri=%s", redirectUrl));

    String parameters = sb.toString();

    URL tokenEndpoint = new URL(config.getTokenEndpoint());
    HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection();
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //connection.addRequestProperty("Authorization", format("Basic %s", credentials()));
    connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length));

    connection.setUseCaches(false);/*from ww w.ja  va 2s . co  m*/
    connection.setDoInput(true);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    //Get Response
    return buildTokenResponse(connection.getInputStream());
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {//from  w  w w . j a v a2 s  . c o m
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}