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:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);//www .  ja  va  2  s .  c om
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

        connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length));

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}

From source file:IntSort.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {/*w w  w .  j av a 2 s  . c  o  m*/
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record      
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {//from   w w w  . j av  a2s  .c o m
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:com.skcraft.launcher.util.HttpRequest.java

/**
 * Execute the request.//  www  .jav a 2 s .  co  m
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java) SKMCLauncher");

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:com.sk89q.squirrelid.util.HttpRequest.java

/**
 * Execute the request.//from w  w w.  j  av  a  2s .c o  m
 * <p/>
 * After execution, {@link #close()} should be called.
 *
 * @return this object
 * @throws java.io.IOException on I/O error
 */
public HttpRequest execute() throws IOException {
    boolean successful = false;

    try {
        if (conn != null) {
            throw new IllegalArgumentException("Connection already executed");
        }

        conn = (HttpURLConnection) reformat(url).openConnection();

        if (body != null) {
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", Integer.toString(body.length));
            conn.setDoInput(true);
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setReadTimeout(READ_TIMEOUT);

        conn.connect();

        if (body != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body);
            out.flush();
            out.close();
        }

        inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream()
                : conn.getErrorStream();

        successful = true;
    } finally {
        if (!successful) {
            close();
        }
    }

    return this;
}

From source file:org.maikelwever.droidpile.backend.ApiConnecter.java

public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException {
    if (data.length < 1) {
        throw new IllegalArgumentException("More than 1 argument is required.");
    }//from   w ww . j a  va 2s . c  o m

    String url = this.baseUrl;
    String suffix = "";
    for (String arg : data) {
        suffix += "/" + arg;
    }

    suffix += "/";

    Log.d("droidpile", "URL we will call: " + url + suffix);

    url += suffix;
    URL uri = new URL(url);
    InputStreamReader is;
    HttpURLConnection con;

    if (url.startsWith("https")) {
        con = (HttpsURLConnection) uri.openConnection();
    } else {
        con = (HttpURLConnection) uri.openConnection();
    }

    String urlParameters = URLEncodedUtils.format(payload, ENCODING);

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", ENCODING);
    con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length));
    con.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    is = new InputStreamReader(con.getInputStream(), ENCODING);

    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(is);
    String read = br.readLine();

    while (read != null) {
        sb.append(read);
        read = br.readLine();
    }
    String stringData = sb.toString();
    con.disconnect();
    return stringData;
}

From source file:net.phalapi.sdk.PhalApiClient.java

protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
    String result = null;/*from w w  w. j  a va2  s.  co m*/
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;

    url = new URL(requestUrl);
    connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST"); // ?
    connection.setUseCaches(false);
    connection.setConnectTimeout(timeoutMs);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    //POST?
    String postContent = "";
    Iterator<Entry<String, String>> iter = params.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
        postContent += "&" + entry.getKey() + "=" + entry.getValue();
    }
    out.writeBytes(postContent);
    out.flush();
    out.close();

    Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);

    in = new InputStreamReader(connection.getInputStream());
    BufferedReader bufferedReader = new BufferedReader(in);
    StringBuffer strBuffer = new StringBuffer();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        strBuffer.append(line);
    }
    result = strBuffer.toString();

    Log.d("[PhalApiClient apiResult]", result);

    if (connection != null) {
        connection.disconnect();
    }

    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {/*  w  w  w .  j a  v a 2  s .c o  m*/
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

        // range
        BigInteger tmpOffset = offset;
        if ((tmpOffset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((tmpOffset == null) || (tmpOffset.signum() == -1)) {
                tmpOffset = BigInteger.ZERO;
            }

            sb.append(tmpOffset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.docd.purefm.tasks.SearchCommandLineTask.java

@Override
protected Void doInBackground(String... params) {
    final CommandFind command = new CommandFind(mStartDirectory.getAbsolutePath(), params);
    // NOTE this doesn't use Shell because we can't create a new CommandLineFile from
    // CommandOutput because executing readlink (which is done in CommandLineFile constructor)
    // will freeze the whole Shell
    DataOutputStream os = null;
    BufferedReader is = null;/*from  w w  w.  j  a  v a  2s.  c o m*/
    BufferedReader err = null;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(mSettings.isSuEnabled() ? "su" : "sh");
        os = new DataOutputStream(process.getOutputStream());
        is = new BufferedReader(new InputStreamReader(process.getInputStream()));
        err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        os.writeBytes(command.toString());
        os.writeBytes("exit\n");
        os.flush();

        String line;
        try {
            while (!isCancelled() && (line = is.readLine()) != null) {
                this.publishProgress(CommandLineFile.fromLSL(null, line));
            }
        } catch (EOFException e) {
            //ignore
        }

        try {
            while (!isCancelled() && (line = err.readLine()) != null) {
                final Matcher denied = DENIED.matcher(line);
                if (denied.matches()) {
                    this.mDenied.add(denied.group(1));
                }
            }
        } catch (EOFException e) {
            //ignore
        }
        process.waitFor();
    } catch (Exception e) {
        Log.w("Exception while searching", e.toString());
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(err);
        if (process != null) {
            try {
                process.destroy();
            } catch (Exception e) {
                //ignored
            }
        }
    }
    return null;
}