Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:nl.knaw.dans.common.lang.file.UnzipUtil.java

private static List<File> extract(final ZipInputStream zipInputStream, String destPath,
        final int initialCapacityForFiles, final UnzipListener unzipListener, final long totSize)
        throws FileNotFoundException, IOException {
    if (unzipListener != null)
        unzipListener.onUnzipStarted(totSize);

    final File destPathFile = new File(destPath);
    if (!destPathFile.exists())
        throw new FileNotFoundException(destPath);
    if (!destPathFile.isDirectory())
        throw new IOException("Expected directory, got file.");
    if (!destPath.endsWith(File.separator))
        destPath += File.separator;

    // now unzip// w  ww. j  a v  a  2  s.  c  om
    BufferedOutputStream out = null;
    ZipEntry entry;
    int count;
    final byte data[] = new byte[BUFFER_SIZE];
    final ArrayList<File> files = new ArrayList<File>(initialCapacityForFiles);
    String entryname;
    String filename;
    String path;
    boolean cancel = false;
    final DefaultUnzipFilenameFilter filter = new DefaultUnzipFilenameFilter();

    try {
        long bytesWritten = 0;
        while (((entry = zipInputStream.getNextEntry()) != null) && !cancel) {
            entryname = entry.getName();
            final int fpos = entryname.lastIndexOf(File.separator);
            if (fpos >= 0) {
                path = entryname.substring(0, fpos);
                filename = entryname.substring(fpos + 1);
            } else {
                path = "";
                filename = new String(entryname);
            }

            if (!filter.accept(destPathFile, filename)) {
                // file filtered out
                continue;
            }

            if (entry.isDirectory()) {
                if (!createPath(destPath, entryname, files, filter))
                    // directory filtered out
                    continue;
            } else {
                if (!StringUtils.isBlank(path)) {
                    if (!createPath(destPath, path, files, filter))
                        // path filtered out
                        continue;
                }

                final String absFilename = destPath + entryname;
                final FileOutputStream fos = new FileOutputStream(absFilename);
                out = new BufferedOutputStream(fos, BUFFER_SIZE);
                try {
                    // inner loop
                    while ((count = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                        out.write(data, 0, count);
                        bytesWritten += count;

                        if (unzipListener != null)
                            cancel = !unzipListener.onUnzipUpdate(bytesWritten, totSize);
                        if (cancel)
                            break;
                    }
                    out.flush();
                } finally {
                    out.close();
                    files.add(new File(absFilename));
                }
            }
        }
    } finally {
        zipInputStream.close();

        // rollback?
        if (cancel) {
            // first remove files
            for (final File file : files) {
                if (!file.isDirectory())
                    file.delete();
            }
            // then folders
            for (final File file : files) {
                if (file.isDirectory())
                    file.delete();
            }
            files.clear();
        }
    }

    if (unzipListener != null)
        unzipListener.onUnzipComplete(files, cancel);

    return files;
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

static private boolean copyFileLocalToLocalByStream(File iLf, String fromUrl, String toUrl, String title_header)
        throws IOException {

    File oLf = new File(toUrl);
    boolean result = false;
    String tmp_file = getLocalTempFileName(toUrl);
    File t_lf = new File(tmp_file);
    t_lf.delete();/* w  w w .ja v  a2 s . c om*/
    long t0 = System.currentTimeMillis();
    FileOutputStream fout = new FileOutputStream(t_lf);
    FileInputStream bis = new FileInputStream(iLf);
    //       FileOutputStream bos = new FileOutputStream(t_lf);
    //       BufferedInputStream bis=new BufferedInputStream(fin,SMB_BUFF_SIZE*16);
    BufferedOutputStream bos = new BufferedOutputStream(fout, SMB_BUFF_SIZE * 16);
    int n = 0;
    long tot = 0;
    long fileBytes = iLf.length();
    String fn = iLf.getName();

    sendMsgToProgDlg(String.format(title_header + " %s %s%% completed.", fn, 0));

    while ((n = bis.read(fileIoArea)) > 0) {
        if (!fileioThreadCtrl.isEnabled()) {
            bis.close();
            bos.close();
            t_lf.delete();
            return false;
        }
        bos.write(fileIoArea, 0, n);
        tot += n;
        if (n < fileBytes)
            sendMsgToProgDlg(String.format(title_header + " %s %s%% completed.", fn, (tot * 100) / fileBytes));
    }
    bis.close();
    bos.flush();
    bos.close();

    setLocalFileLastModifiedTime(t_lf, iLf.lastModified());

    //       Log.v("","tmp_file="+tmp_file+", out="+toUrl);
    boolean rc_d = true;
    if (oLf.exists())
        rc_d = oLf.delete();
    if (rc_d) {
        boolean rc_r = t_lf.renameTo(oLf);
        if (rc_r) {
            long t = System.currentTimeMillis() - t0;
            if (mGp.settingsMslScan)
                scanMediaStoreLibraryFile(toUrl);
            sendLogMsg("I", fromUrl + " was copied to " + toUrl + ", " + tot + " bytes transfered in " + t
                    + " mili seconds at " + calTransferRate(tot, t));
            result = true;
        } else {
            t_lf.delete();
            sendLogMsg("I", "Copy was failed, Rename from=" + fromUrl + " to=" + toUrl);
            fileioThreadCtrl.setThreadMessage("Copy was failed, Rename from=" + fromUrl + " to=" + toUrl);
        }
    } else {
        t_lf.delete();
        sendLogMsg("I", "Copy was failed, Target file not deleted, Target file=" + toUrl);
        fileioThreadCtrl.setThreadMessage("Copy was failed, Target file not deleted, Target file=" + toUrl);
    }

    return result;
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

static private boolean copySafFileLocalToLocalByStream(File iLf, String fromUrl, String toUrl,
        String title_header) throws IOException {
    SafFile oLf = SafUtil.getSafDocumentFileByPath(mSafCA, toUrl, false);
    boolean result = false;
    String tmp_file = toUrl + ".work";
    SafFile t_df = SafUtil.getSafDocumentFileByPath(mSafCA, tmp_file, false);
    //      t_df.delete();
    //       File t_lf=new File(tmp_file);
    //       t_lf.delete();
    long t0 = System.currentTimeMillis();
    FileInputStream bis = new FileInputStream(iLf);
    OutputStream fout = mContext.getContentResolver().openOutputStream(t_df.getUri());
    //       BufferedInputStream bis=new BufferedInputStream(fin,SMB_BUFF_SIZE);
    BufferedOutputStream bos = new BufferedOutputStream(fout, SMB_BUFF_SIZE * 32);
    int n = 0;//  www .j a  v a  2 s .co  m
    long tot = 0;
    long fileBytes = iLf.length();
    String fn = iLf.getName();

    sendMsgToProgDlg(String.format(title_header + " %s %s%% completed.", fn, 0));

    while ((n = bis.read(fileIoArea)) > 0) {
        if (!fileioThreadCtrl.isEnabled()) {
            bis.close();
            bos.close();
            t_df.delete();
            return false;
        }
        bos.write(fileIoArea, 0, n);
        tot += n;
        if (n < fileBytes)
            sendMsgToProgDlg(String.format(title_header + " %s %s%% completed.", fn, (tot * 100) / fileBytes));
    }
    bis.close();
    bos.flush();
    bos.close();

    //       setLocalFileLastModifiedTime(t_lf, iLf.lastModified());

    //       Log.v("","tmp_file="+tmp_file+", out="+toUrl);
    boolean rc_d = true;
    if (oLf.exists())
        rc_d = oLf.delete();
    if (rc_d) {
        String nm = SafUtil.getFileNameFromPath(toUrl);
        boolean rc_r = t_df.renameTo(nm);
        if (rc_r) {
            long t = System.currentTimeMillis() - t0;
            if (mGp.settingsMslScan)
                scanMediaStoreLibraryFile(toUrl);
            sendLogMsg("I", fromUrl + " was copied to " + toUrl + ", " + tot + " bytes transfered in " + t
                    + " mili seconds at " + calTransferRate(tot, t));
            result = true;
        } else {
            t_df.delete();
            sendLogMsg("I", "Copy was failed, Rename from=" + tmp_file + " to=" + toUrl);
            fileioThreadCtrl.setThreadMessage("Copy was failed, Rename from=" + tmp_file + " to=" + toUrl);
        }
    } else {
        t_df.delete();
        sendLogMsg("I", "Copy was failed, Target file not deleted, Target file=" + toUrl);
        fileioThreadCtrl.setThreadMessage("Copy was failed, Target file not deleted, Target file=" + toUrl);
    }

    return result;
}

From source file:adams.core.io.fileoperations.FtpFileOperations.java

/**
 * Copies a file.//w  w w  . ja v a 2s .  c  o m
 *
 * @param source   the source file
 * @param target   the target file
 * @return      null if successful, otherwise error message
 */
public String copy(String source, String target) {
    String result;
    String remoteFile;
    String outFile;
    String inFile;
    BufferedOutputStream ostream;
    FileOutputStream fos;
    BufferedInputStream istream;
    FileInputStream fis;

    result = null;

    switch (m_Direction) {
    case LOCAL_TO_REMOTE:
        remoteFile = target;
        inFile = source;
        istream = null;
        fis = null;
        try {
            if (isLoggingEnabled())
                getLogger().info("Uploading " + inFile + " to " + remoteFile);
            fis = new FileInputStream(inFile);
            istream = new BufferedInputStream(fis);
            m_Client.storeFile(remoteFile, istream);
        } catch (Exception e) {
            result = Utils.handleException(this,
                    "Failed to upload file '" + inFile + "' to '" + remoteFile + "': ", e);
        } finally {
            FileUtils.closeQuietly(istream);
            FileUtils.closeQuietly(fis);
        }
        break;

    case REMOTE_TO_LOCAL:
        remoteFile = source;
        outFile = target;
        fos = null;
        ostream = null;
        try {
            if (isLoggingEnabled())
                getLogger().info("Downloading " + remoteFile);
            fos = new FileOutputStream(outFile);
            ostream = new BufferedOutputStream(fos);
            m_Client.retrieveFile(remoteFile, ostream);
            ostream.flush();
            ostream.close();
        } catch (Exception e) {
            result = Utils.handleException(this,
                    "Failed to download file '" + remoteFile + "' to '" + outFile + "': ", e);
        } finally {
            FileUtils.closeQuietly(ostream);
            FileUtils.closeQuietly(fos);
        }
        break;

    default:
        throw new IllegalStateException("Unhandled direction: " + m_Direction);
    }

    return result;
}

From source file:gobblin.tunnel.TalkPastServer.java

@Override
void handleClientSocket(Socket clientSocket) throws IOException {
    LOG.info("Writing to client");
    try {/*from   www . j  av a  2s  .co m*/
        final BufferedOutputStream serverOut = new BufferedOutputStream(clientSocket.getOutputStream());
        EasyThread clientWriterThread = new EasyThread() {
            @Override
            void runQuietly() throws Exception {
                long t = System.currentTimeMillis();
                try {
                    for (int i = 0; i < nMsgs; i++) {
                        serverOut.write(generateMsgFromServer(i).getBytes());
                        sleepQuietly(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info("Server done writing in " + (System.currentTimeMillis() - t) + " ms");
            }
        }.startThread();
        _threads.add(clientWriterThread);

        BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String line = serverIn.readLine();
        while (line != null && !line.equals("Goodbye")) {
            String[] tokens = line.split(":", 2);
            String client = tokens[0];
            digestMsgsRecvdAtServer.get(client).update(line.getBytes());
            digestMsgsRecvdAtServer.get(client).update("\n".getBytes());
            line = serverIn.readLine();
        }
        LOG.info("Server done reading");
        try {
            clientWriterThread.join();
        } catch (InterruptedException e) {
        }
        serverOut.write("Goodbye\n".getBytes());
        serverOut.flush();
        clientSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

private static boolean copyFileRemoteToLocalByStream(SmbFile hf, File lf, String toUrl, String fromUrl,
        String title_header) throws IOException {
    File oLf = new File(toUrl);
    boolean result = false;
    String tmp_file = getLocalTempFileName(toUrl);
    File t_lf = new File(tmp_file);
    t_lf.delete();/*from ww  w . ja v  a 2s .c  o m*/

    long t0 = System.currentTimeMillis();
    SmbFileInputStream bis = new SmbFileInputStream(hf);
    FileOutputStream out = new FileOutputStream(t_lf);
    //       BufferedInputStream bis=new BufferedInputStream(in,SMB_BUFF_SIZE);
    BufferedOutputStream bos = new BufferedOutputStream(out, SMB_BUFF_SIZE * 32);
    int n;
    long tot = 0;
    long fileBytes = hf.length();
    String fn = hf.getName().replaceAll("/", "");

    sendMsgToProgDlg(String.format(title_header + " %s,  %s%% completed.", fn, 0));

    while ((n = bis.read(fileIoArea)) > 0) {
        if (!fileioThreadCtrl.isEnabled()) {
            bis.close();
            bos.close();
            t_lf.delete();
            return false;
        }
        bos.write(fileIoArea, 0, n);
        tot += n;
        if (tot < fileBytes)
            sendMsgToProgDlg(
                    String.format(title_header + " %s,  %s%% completed.", fn, (tot * 100) / fileBytes));
    }
    bis.close();
    bos.flush();
    bos.close();

    setLocalFileLastModifiedTime(t_lf, hf.lastModified());

    boolean rc_d = true;
    if (oLf.exists())
        rc_d = oLf.delete();

    if (rc_d) {
        boolean rc = t_lf.renameTo(oLf);
        if (rc) {
            long t = System.currentTimeMillis() - t0;
            if (mGp.settingsMslScan)
                scanMediaStoreLibraryFile(toUrl);
            sendLogMsg("I", fromUrl + " was copied to " + toUrl + ", " + tot + " bytes transfered in " + t
                    + " mili seconds at " + calTransferRate(tot, t));
            result = true;
        } else {
            t_lf.delete();
            sendLogMsg("I", "Copy was failed, Rename from=" + fromUrl + " to=" + toUrl);
            fileioThreadCtrl.setThreadMessage("Copy was failed, Rename from=" + fromUrl + " to=" + toUrl);
        }
    } else {
        t_lf.delete();
        sendLogMsg("I", "Copy was failed, Target file not deleted, Target file=" + toUrl);
        fileioThreadCtrl.setThreadMessage("Copy was failed, Target file not deleted, Target file=" + toUrl);
    }
    return result;
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

private static boolean copySafFileRemoteToLocalByStream(SmbFile hf, File lf, String toUrl, String fromUrl,
        String title_header) throws IOException {

    SafFile oLf = SafUtil.getSafDocumentFileByPath(mSafCA, toUrl, false);
    boolean result = false;
    String tmp_file = toUrl + ".work";
    SafFile t_df = SafUtil.getSafDocumentFileByPath(mSafCA, tmp_file, false);
    long t0 = System.currentTimeMillis();

    SmbFileInputStream bis = new SmbFileInputStream(hf);
    OutputStream fout = mContext.getContentResolver().openOutputStream(t_df.getUri());
    BufferedOutputStream bos = new BufferedOutputStream(fout, SMB_BUFF_SIZE * 32);
    int n;/* w  w  w  .  j  a v  a 2  s .c o m*/
    long tot = 0;
    long fileBytes = hf.length();
    String fn = hf.getName().replaceAll("/", "");

    sendMsgToProgDlg(String.format(title_header + " %s,  %s%% completed.", fn, 0));

    while ((n = bis.read(fileIoArea)) > 0) {
        if (!fileioThreadCtrl.isEnabled()) {
            bis.close();
            bos.close();
            t_df.delete();
            return false;
        }
        bos.write(fileIoArea, 0, n);
        tot += n;
        if (tot < fileBytes)
            sendMsgToProgDlg(
                    String.format(title_header + " %s,  %s%% completed.", fn, (tot * 100) / fileBytes));
    }
    bis.close();
    bos.flush();
    bos.close();

    //       setLocalFileLastModifiedTime(t_lf, hf.lastModified());

    boolean rc_d = true;
    if (oLf.exists())
        rc_d = oLf.delete();

    if (rc_d) {
        String nm = SafUtil.getFileNameFromPath(toUrl);
        boolean rc = t_df.renameTo(nm);
        if (rc) {
            long t = System.currentTimeMillis() - t0;
            if (mGp.settingsMslScan)
                scanMediaStoreLibraryFile(toUrl);
            sendLogMsg("I", fromUrl + " was copied to " + toUrl + ", " + tot + " bytes transfered in " + t
                    + " mili seconds at " + calTransferRate(tot, t));
            result = true;
        } else {
            t_df.delete();
            sendLogMsg("I", "Copy was failed, Rename from=" + fromUrl + " to=" + toUrl);
            fileioThreadCtrl.setThreadMessage("Copy was failed, Rename from=" + tmp_file + " to=" + toUrl);
        }
    } else {
        t_df.delete();
        sendLogMsg("I", "Copy was failed, Target file not deleted, Target file=" + toUrl);
        fileioThreadCtrl.setThreadMessage("Copy was failed, Target file not deleted, Target file=" + toUrl);
    }
    return result;
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderAnyMemo.java

private void downloadDatabase(final DownloadItem di) throws Exception {
    String filename = di.getExtras("filename");
    if (filename == null) {
        throw new Exception("Could not get filename");
    }/*from w w  w .j  av a  2  s.com*/

    String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + getString(R.string.default_dir);
    File outFile = new File(sdpath + filename);
    mHandler.post(new Runnable() {
        public void run() {
            mProgressDialog = new ProgressDialog(DownloaderAnyMemo.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMessage(getString(R.string.loading_downloading));
            mProgressDialog.show();

        }
    });
    try {
        OutputStream out;
        if (outFile.exists()) {
            throw new IOException("Database already exist!");
        }
        try {
            outFile.createNewFile();
            out = new FileOutputStream(outFile);

            URL myURL = new URL(di.getAddress());
            Log.v(TAG, "URL IS: " + myURL);
            URLConnection ucon = myURL.openConnection();
            final int fileSize = ucon.getContentLength();
            mHandler.post(new Runnable() {
                public void run() {
                    mProgressDialog.setMax(fileSize);
                }
            });

            byte[] buf = new byte[8192];

            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, 8192);
            Runnable increaseProgress = new Runnable() {
                public void run() {
                    mProgressDialog.setProgress(mDownloadProgress);
                }
            };
            int len = 0;
            int lenSum = 0;
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
                lenSum += len;
                if (lenSum > fileSize / 50) {
                    /* This is tricky.
                     * The UI thread can not be updated too often.
                     * So we update it only 50 times
                     */
                    mDownloadProgress += lenSum;
                    lenSum = 0;
                    mHandler.post(increaseProgress);
                }
            }
            out.close();
            is.close();
            /* Uncompress the zip file that contains images */
            if (filename.endsWith(".zip")) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mProgressDialog.setProgress(fileSize);
                        mProgressDialog.setMessage(getString(R.string.downloader_extract_zip));
                    }
                });

                BufferedOutputStream dest = null;
                BufferedInputStream ins = null;
                ZipEntry entry;
                ZipFile zipfile = new ZipFile(outFile);
                Enumeration<?> e = zipfile.entries();
                while (e.hasMoreElements()) {
                    entry = (ZipEntry) e.nextElement();
                    Log.v(TAG, "Extracting: " + entry);
                    if (entry.isDirectory()) {
                        new File(sdpath + "/" + entry.getName()).mkdir();
                    } else {
                        ins = new BufferedInputStream(zipfile.getInputStream(entry), 8192);
                        int count;
                        byte data[] = new byte[8192];
                        FileOutputStream fos = new FileOutputStream(sdpath + "/" + entry.getName());
                        dest = new BufferedOutputStream(fos, 8192);
                        while ((count = ins.read(data, 0, 8192)) != -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                        dest.close();
                        ins.close();
                    }
                }
                /* Delete the zip file if it is successfully decompressed */
                outFile.delete();
            }
            /* We do not check ttf file as db */
            if (!filename.toLowerCase().endsWith(".ttf")) {
                /* Check if the db is correct */
                filename = filename.replace(".zip", ".db");
                DatabaseHelper dh = new DatabaseHelper(DownloaderAnyMemo.this, sdpath, filename);
                dh.close();
            }
        } catch (Exception e) {
            if (outFile.exists()) {
                outFile.delete();
            }
            throw new Exception(e);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error downloading", e);
        throw new Exception(e);
    } finally {
        mHandler.post(new Runnable() {
            public void run() {
                mProgressDialog.dismiss();
            }
        });
    }

}

From source file:com.wso2telco.dep.mediator.RequestExecutor.java

/**
 * Make north bound request.//from w ww. j a  va2 s.co m
 *
 * @param operatorendpoint
 *            the operatorendpoint
 * @param url
 *            the url
 * @param requestStr
 *            the request str
 * @param auth
 *            the auth
 * @param messageContext
 *            the message context
 * @param inclueHeaders
 *            the inclue headers
 * @return the int
 */
public int makeNorthBoundRequest(OperatorEndpoint operatorendpoint, String url, String requestStr, boolean auth,
        MessageContext messageContext, boolean inclueHeaders) {

    ICallresponse icallresponse = null;
    String retStr = "";
    int statusCode = 0;

    URL neturl;
    HttpURLConnection connection = null;

    try {

        neturl = new URL(url);
        connection = (HttpURLConnection) neturl.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Charset", "UTF-8");// ADDED
        if (auth) {
            connection.setRequestProperty("Authorization",
                    "Bearer " + getAccessToken(operatorendpoint.getOperator(), messageContext));

            // Add JWT token header
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                String jwtparam = (String) headersMap.get("x-jwt-assertion");
                if (jwtparam != null) {
                    connection.setRequestProperty("x-jwt-assertion", jwtparam);
                }
            }
        }

        if (inclueHeaders) {
            org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                    .getAxis2MessageContext();
            Object headers = axis2MessageContext
                    .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null && headers instanceof Map) {
                Map headersMap = (Map) headers;
                Iterator it = headersMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); // avoids
                    // a
                    // ConcurrentModificationException
                }
            }
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        log.info("Northbound Request URL: " + connection.getRequestMethod() + " " + connection.getURL()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Northbound Request Headers: " + connection.getRequestProperties());
        }
        log.info("Northbound Request Body: " + requestStr + " Request ID: " + UID.getRequestID(messageContext));

        // ========================UNICODE
        // PATCH=========================================
        BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream());
        wr.write(requestStr.getBytes("UTF-8"));
        wr.flush();
        wr.close();
        // ========================UNICODE
        // PATCH=========================================

        statusCode = connection.getResponseCode();

        log.info("Northbound Response Status: " + statusCode + " " + connection.getResponseMessage()
                + " Request ID: " + UID.getRequestID(messageContext));
        if (log.isDebugEnabled()) {
            log.debug("Northbound Response Headers: " + connection.getHeaderFields());
        }
        log.info("Northbound Response Body: " + retStr + " Request ID: " + UID.getRequestID(messageContext));

        if (statusCode != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + statusCode);
        }

    } catch (Exception e) {
        log.error("[WSRequestService ], makerequest, " + e.getMessage(), e);
        return 0;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return statusCode;
}

From source file:org.codelabor.system.remoting.tcp.services.SimpleSocketAdapterServiceImpl.java

public String send(String inputMessage) throws Exception {
    Socket socket = null;/* w  w  w. j av a  2  s  .  com*/
    InputStream inputStream = null;
    OutputStream outputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    String receivedMessage = null;

    try {
        // connect to server
        socket = new Socket(host, port);

        // setup stream
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();

        // send message
        outputStream.write(inputMessage.getBytes(charsetName));
        outputStream.flush();
        if (log.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("sent message: [").append(inputMessage).append("]");
            log.debug(sb.toString());
        }

        int readSize = 0;
        int totalReadSize = 0;

        byte[] messageLengthBytes = new byte[MESSAGE_LENGTH_FIELD_LENGTH];
        inputStream.read(messageLengthBytes, 0, MESSAGE_LENGTH_FIELD_LENGTH);
        String messageLengthString = new String(messageLengthBytes, charsetName);
        totalReadSize += MESSAGE_LENGTH_FIELD_LENGTH;
        int messageLength = Integer.parseInt(messageLengthString);

        // read input stream
        byte[] buffer = new byte[8 * 1024];
        byteArrayOutputStream = new ByteArrayOutputStream();
        bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
        while (messageLength > totalReadSize && (readSize = inputStream.read(buffer)) != -1) {
            bufferedOutputStream.write(buffer, 0, readSize);
            bufferedOutputStream.flush();
            totalReadSize += readSize;
            if (log.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("read size: ").append(readSize);
                sb.append(", ");
                sb.append("total read size: ").append(totalReadSize);
                sb.append(", ");
                sb.append("message length: ").append(messageLength);
                log.debug(sb.toString());
            }
        }
        byte[] remainsMessageBytes = byteArrayOutputStream.toByteArray();
        byte[] receivedMessageBytes = new byte[messageLengthBytes.length + remainsMessageBytes.length];
        System.arraycopy(messageLengthBytes, 0, receivedMessageBytes, 0, messageLengthBytes.length);
        System.arraycopy(remainsMessageBytes, 0, receivedMessageBytes, messageLengthBytes.length,
                remainsMessageBytes.length);
        receivedMessage = new String(receivedMessageBytes, charsetName);

        if (log.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("received message: [").append(receivedMessage).append("]");
            log.debug(sb.toString());
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (byteArrayOutputStream != null)
            byteArrayOutputStream.close();
        if (bufferedOutputStream != null)
            bufferedOutputStream.close();
        if (inputStream != null)
            inputStream.close();
        if (outputStream != null)
            outputStream.close();
        if (socket != null)
            socket.close();
    }
    return receivedMessage;
}