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.salesmanager.core.module.impl.integration.payment.PaypalTransactionImpl.java

public Map httpcall(IntegrationProperties keys, CoreModuleService cms, String methodName, String nvpStr)
        throws Exception {

    // return null;

    boolean bSandbox = false;
    if (keys.getProperties5().equals("2")) {// sandbox
        bSandbox = true;/*from  w w  w .j  a v a2 s  .c  o  m*/
    }

    String gv_APIEndpoint = "";
    String PAYPAL_URL = "";
    String gv_Version = "3.3";

    if (bSandbox == true) {
        gv_APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp";
        PAYPAL_URL = new StringBuffer().append(cms.getCoreModuleServiceDevProtocol()).append("://")
                .append(cms.getCoreModuleServiceDevDomain()).append(cms.getCoreModuleServiceDevEnv())
                .append("?cmd=_express-checkout&token=").toString();
        // PAYPAL_URL =
        // "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
    } else {
        gv_APIEndpoint = "https://api-3t.paypal.com/nvp";
        PAYPAL_URL = new StringBuffer().append(cms.getCoreModuleServiceProdProtocol()).append("://")
                .append(cms.getCoreModuleServiceProdDomain()).append(cms.getCoreModuleServiceProdEnv())
                .append("?cmd=_express-checkout&token=").toString();
        // PAYPAL_URL =
        // "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
    }

    String agent = "Mozilla/4.0";
    String respText = "";
    Map nvp = null;

    // deformatNVP( nvpStr );
    String encodedData = "METHOD=" + methodName + "&VERSION=" + gv_Version + "&PWD=" + keys.getProperties2()
            + "&USER=" + keys.getProperties1() + "&SIGNATURE=" + keys.getProperties3() + nvpStr
            + "&BUTTONSOURCE=" + "PP-ECWizard";
    log.debug("REQUEST SENT TO PAYPAL -> " + encodedData);

    HttpURLConnection conn = null;
    DataOutputStream output = null;
    DataInputStream in = null;
    BufferedReader is = null;
    try {
        URL postURL = new URL(gv_APIEndpoint);
        conn = (HttpURLConnection) postURL.openConnection();

        // Set connection parameters. We need to perform input and output,
        // so set both as true.
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Set the content type we are POSTing. We impersonate it as
        // encoded form data
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", agent);

        // conn.setRequestProperty( "Content-Type", type );
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestMethod("POST");

        // get the output stream to POST to.
        output = new DataOutputStream(conn.getOutputStream());
        output.writeBytes(encodedData);
        output.flush();
        // output.close ();

        // Read input from the input stream.
        in = new DataInputStream(conn.getInputStream());
        int rc = conn.getResponseCode();
        if (rc != -1) {
            is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String _line = null;
            while (((_line = is.readLine()) != null)) {
                log.debug("Response line from Paypal -> " + _line);
                respText = respText + _line;
            }
            nvp = StringUtil.deformatUrlResponse(respText);
        } else {
            throw new Exception("Invalid response from paypal, return code is " + rc);
        }

        nvp.put("PAYPAL_URL", PAYPAL_URL);
        nvp.put("NVP_URL", gv_APIEndpoint);

        return nvp;

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (in != null) {
            try {
                in.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (output != null) {
            try {
                output.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }
    }
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath,
        String resourceType) {/*  ww w . j av  a2 s  .  co  m*/

    if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;
        try {

            URL pageurl = new URL(pageURL);
            StringBuffer sb = new StringBuffer(
                    "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>");
            sb.append("<events>" + event + "</events>");
            sb.append("<pageURL>" + pageURL + "</pageURL>");
            sb.append("<pageName>"
                    + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":")
                    + "</pageName>");
            sb.append("<evar1>" + resourcePath + "</evar1>");
            sb.append("<evar2>" + resourceType + "</evar2>");
            sb.append("<visitorID>demomachine</visitorID>");
            sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>");
            sb.append("</request>");

            logger.debug("New Analytics Event: " + sb.toString());

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(sb.toString());
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.error(ex.getMessage());

        }

    }

}

From source file:Main.java

public static String postMultiPart(String urlTo, String post, String filepath, String filefield)
        throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {/*from ww w.  j av  a2  s . co m*/
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();
        result = convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

public HttpResponse execute(HashMap<String, File> files) throws HttpClientException {
    HttpURLConnection conn = null;
    UncloseableInputStream payloadStream = null;
    try {/*from  ww  w .  ja  v  a  2s.c  o m*/
        //            if (parameters != null && !parameters.isEmpty()) {
        //                final StringBuilder buf = new StringBuilder(256);
        //                if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) {
        //                    buf.append('?');
        //                }
        //
        //                int paramIdx = 0;
        //                for (final Map.Entry<String, String> e : parameters.entrySet()) {
        //                    if (paramIdx != 0) {
        //                        buf.append("&");
        //                    }
        //                    final String name = e.getKey();
        //                    final String value = e.getValue();
        //                    buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=")
        //                            .append(URLEncoder.encode(value, CONTENT_CHARSET));
        //                    ++paramIdx;
        //                }
        //
        //                if (!contentSet
        //                        && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) {
        //                    try {
        //                        content = buf.toString().getBytes(CONTENT_CHARSET);
        //                    } catch (UnsupportedEncodingException e) {
        //                        // Unlikely to happen.
        //                        throw new HttpClientException("Encoding error", e);
        //                    }
        //                } else {
        //                    uri += buf;
        //                }
        //            }

        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setConnectTimeout(hc.getConnectTimeout());
        conn.setReadTimeout(hc.getReadTimeout());
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(method);
        conn.setUseCaches(false);
        conn.setDoInput(true);

        if (headers != null && !headers.isEmpty()) {
            for (final Map.Entry<String, List<String>> e : headers.entrySet()) {
                final List<String> values = e.getValue();
                if (values != null) {
                    final String name = e.getKey();
                    for (final String value : values) {
                        conn.addRequestProperty(name, value);
                    }
                }
            }
        }

        if (cookies != null && !cookies.isEmpty()
                || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) {
            final StringBuilder cookieHeaderValue = new StringBuilder(256);
            prepareCookieHeader(cookies, cookieHeaderValue);
            prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue);
            conn.setRequestProperty("Cookie", cookieHeaderValue.toString());
        }

        final String userAgent = hc.getUserAgent();
        if (userAgent != null) {
            conn.setRequestProperty("User-Agent", userAgent);
        }

        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET);
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        if (conn instanceof HttpsURLConnection) {
            setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn);
        }

        // ?
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CONTENT_CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());

        // ???
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\""
                        + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CONTENT_CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
        }

        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        final int statusCode = conn.getResponseCode();
        if (statusCode == -1) {
            throw new HttpClientException("Invalid response from " + uri);
        }
        if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) {
            throw new HttpClientException(
                    "Expected status code " + expectedStatusCodes + ", got " + statusCode);
        } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) {
            throw new HttpClientException("Expected status code 2xx, got " + statusCode);
        }

        final Map<String, List<String>> headerFields = conn.getHeaderFields();
        final Map<String, String> inMemoryCookies = hc.getInMemoryCookies();
        if (headerFields != null) {
            final List<String> newCookies = headerFields.get("Set-Cookie");
            if (newCookies != null) {
                for (final String newCookie : newCookies) {
                    final String rawCookie = newCookie.split(";", 2)[0];
                    final int i = rawCookie.indexOf('=');
                    final String name = rawCookie.substring(0, i);
                    final String value = rawCookie.substring(i + 1);
                    inMemoryCookies.put(name, value);
                }
            }
        }

        if (isStatusCodeError(statusCode)) {
            // Got an error: cannot read input.
            payloadStream = new UncloseableInputStream(getErrorStream(conn));
        } else {
            payloadStream = new UncloseableInputStream(getInputStream(conn));
        }
        final HttpResponse resp = new HttpResponse(statusCode, payloadStream,
                headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies);
        if (handler != null) {
            try {
                handler.onResponse(resp);
            } catch (HttpClientException e) {
                throw e;
            } catch (Exception e) {
                throw new HttpClientException("Error in response handler", e);
            }
        } else {
            final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir());
            resp.preload(temp);
            temp.delete();
        }
        return resp;
    } catch (SocketTimeoutException e) {
        if (handler != null) {
            try {
                handler.onTimeout();
                return null;
            } catch (HttpClientException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new HttpClientException("Error in response handler", e2);
            }
        } else {
            throw new HttpClientException("Response timeout from " + uri, e);
        }
    } catch (IOException e) {
        throw new HttpClientException("Connection failed to " + uri, e);
    } finally {
        if (conn != null) {
            if (payloadStream != null) {
                // Fully read Http response:
                // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html
                try {
                    while (payloadStream.read(buffer) != -1) {
                        ;
                    }
                } catch (IOException ignore) {
                }
                payloadStream.forceClose();
            }
            conn.disconnect();
        }
    }
}

From source file:com.android.leanlauncher.LauncherTransitionable.java

private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
    DataOutputStream out = null;
    try {/*from   w w  w  . j a v  a2 s .  c  om*/
        out = new DataOutputStream(context.openFileOutput(LauncherFiles.LAUNCHER_PREFERENCES, MODE_PRIVATE));
        out.writeUTF(configuration.locale);
        out.writeInt(configuration.mcc);
        out.writeInt(configuration.mnc);
        out.flush();
    } catch (FileNotFoundException e) {
        // Ignore
    } catch (IOException e) {
        //noinspection ResultOfMethodCallIgnored
        context.getFileStreamPath(LauncherFiles.LAUNCHER_PREFERENCES).delete();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java

/**
 * Convert the array of unix times to a compressed timeline, and return the byte array
 * representing that compressed timeline
 * @param times an int array giving the unix times to be compressed
 * @return the compressed timeline/*from   ww w  .  java 2s . c om*/
 */
@Override
public byte[] compressDateTimes(final List<DateTime> times) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final DataOutputStream dataStream = new DataOutputStream(outputStream);
    try {
        int lastTime = 0;
        int lastDelta = 0;
        int repeatCount = 0;
        for (DateTime time : times) {
            final int newTime = DateTimeUtils.unixSeconds(time);
            if (lastTime == 0) {
                lastTime = newTime;
                writeTime(0, lastTime, dataStream);
                continue;
            } else if (newTime < lastTime) {
                log.warn("In TimelineCoder.compressTimes(), newTime {} is < lastTime {}; ignored", newTime,
                        lastTime);
                continue;
            }
            final int delta = newTime - lastTime;
            final boolean deltaWorks = delta <= TimelineOpcode.MAX_DELTA_TIME;
            final boolean sameDelta = repeatCount > 0 && delta == lastDelta;
            if (deltaWorks) {
                if (sameDelta) {
                    repeatCount++;
                    if (repeatCount == MAX_SHORT_REPEAT_COUNT) {
                        writeRepeatedDelta(delta, repeatCount, dataStream);
                        repeatCount = 0;
                    }
                } else {
                    if (repeatCount > 0) {
                        writeRepeatedDelta(lastDelta, repeatCount, dataStream);
                    }
                    repeatCount = 1;
                }
                lastDelta = delta;
            } else {
                if (repeatCount > 0) {
                    writeRepeatedDelta(lastDelta, repeatCount, dataStream);
                }
                writeTime(0, newTime, dataStream);
                repeatCount = 0;
                lastDelta = 0;
            }
            lastTime = newTime;
        }
        if (repeatCount > 0) {
            writeRepeatedDelta(lastDelta, repeatCount, dataStream);
        }
        dataStream.flush();
        return outputStream.toByteArray();
    } catch (IOException e) {
        log.error("Exception compressing times list of length {}", times.size(), e);
        return null;
    }
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ?/* w ww  .  j  a v  a  2 s .  com*/
 * @param appWorkspace  ?
 * @param source        ?
 * @param target        ??
 * @param args          JSONArray
 * @param callbackCtx   nativejs
 *
 * args[2] fileKey       ?name file?
 * args[3] fileName      ??? image.jpg?
 * args[4] mimeType      ?mimeimage/jpeg?
 * args[5] params        HTTP????/
 * args[6] trustEveryone 
 * args[7] chunkedMode   ??????true
 * @return FileUploadResult
 */
private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args,
        XCallbackContext callbackCtx) {
    XLog.d(CLASS_NAME, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
        JSONObject headers = args.optJSONObject(8);
        if (headers == null && params != null) {
            headers = params.optJSONObject("headers");
        }
        String objectId = args.getString(9);
        //------------------ 
        URL url = new URL(target);
        conn = getURLConnection(url, trustEveryone);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
        setCookieProperty(conn, target);
        // ??
        handleRequestHeader(headers, conn);
        byte[] extraBytes = extraBytesFromParams(params, fileKey);

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
        byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE);

        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source);
        int maxBufferSize = XConstant.BUFFER_LEN;

        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraBytes.length + midParams.length() + tailParams.length()
                    + fileNameBytes.length;
            XLog.d(CLASS_NAME, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            XLog.d(CLASS_NAME, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }
        // ???
        OutputStream ouputStream = conn.getOutputStream();
        DataOutputStream dos = new DataOutputStream(ouputStream);
        dos.write(extraBytes);
        dos.write(fileNameBytes);
        dos.writeBytes(midParams);
        XFileUploadResult result = new XFileUploadResult();
        FileTransferProgress progress = new FileTransferProgress();
        int bytesAvailable = fileInputStream.available();
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];
        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        long totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bytesRead);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            if (objectId != null) {
                //?js??object ID?
                progress.setTotal(bytesAvailable);
                XLog.d(CLASS_NAME, "total=" + bytesAvailable);
                progress.setLoaded(totalBytes);
                progress.setLengthComputable(true);
                XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK,
                        progress.toJSONObject());
                progressResult.setKeepCallback(true);
                callbackCtx.sendExtensionResult(progressResult);
            }
            synchronized (abortTriggered) {
                if (objectId != null && abortTriggered.contains(objectId)) {
                    abortTriggered.remove(objectId);
                    throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED);
                }
            }
        }
        dos.writeBytes(tailParams);
        fileInputStream.close();
        dos.flush();
        dos.close();
        checkConnection(conn);
        setUploadResult(result, conn);

        // 
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory);
        }

        XLog.d(CLASS_NAME, "****** About to return a result from upload");
        return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject());

    } catch (AbortException e) {
        JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn);
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.ERROR, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.getMessage());
        return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        XLog.e(CLASS_NAME, error.toString());
        return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public Boolean upload_v2() {
    this.downloader.login();
    String page = this.downloader.getUrlData(this.URL);
    String viewstate = "";
    Pattern p = Pattern//from w w  w.j a v  a2  s .  c  om
            .compile("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"([^\"]+)\" />");
    Matcher m = p.matcher(page);
    m.find();
    viewstate = m.group(1);

    //System.out.println("viewstate=" + viewstate);
    // got viewstate

    InputStream fn_is = null;
    String raw_upload_data = "";
    try {
        fn_is = new ByteArrayInputStream(
                ("GC2BNHP,2010-11-07T14:00Z,Write note,\"bla bla\"").getBytes("UTF-8"));
        raw_upload_data = "GC2BNHP,2010-11-07T20:50Z,Write note,\"bla bla\"".getBytes("UTF-8").toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    String cookies_string = this.downloader.getCookies();

    ArrayList<InputStream> files = new ArrayList();
    files.add(fn_is);

    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("ctl00$ContentBody$btnUpload", "Upload Field Note");
    ht.put("ctl00$ContentBody$chkSuppressDate", "");
    //   ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt");
    ht.put("__VIEWSTATE", viewstate);

    HttpData data = HttpRequest.post(this.URL, ht, files, cookies_string);
    //System.out.println(data.content);

    String boundary = "----------ThIs_Is_tHe_bouNdaRY_$";
    String crlf = "\r\n";

    URL url = null;
    try {
        url = new URL(this.URL);
    } catch (MalformedURLException e2) {
        e2.printStackTrace();
    }
    HttpURLConnection con = null;
    try {
        con = (HttpURLConnection) url.openConnection();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    try {
        con.setRequestMethod("POST");
    } catch (java.net.ProtocolException e) {
        e.printStackTrace();
    }

    con.setRequestProperty("Cookie", cookies_string);
    //System.out.println("Cookie: " + cookies_string[0] + "=" + cookies_string[1]);

    con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
    con.setRequestProperty("Pragma", "no-cache");
    //con.setRequestProperty("Connection", "Keep-Alive");
    String content_type = String.format("multipart/form-data; boundary=%s", boundary);
    con.setRequestProperty("Content-Type", content_type);

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(con.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

    String raw_data = "";

    //
    raw_data = raw_data + "--" + boundary + crlf;
    raw_data = raw_data
            + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$btnUpload")
            + crlf;
    raw_data = raw_data + crlf;
    raw_data = raw_data + "Upload Field Note" + crlf;
    //

    //
    raw_data = raw_data + "--" + boundary + crlf;
    raw_data = raw_data
            + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$chkSuppressDate")
            + crlf;
    raw_data = raw_data + crlf;
    raw_data = raw_data + "" + crlf;
    //

    //
    raw_data = raw_data + "--" + boundary + crlf;
    raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "__VIEWSTATE") + crlf;
    raw_data = raw_data + crlf;
    raw_data = raw_data + viewstate + crlf;
    //

    //
    raw_data = raw_data + "--" + boundary + crlf;
    raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"",
            "ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt") + crlf;
    raw_data = raw_data + String.format("Content-Type: %s", "text/plain") + crlf;
    raw_data = raw_data + crlf;
    raw_data = raw_data + raw_upload_data + crlf;
    //

    //
    raw_data = raw_data + "--" + boundary + "--" + crlf;
    raw_data = raw_data + crlf;

    try {
        this.SendPost(this.URL, raw_data, cookies_string);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    //System.out.println(raw_data);

    try {
        dos.writeBytes(raw_data);
        //dos.writeChars(raw_data);
        dos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    HttpData ret2 = new HttpData();
    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(con.getInputStream()), HTMLDownloader.large_buffer_size);
        String line;
        while ((line = rd.readLine()) != null) {
            ret2.content += line + "\r\n";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    //get headers
    Map<String, List<String>> headers = con.getHeaderFields();
    Set<Entry<String, List<String>>> hKeys = headers.entrySet();
    for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
        Entry<String, List<String>> m99 = i.next();

        //System.out.println("HEADER_KEY" + m99.getKey() + "=" + m99.getValue());
        ret2.headers.put(m99.getKey(), m99.getValue().toString());
        if (m99.getKey().equals("set-cookie"))
            ret2.cookies.put(m99.getKey(), m99.getValue().toString());
    }
    try {
        dos.close();
        rd.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //System.out.println(ret2.content);

    //System.out.println("FFFFFFFFFFFFFFFFFFFFFFFFFFFF");
    ClientHttpRequest client_req;
    try {
        client_req = new ClientHttpRequest(this.URL);
        String[] cookies_string2 = this.downloader.getCookies2();
        for (int jk = 0; jk < cookies_string2.length; jk++) {
            System.out.println(cookies_string2[jk * 2] + "=" + cookies_string2[(jk * 2) + 1]);
            client_req.setCookie(cookies_string2[jk * 2], cookies_string2[(jk * 2) + 1]);
        }
        client_req.setParameter("ctl00$ContentBody$btnUpload", "Upload Field Note");
        client_req.setParameter("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt", fn_is);
        InputStream response = client_req.post();
        //System.out.println(this.convertStreamToString(response));
    } catch (IOException e) {
        e.printStackTrace();
    }

    //ArrayList<InputStream> files = new ArrayList();
    files.clear();
    files.add(fn_is);

    Hashtable<String, String> ht2 = new Hashtable<String, String>();
    ht2.put("ctl00$ContentBody$btnUpload", "Upload Field Note");
    ht2.put("ctl00$ContentBody$chkSuppressDate", "");
    //   ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt");
    ht2.put("__VIEWSTATE", viewstate);

    HttpData data3 = HttpRequest.post(this.URL, ht2, files, cookies_string);
    //System.out.println(data3.content);

    //      String the_page2 = this.downloader.get_reader_mpf(this.URL, raw_data, null, true, boundary);
    //System.out.println("page2=\n" + the_page2);

    Boolean ret = false;
    return ret;
}

From source file:com.otaupdater.DownloadsActivity.java

private void flashFiles(String[] files, boolean backup, boolean wipeCache, boolean wipeData) {
    try {/*from  w w  w.  ja v a 2s.c  om*/
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        os.writeBytes("mkdir -p /cache/recovery/\n");
        os.writeBytes("rm -f /cache/recovery/command\n");
        os.writeBytes("rm -f /cache/recovery/extendedcommand\n");
        os.writeBytes("echo 'boot-recovery' >> /cache/recovery/command\n");

        //no official cwm for sony, so use extendedcommand. sony devices cannot use regular command file
        if (Build.MANUFACTURER.toLowerCase(Locale.US).contains("sony")) {
            if (backup) {
                os.writeBytes("echo 'backup_rom /sdcard/clockworkmod/backup/ota_"
                        + new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US).format(new Date())
                        + "' >> /cache/recovery/extendedcommand\n");
            }
            if (wipeData) {
                os.writeBytes("echo 'format(\"/data\");' >> /cache/recovery/extendedcommand\n");
            }
            if (wipeCache) {
                os.writeBytes("echo 'format(\"/cache\");' >> /cache/recovery/extendedcommand\n");
            }

            for (String file : files) {
                os.writeBytes("echo 'install_zip(\"" + file + "\");' >> /cache/recovery/extendedcommand\n");
            }
        } else {
            if (backup) {
                os.writeBytes("echo '--nandroid' >> /cache/recovery/command\n");
            }
            if (wipeData) {
                os.writeBytes("echo '--wipe_data' >> /cache/recovery/command\n");
            }
            if (wipeCache) {
                os.writeBytes("echo '--wipe_cache' >> /cache/recovery/command\n");
            }

            for (String file : files) {
                os.writeBytes("echo '--update_package=" + file + "' >> /cache/recovery/command\n");
            }
        }

        String rebootCmd = PropUtils.getRebootCmd();
        if (!rebootCmd.equals("$$NULL$$")) {
            os.writeBytes("sync\n");
            if (rebootCmd.endsWith(".sh")) {
                os.writeBytes("sh " + rebootCmd + "\n");
            } else {
                os.writeBytes(rebootCmd + "\n");
            }
        }

        os.writeBytes("sync\n");
        os.writeBytes("exit\n");
        os.flush();
        p.waitFor();
        ((PowerManager) getSystemService(POWER_SERVICE)).reboot("recovery");
    } catch (Exception e) {
        e.printStackTrace();
    }
}