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.comcast.viper.flume2storm.zookeeper.ZkTestUtils.java

/**
 * Utility function to send a command to the internal server. ZK servers
 * accepts 4 byte command strings to test their liveness.
 *//* www. j av  a  2s .c  om*/
protected static String send4LetterWord(final String host, final int port, final String cmd) {
    Preconditions.checkArgument(cmd.length() == 4);
    try {
        final Socket sock = new Socket(host, port);
        OutputStream outstream = null;
        BufferedReader reader = null;
        try {
            outstream = sock.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();

            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            final StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } finally {
            if (outstream != null) {
                outstream.close();
            }
            sock.close();
            if (reader != null) {
                reader.close();
            }
        }
    } catch (final Exception e) {
        System.out.println(e.getMessage());
        return StringUtils.EMPTY;
    }
}

From source file:fr.paris.lutece.plugins.directory.web.DoDownloadFile.java

/**
 * Write in the http response the file to upload
 * @param request the http request//from  w ww .j  av  a2 s . co  m
 * @param response The http response
 * @return Error Message
 *
 */
public static String doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);
    String strIdFile = request.getParameter(PARAMETER_ID_FILE);
    int nIdFile = DirectoryUtils.CONSTANT_ID_NULL;

    if (StringUtils.isBlank(strIdFile) || !StringUtils.isNumeric(strIdFile)) {
        String strIdDirectoryRecord = request.getParameter(DirectoryUtils.PARAMETER_ID_DIRECTORY_RECORD);
        String strIdEntry = request.getParameter(DirectoryUtils.PARAMETER_ID_ENTRY);

        if ((StringUtils.isBlank(strIdDirectoryRecord) || !StringUtils.isNumeric(strIdDirectoryRecord))
                && (StringUtils.isBlank(strIdEntry) || !StringUtils.isNumeric(strIdEntry))) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
                    AdminMessage.TYPE_STOP);
        }

        int nIdDirectoryRecord = DirectoryUtils.convertStringToInt(strIdDirectoryRecord);
        int nIdEntry = DirectoryUtils.convertStringToInt(strIdEntry);
        RecordFieldFilter rfFilter = new RecordFieldFilter();
        rfFilter.setIdRecord(nIdDirectoryRecord);
        rfFilter.setIdEntry(nIdEntry);

        List<RecordField> listRecordFields = RecordFieldHome.getRecordFieldList(rfFilter, plugin);

        if ((listRecordFields != null) && !listRecordFields.isEmpty()) {
            RecordField recordField = listRecordFields.get(0);

            if ((recordField != null) && (recordField.getFile() != null)) {
                nIdFile = recordField.getFile().getIdFile();
            }
        }

        if ((nIdFile == DirectoryUtils.CONSTANT_ID_NULL) || (nIdFile == DirectoryUtils.CONSTANT_ID_ZERO)) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
                    AdminMessage.TYPE_STOP);
        }
    } else {
        nIdFile = DirectoryUtils.convertStringToInt(strIdFile);
    }

    File file = FileHome.findByPrimaryKey(nIdFile, plugin);
    PhysicalFile physicalFile = (file != null)
            ? PhysicalFileHome.findByPrimaryKey(file.getPhysicalFile().getIdPhysicalFile(), plugin)
            : null;

    if (physicalFile != null) {
        try {
            byte[] byteFileOutPut = physicalFile.getValue();
            DirectoryUtils.addHeaderResponse(request, response, file.getTitle());

            String strMimeType = file.getMimeType();

            if (strMimeType == null) {
                strMimeType = FileSystemUtil.getMIMEType(file.getTitle());
            }

            response.setContentType(strMimeType);
            response.setContentLength(byteFileOutPut.length);

            OutputStream os = response.getOutputStream();
            os.write(byteFileOutPut);
            os.close();
        } catch (IOException e) {
            AppLogService.error(e);
        }
    }

    return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
            AdminMessage.TYPE_STOP);
}

From source file:Main.java

public static boolean addByte(@NonNull File fileName, @NonNull String content) {
    if (!fileName.isFile()) {
        return false;
    }/*from w  ww .  j  a v a2s.  co  m*/
    OutputStream out = null;
    try {
        out = new FileOutputStream(fileName, true);
        byte[] b = content.getBytes();
        for (int i = 0; i < b.length; i++) {
            out.write(b[i]);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        CloseableClose(out);
    }
}

From source file:Main.java

public static void writeWLenData(OutputStream os, byte[] bytes, boolean big_endian) throws IOException {
    if (bytes == null) {
        writeShort(os, 0, big_endian);//from w  w  w  .j  a  v a 2 s  .c om
    } else {
        writeShort(os, bytes.length, big_endian);
        os.write(bytes);
    }
}

From source file:DOMUtil.java

protected static void print(OutputStream out, String s) {
    if (out != null)
        try {//from   www . j  a  v a 2  s .  com
            out.write(s.getBytes());
            out.write(sep);
        } catch (IOException ioe) {
        }
}

From source file:com.cloudbees.workflow.Util.java

public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType)
        throws IOException {
    String jenkinsUrl = jenkins.getRootUrl();
    URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/"));
    HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

    try {/*  ww  w.j  ava  2  s  . c  om*/
        conn.setRequestMethod("POST");

        // Set the crumb header, otherwise the POST may be rejected.
        NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins);
        conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue());

        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        if (content != null) {
            byte[] bytes = content.getBytes(Charset.forName("UTF-8"));

            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            final OutputStream os = conn.getOutputStream();
            try {
                os.write(bytes);
                os.flush();
            } finally {
                os.close();
            }
        }

        return conn.getResponseCode();
    } finally {
        conn.disconnect();
    }
}

From source file:eu.swiec.bearballin.common.io.FileIO.java

@Deprecated
public static void writePageSource(String fileName, String pageSource) throws IOException {
    File pageFile = new File(fileName);
    if (pageFile.createNewFile()) {
        OutputStream outStrem = new FileOutputStream(pageFile);
        outStrem.write(pageSource.getBytes("UTF-16"));
        // outStrem.write(pageSource.getBytes(), 0, pageSource.length());
        outStrem.close();/*from   w  w w . ja v  a 2s .c  om*/
    }

}

From source file:Main.java

public static void write(char[] data, OutputStream output, String encoding) throws IOException {
    if (data != null)
        output.write(new String(data).getBytes(encoding));
}

From source file:Main.java

public static void write(CharSequence data, OutputStream output, String encoding) throws IOException {
    if (data != null)
        output.write(data.toString().getBytes(encoding));
}

From source file:com.onesignal.OneSignalRestClient.java

private static void makeRequest(String url, String method, JSONObject jsonBody,
        ResponseHandler responseHandler) {
    HttpURLConnection con = null;
    int httpResponse = -1;
    String json = null;//from w w  w  .j ava 2s. co m

    try {
        con = (HttpURLConnection) new URL(BASE_URL + url).openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);

        if (jsonBody != null)
            con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestMethod(method);

        if (jsonBody != null) {
            String strJsonBody = jsonBody.toString();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody);

            byte[] sendBytes = strJsonBody.getBytes("UTF-8");
            con.setFixedLengthStreamingMode(sendBytes.length);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sendBytes);
        }

        httpResponse = con.getResponseCode();

        InputStream inputStream;
        Scanner scanner;
        if (httpResponse == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
            scanner = new Scanner(inputStream, "UTF-8");
            json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
            scanner.close();
            OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json);

            if (responseHandler != null)
                responseHandler.onSuccess(json);
        } else {
            inputStream = con.getErrorStream();
            if (inputStream == null)
                inputStream = con.getInputStream();

            if (inputStream != null) {
                scanner = new Scanner(inputStream, "UTF-8");
                json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                scanner.close();
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json);
            } else
                OneSignal.Log(OneSignal.LOG_LEVEL.WARN,
                        method + " HTTP Code: " + httpResponse + " No response body!");

            if (responseHandler != null)
                responseHandler.onFailure(httpResponse, json, null);
        }
    } catch (Throwable t) {
        if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException)
            OneSignal.Log(OneSignal.LOG_LEVEL.INFO,
                    "Could not send last request, device is offline. Throwable: " + t.getClass().getName());
        else
            OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t);

        if (responseHandler != null)
            responseHandler.onFailure(httpResponse, null, t);
    } finally {
        if (con != null)
            con.disconnect();
    }
}