Example usage for java.io OutputStream write

List of usage examples for java.io OutputStream write

Introduction

In this page you can find the example usage for java.io OutputStream write.

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this output stream.

Usage

From source file:com.android.nunes.sophiamobile.gsm.GcmSender.java

public static void enviar(String msg, String token) {

    try {// w w w  .  j a v a2  s .c o  m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", msg.trim());
        // Where to send GCM message.
        if (token != null) {
            jGcmData.put("to", token.trim());
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {//  w w w  . ja  va2 s  .  c  om
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:ca.xecure.easychip.CommonUtilities.java

public static void http_post(String endpoint, Map<String, String> params) throws IOException {
    URL url;//from w  ww  .j  ava2 s.c o  m
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }

    String body = JSONValue.toJSONString(params);
    Log.v(LOG_TAG, "Posting '" + body + "' to " + url);

    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();

        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:jenkins.security.security218.ysoserial.payloads.FileUpload1.java

private static DiskFileItem makePayload(int thresh, String repoPath, String filePath, byte[] data)
        throws IOException, Exception {
    // if thresh < written length, delete outputFile after copying to repository temp file
    // otherwise write the contents to repository temp file
    File repository = new File(repoPath);
    DiskFileItem diskFileItem = new DiskFileItem("test", "application/octet-stream", false, "test", 100000,
            repository);/*from ww  w  . ja va2s.c  o  m*/
    File outputFile = new File(filePath);
    DeferredFileOutputStream dfos = new DeferredFileOutputStream(thresh, outputFile);
    OutputStream os = (OutputStream) Reflections.getFieldValue(dfos, "memoryOutputStream");
    os.write(data);
    Reflections.getField(ThresholdingOutputStream.class, "written").set(dfos, data.length);
    Reflections.setFieldValue(diskFileItem, "dfos", dfos);
    Reflections.setFieldValue(diskFileItem, "sizeThreshold", 0);
    return diskFileItem;
}

From source file:com.codelanx.playtime.callable.UUIDFetcher.java

private static void writeBody(HttpURLConnection connection, String body) throws Exception {
    OutputStream stream = connection.getOutputStream();
    stream.write(body.getBytes());
    stream.flush();/* w w w .  j a  v a2s.  c om*/
    stream.close();
}

From source file:com.qq.tars.tools.SystemUtils.java

public static Pair<Integer, Pair<String, String>> exec(String command) {
    log.info("start to exec shell, command={}", command);

    try {/*w w  w  .  j av  a 2  s. co  m*/
        Process process = Runtime.getRuntime().exec("/bin/sh");

        OutputStream os = process.getOutputStream();
        os.write(command.getBytes());
        os.close();

        final StringBuilder stdout = new StringBuilder(1024);
        final StringBuilder stderr = new StringBuilder(1024);
        final BufferedReader stdoutReader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(process.getErrorStream(), "GBK"));

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stdoutReader.readLine())) {
                    stdout.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stdout error", e);
            }
        }).start();

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stderrReader.readLine())) {
                    stderr.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stderr error", e);
            }
        }).start();

        int ret = process.waitFor();

        stdoutReader.close();
        stderrReader.close();

        Pair<String, String> output = Pair.of(stdout.toString(), stderr.toString());
        return Pair.of(ret, output);
    } catch (Exception e) {
        return Pair.of(-1, Pair.of("", ExceptionUtils.getStackTrace(e)));
    }
}

From source file:com.screenslicer.core.util.Email.java

public static void sendResults(EmailExport export) {
    if (WebApp.DEV) {
        return;//from  w  w w.j  av a 2s .  c o m
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("key", Config.instance.mandrillKey());
    List<Map<String, String>> to = new ArrayList<Map<String, String>>();
    for (int i = 0; i < export.recipients.length; i++) {
        to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i],
                export.recipients[i].split("@")[0], "to"));
    }
    List<Map<String, String>> attachments = new ArrayList<Map<String, String>>();
    for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) {
        attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()),
                entry.getKey(), Base64.encodeBase64String(entry.getValue())));
    }
    params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers",
            "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.",
            "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title,
            Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments));
    params.put("async", true);
    HttpURLConnection conn = null;
    String resp = null;
    Log.info("Sending email: " + export.title, false);
    try {
        conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json")
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0");
        String data = CommonUtil.gson.toJson(params, CommonUtil.objectType);
        byte[] bytes = data.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", "" + bytes.length);
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        resp = IOUtils.toString(conn.getInputStream(), "utf-8");
        if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) {
            Log.warn("Invalid/rejected email addreses");
        }
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:Main.java

public static final void writeFix(OutputStream out, String s) throws IOException {
    if (s == null || s.length() == 0)
        return;//from   www .  j  a  v  a  2 s  . c o  m
    byte[] b = s.getBytes();
    out.write(b);
}

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {/*from  w w  w  . j a v  a2  s  .  c  om*/
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:Main.java

public static String createExternalStoragePrivateFile(Context appCtx, InputStream is, String fileName) {

    File file = new File(appCtx.getExternalFilesDir(null), fileName);

    try {/*from   w w  w.  j a  va 2 s  . c o m*/
        //InputStream is = appCtx.getResources().openRawResource(R.raw.calipso);
        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();
    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }

    return file.getPath();
}