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:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/*from w w  w .  j a v a2 s  .c  o  m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from w w w  .  ja  va2s .  c om
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:com.shubhangrathore.xposed.xhover.MainActivity.java

/**
 * Restarts SystemUI. Requires SuperUser privilege.
 *
 * @return boolean true if successful, else false.
 *///from   w w w. j  a v  a2 s  .  c om
private boolean restartSystemUi() {
    boolean mSuccessful;
    try {
        Process mProcess = Runtime.getRuntime().exec("su");
        DataOutputStream mDataOutputStream = new DataOutputStream(mProcess.getOutputStream());
        mDataOutputStream.writeBytes("pkill com.android.systemui \n");
        mDataOutputStream.writeBytes("exit\n");
        mDataOutputStream.flush();
        // We wait for the command to be completed
        // before moving forward. This ensures that the method
        // returns only after all the commands' execution is complete.
        mProcess.waitFor();

        if (mProcess.exitValue() == 1) {
            // If control is here, that means the sub process has returned
            // an unsuccessful exit code.
            // Most probably, SuperUser permission was denied
            Log.e(TAG, "Utilities: SuperUser permission denied. Unable to restart SystemUI.");
            mSuccessful = false;
        } else {
            // SuperUser permission granted
            Log.i(TAG, "Utilities: SuperUser permission granted. SystemUI restarted.");
            mSuccessful = true;
        }
    } catch (IOException e) {
        Log.e(TAG, "restartSystemUI: I/O exception");
        mSuccessful = false;
    } catch (InterruptedException e) {
        Log.e(TAG, "restartSystemUI: InterruptedException exception");
        mSuccessful = false;
    }
    return mSuccessful;
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

/**
 * Sends the data to the bStats server.//from  w ww  . ja v a  2 s.  c o m
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}

From source file:com.igormaznitsa.jhexed.swing.editor.filecontainer.FileContainer.java

public void write(final OutputStream out) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    dout.writeInt(MAGIC);/* w  ww  .j av a2s  .c  o m*/
    dout.writeShort(FORMAT_VERSION);

    dout.writeShort(this.sections.size());
    for (final FileContainerSection s : this.sections) {
        s.write(dout);
    }
    dout.writeInt(MAGIC);

    dout.flush();
}

From source file:SortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w w w  . ja  va2s.c  o m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String[] inputString = new String[3];
            int z = 0;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private byte[] getRequest(JSONObject jsonObject) throws Exception {
    byte[] requestBytes = jsonObject.toString().getBytes();

    String header = "ZBXD\1";
    byte[] headerBytes = header.getBytes();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeLong(requestBytes.length);/*from   w w  w.  java2 s. c o m*/
    dos.flush();
    dos.close();
    bos.close();
    byte[] requestLengthBytes = bos.toByteArray();

    byte[] allBytes = new byte[headerBytes.length + requestLengthBytes.length + requestBytes.length];

    int index = 0;
    for (int i = 0; i < headerBytes.length; i++) {
        allBytes[index++] = headerBytes[i];
    }
    for (int i = 0; i < requestLengthBytes.length; i++) {
        allBytes[index++] = requestLengthBytes[7 - i]; // Reverse the byte order.
    }
    for (int i = 0; i < requestBytes.length; i++) {
        allBytes[index++] = requestBytes[i];
    }

    return allBytes;
}

From source file:com.amazon.alexa.avs.auth.companionapp.OAuth2ClientForPkce.java

JsonObject postRequest(HttpURLConnection connection, String data) throws IOException {
    int responseCode = -1;
    InputStream error = null;//from   w w w  . j a  va2  s  .  co m
    InputStream response = null;
    DataOutputStream outputStream = null;
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(data.getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    outputStream.close();
    responseCode = connection.getResponseCode();

    try {
        response = connection.getInputStream();
        JsonReader reader = Json.createReader(new InputStreamReader(response, StandardCharsets.UTF_8));
        return reader.readObject();

    } catch (IOException ioException) {
        error = connection.getErrorStream();
        if (error != null) {
            LWAException lwaException = new LWAException(IOUtils.toString(error), responseCode);
            throw lwaException;
        } else {
            throw ioException;
        }
    } finally {
        IOUtils.closeQuietly(error);
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:httpRequests.GetPost.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) 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);//from  w ww .  j  a v  a  2 s . co  m
    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
    System.out.println(response.toString());

}

From source file:MixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//from   w  w  w.  j a v a 2 s. c om
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
            }
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}