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:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server./*from  www . j  a  va  2s . 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:de.gebatzens.sia.SiaAPI.java

public APIResponse doRequest(String url, JSONObject request) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(BuildConfig.BACKEND_SERVER + url).openConnection();

    con.setRequestProperty("User-Agent",
            "SchulinfoAPP/" + BuildConfig.VERSION_NAME + " (" + BuildConfig.VERSION_CODE + " "
                    + BuildConfig.BUILD_TYPE + " Android " + Build.VERSION.RELEASE + " " + Build.PRODUCT + ")");
    con.setRequestProperty("Accept-Encoding", "gzip");
    con.setConnectTimeout(3000);/*from w  w w  .  ja v  a 2s .  c  om*/
    con.setRequestMethod(request == null ? "GET" : "POST");
    con.setInstanceFollowRedirects(false);

    if (request != null) {
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(request.toString());
        wr.flush();
        wr.close();
    }

    if (BuildConfig.DEBUG)
        Log.d("ggvp", "connection to " + con.getURL() + " established");

    InputStream in = con.getResponseCode() != 200 ? con.getErrorStream() : con.getInputStream();
    String encoding = con.getHeaderField("Content-Encoding");
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        in = new GZIPInputStream(in);
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String response = "";
    String line = "";
    while ((line = reader.readLine()) != null)
        response += line;
    JSONObject json = null;
    try {
        json = new JSONObject(response);
        String state = json.getString("state");
        Object data = json.opt("data");
        String reason = json.optString("reason", "");

        Log.d("ggvp", "received state " + state + " " + con.getResponseCode() + " reason: " + reason);

        return new APIResponse(state.equals("succeeded") ? APIState.SUCCEEDED : APIState.FAILED, data, reason);

    } catch (JSONException e) {
        Log.e("ggvp", e.toString());
        e.printStackTrace();
        return new APIResponse(APIState.FAILED);
    }

}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

@SuppressWarnings("deprecation")
public String runAsRoot(String command) {
    String output = new String();

    try {//from ww  w. j  a  v  a  2s  . co  m
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        DataInputStream is = new DataInputStream(p.getInputStream());
        os.writeBytes(command + "\n");
        os.flush();

        String line = new String();
        while ((line = is.readLine()) != null) {
            output = output + line;
        }

        os.writeBytes("exit\n");
        os.flush();
    } catch (Throwable e) {
        Log.i(MyApp.TAG, e.getMessage().toString());
    }

    return output;
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

@SuppressWarnings("deprecation")
public String runAsUser(String command) {
    String output = new String();

    try {//from  w  w w.ja v  a2s .c  o  m
        Process p = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        DataInputStream is = new DataInputStream(p.getInputStream());

        os.writeBytes("exec " + command + "\n");
        os.flush();

        String line = new String();
        while ((line = is.readLine()) != null) {
            output = output + line;
        }

        // os.writeBytes("exit\n");
        os.flush();
        p.waitFor();

    } catch (Throwable e) {
        Log.i(MyApp.TAG, e.getMessage().toString());
    }

    return output;
}

From source file:cd.education.data.collector.android.tasks.FormLoaderTask.java

/**
 * Write the FormDef to the file system as a binary blog.
 *
 * @param filepath/*from   w  w  w .  j av a  2 s .c om*/
 *          path to the form file
 */
public void serializeFormDef(FormDef fd, String filepath) {
    // calculate unique md5 identifier
    String hash = FileUtils.getMd5Hash(new File(filepath));
    File formDef = new File(Collect.CACHE_PATH + File.separator + hash + ".formdef");

    // formdef does not exist, create one.
    if (!formDef.exists()) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(formDef);
            DataOutputStream dos = new DataOutputStream(fos);
            fd.writeExternal(dos);
            dos.flush();
            dos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:me.cybermaxke.merchants.v16r3.SMerchant.java

@Override
public boolean addCustomer(Player player) {
    checkNotNull(player, "player");

    if (this.customers.add(player)) {
        EntityPlayer player0 = ((CraftPlayer) player).getHandle();
        Container container0 = null;

        try {//from   w ww.jav  a 2  s.com
            container0 = new SContainerMerchant(player0, this);
            container0 = CraftEventFactory.callInventoryOpenEvent(player0, container0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (container0 == null) {
            this.customers.remove(player);
            return false;
        }

        int window = player0.nextContainerCounter();

        player0.activeContainer = container0;
        player0.activeContainer.windowId = window;
        player0.activeContainer.addSlotListener(player0);

        // Open the window
        player0.playerConnection.sendPacket(new Packet100OpenWindow(window, 6, this.sendTitle, 3, true));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        try {
            // Write the window id
            dos.writeInt(window);
            // Write the offers
            this.offers.a(dos);
            // Flush and close data stream
            dos.flush();
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Send the offers
        player0.playerConnection.sendPacket(new Packet250CustomPayload("MC|TrList", baos.toByteArray()));
        return true;
    }

    return false;
}

From source file:info.magnolia.cms.exchange.simple.Transporter.java

/**
 * http form multipart form post/*from w w w .j av a2 s  . c o m*/
 * @param connection
 * @param activationContent
 * @throws ExchangeException
 */
public static void transport(URLConnection connection, ActivationContent activationContent)
        throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
        connection.setRequestProperty("Cache-Control", "no-cache");

        outStream = new DataOutputStream(connection.getOutputStream());
        outStream.writeBytes("--" + BOUNDARY + "\r\n");

        // set all resources from activationContent
        Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
        while (fileNameIterator.hasNext()) {
            String fileName = (String) fileNameIterator.next();
            fis = new FileInputStream(activationContent.getFile(fileName));
            outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\""
                    + fileName + "\"\r\n");
            outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
            while (true) {
                synchronized (buffer) {
                    int amountRead = fis.read(buffer);
                    if (amountRead == -1) {
                        break;
                    }
                    outStream.write(buffer, 0, amountRead);
                }
            }
            fis.close();
            outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
        }
        outStream.flush();
        outStream.close();

        log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
        throw new ExchangeException(
                "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
    }

}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

JSONObject doRequest(HttpURLConnection connection, String data) throws IOException, JSONException {
    int responseCode = -1;
    InputStream response = null;/*  www  . java 2s .  c o m*/
    DataOutputStream outputStream = null;

    try {
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        connection.setRequestProperty("Content-Type", "application/json");
        if (data != null) {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
        } else {
            connection.setRequestMethod("GET");
        }

        responseCode = connection.getResponseCode();
        response = connection.getInputStream();

        if (responseCode != 204) {
            String responseString = IOUtils.toString(response);
            JSONObject jsonObject = new JSONObject(responseString);
            return jsonObject;
        } else {
            return null;
        }
    } catch (IOException e) {
        if (responseCode < 200 || responseCode >= 300) {
            response = connection.getErrorStream();
            if (response != null) {
                String responseString = IOUtils.toString(response);
                throw new RuntimeException(responseString);
            }
        }
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(response);
    }
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

@Override
public String encryptData(final SecureToken data) {
    if (data == null || StringUtils.isBlank(data.getData())) {
        throw new IllegalArgumentException("missing token");
    }/* w w w.ja va  2 s  . c  om*/
    try {
        final SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
        final int[] paddingSizes = computePaddingLengths(random);

        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        dataOutputStream.write(generatePadding(paddingSizes[0], random));
        dataOutputStream.writeUTF(data.getData());
        dataOutputStream.writeUTF(createChecksum(data.getData()));
        dataOutputStream.writeLong(data.getTimeStamp());
        dataOutputStream.write(generatePadding(paddingSizes[1], random));

        dataOutputStream.flush();
        final byte[] unsignedDataBytes = byteArrayOutputStream.toByteArray();

        final byte[] md5SigBytes = generateSignature(unsignedDataBytes, 0, unsignedDataBytes.length,
                signatureKeyBytes);
        byteArrayOutputStream.write(md5SigBytes);
        byteArrayOutputStream.flush();

        final byte[] signedDataBytes = byteArrayOutputStream.toByteArray();

        return encrypt(signedDataBytes, encryptionKeyBytes, random);
    } catch (final IOException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    } catch (final GeneralSecurityException e) {
        LOG.error("Could not encrypt", e);
        throw new SystemException(e.toString(), e);
    }
}

From source file:com.mirth.connect.connectors.mllp.protocols.LlpProtocol.java

public void write(OutputStream os, byte[] data) throws IOException {
    // Write the data with LLP wrappers
    DataOutputStream dos = new DataOutputStream(os);
    dos.writeByte(START_MESSAGE);//  ww w  .  jav  a2 s  .c  o m

    // MIRTH-1448: Changed from writing the entire byte[] to writing
    // each byte in the byte[] to avoid sending the START_MESSAGE as
    // its own packet.
    for (int i = 0; i < data.length; i++) {
        dos.writeByte(data[i]);
    }

    dos.writeByte(END_MESSAGE);
    if (END_OF_RECORD != 0) {
        dos.writeByte(END_OF_RECORD);
    }
    try {
        dos.flush();
    } catch (SocketException se) {
        logger.debug("Socket closed while trying to flush");
    }
}