Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

In this page you can find the example usage for java.io DataOutputStream writeBytes.

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:org.rifidi.edge.adapter.csl.util.CslRfidTagServer.java

private void StartTCPClient() {
    Socket tagServerSocket;/*from   w ww .  j a va 2s .  co  m*/

    synchronized (tcpClientStarted) {
        if (tcpClientStarted)
            return;
        else
            tcpClientStarted = true;
    }

    while (true) {
        try {
            String data;

            tagServerSocket = new Socket("localhost", this.notifyAddrPort);
            DataOutputStream outToServer = new DataOutputStream(tagServerSocket.getOutputStream());

            while (true) {

                try {
                    // Thread.sleep(200);
                    Thread.sleep(20);
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }

                int cnt_rd = 0;
                // while((cnt_rd < 100) && (TagBuffer.size() > 0))
                while ((cnt_rd < 10) && (TagBuffer.size() > 0)) {
                    synchronized (TagBuffer) {
                        if (TagBuffer.size() != 0) {
                            data = "";
                            TagInfo tag = TagBuffer.peek();
                            data += "ReaderIP:" + tag.addr;
                            data += "|ID:" + tag.epc;
                            data += "|Antenna:" + tag.antennaPort;
                            data += "|Timestamp:" + tag.timestamp;
                            data += "|PC:" + tag.pc;
                            data += "|RSSI:" + tag.rssi + "\n";

                            //                        logger.info(String.format("Return: %s \n", data));
                            //                        logger.info(String.format("TagBuffer Size: %s \n", TagBuffer.size()));

                            TagBuffer.remove();
                            outToServer.writeBytes(data);
                            System.out.println(data);

                            cnt_rd++;
                        }
                    }
                }
                synchronized (tcpClientStarted) {
                    if (!tcpClientStarted)
                        break;
                }
            }
            tagServerSocket.close();
            tagServerSocket = null;

        } catch (UnknownHostException e) {
            tagServerSocket = null;
            logger.error("Unable to connect to port " + this.notifyAddrPort);
        } catch (IOException e) {
            // tagServerSocket = null;
            String data1 = String.format("00");
            logger.error("Unable to send tag data to server" + data1);
        }
        synchronized (tcpClientStarted) {
            if (!tcpClientStarted)
                break;
        }
    }

}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

public int uploadFile(String sourceFileUri) {
    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php";
    String fileName = sourceFileUri;
    Log.d("file upload url", upLoadServerUri);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.d("uploadFile", "Source File Does not exist");
        return 0;
    }/*from   w w  w  .j  a  v  a 2s  . c o  m*/
    int serverResponseCode = 0;
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-"
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

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

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        //close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();
        Log.d("Contact file ", "uploaded");
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path//  w w  w  .  j  ava  2s  .co  m
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

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

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}

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  .  ja  va2  s. c  o  m
            .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.acc.android.network.operator.base.BaseHttpOperator.java

public static String post(String actionUrl, UploadData uploadData) {
    HttpURLConnection httpURLConnection = null;
    DataOutputStream dataOutputStream = null;
    InputStream inputStream = null;
    String resultString = null;//from www .j  a v a 2 s .  c om
    // if (AppLibConstant.isUseLog()) {
    LogUtil.info("actionUrl", actionUrl);
    LogUtil.info("uploadData", uploadData);
    LogUtil.info("sessionStr", sessionStr);
    // }
    try {
        URL url = new URL(actionUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        // httpURLConnection.setRequestProperty("Cookie",
        // "JSESSIONID=320C57C083E7F678ED14B8974732225E");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Content-Type",
                UploadConstant.MULTIPART_FORM_DATA + ";boundary=" + UploadConstant.BOUNDARY);
        // httpURLConnection.setChunkedStreamingMode(0);
        sessonInject(httpURLConnection);
        dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        addFormField(uploadData.getParamMap(), dataOutputStream);
        if (!ListUtil.isEmpty(uploadData.getUploadFiles())) {
            addUploadDataContent(uploadData.getUploadFiles(), dataOutputStream
            // , TAGSTRING
            );
        }
        dataOutputStream.writeBytes(UploadConstant.LINEEND);
        dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY
                + UploadConstant.TWOHYPHENS + UploadConstant.LINEEND);
        // try {
        dataOutputStream.flush();
        // } catch (Exception exception) {
        // if (dataOutputStream != null) {
        // dataOutputStream.close();
        // }
        // dataOutputStream = new DataOutputStream(
        // httpURLConnection.getOutputStream());
        // addFormField(uploadData.getParamMap(), dataOutputStream);
        // if (!ListUtil.isEmpty(uploadData.getUploadFiles())) {
        // addUploadDataContent(uploadData.getUploadFiles(),
        // dataOutputStream
        // // , TAGSTRING
        // );
        // }
        // dataOutputStream.writeBytes(UploadConstant.LINEEND);
        // dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS
        // + UploadConstant.BOUNDARY + UploadConstant.TWOHYPHENS
        // + UploadConstant.LINEEND);
        // dataOutputStream.flush();
        // }
        inputStream = httpURLConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        resultString = br.readLine();
        // if (AppLibConstant.isUseLog()) {
        LogUtil.info("resultString", resultString);
        // }
        // LogUtil.systemOut(resultString);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dataOutputStream != null) {
                dataOutputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
    return resultString;
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. /*from ww  w .  j  a  va2s  .  c  om*/
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

public int uploadFile(String sourceFileUri, String fileName) {

    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php";

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }//  w  w w  .ja v  a 2s  . c  o  m
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
        // connection to
        // the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", sourceFileUri);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of
        // maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);

        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

        // close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:edu.slu.action.ObjectAction.java

/**
 * Public API proxy to generate a new access token through Auth0.
 * /*from w  w  w.j  a v  a  2 s  . c  o  m*/
 * @param refreshToken The refresh token given to the user on registration or generateNewRefreshToken
 * @return the Auth0 /oauth/token return's access_token property
 */
public void generateNewAccessToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate an access token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();
        tokenRequestParams.element("grant_type", "refresh_token");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("refresh_token", received.getString("refresh_token"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
* Public API proxy to generate a new refresh token through Auth0.
* 
* @param authCode An authorization code generated by the Auth0 /authorize call.
* @return the Auth0 /oauth/token return's refresh_token value
*///from  w w w. j  a va 2s.c o  m
public void generateNewRefreshToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate a refresh token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();

        tokenRequestParams.element("grant_type", "authorization_code");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("code", received.getString("authorization_code"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject(); //We were never going to get a response, so return an empty object.
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}