Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:com.sim2dial.dialer.ChatFragment.java

private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) {
    String fileName;/*from   w  w w.j  a v  a  2s. co m*/
    if (filePath != null) {
        File sourceFile = new File(filePath);
        fileName = sourceFile.getName();
    } else {
        fileName = getString(R.string.temp_photo_name_with_date).replace("%s",
                String.valueOf(System.currentTimeMillis()));
    }

    if (getResources().getBoolean(R.bool.hash_images_as_name_before_upload)) {
        fileName = String.valueOf(hashBitmap(file)) + ".jpg";
    }

    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";

        URL url = new URL(uploadServerUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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);

        ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream());
        pos.setListener(new OutputStreamListener() {
            @Override
            public void onBytesWrite(int count) {
                bytesSent += count;
                progressBar.setProgress(bytesSent * 100 / imageSize);
            }
        });
        DataOutputStream dos = new DataOutputStream(pos);

        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);

        file.compress(CompressFormat.JPEG, compressorQuality, dos);

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

        dos.flush();
        dos.close();

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();

        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return response;
}

From source file:org.xingjitong.ChatFragment.java

private String uploadImage(String filePath, Bitmap file, int compressorQuality, final int imageSize) {
    String fileName;//from  ww  w .  jav  a 2 s  . co m
    if (filePath != null) {
        File sourceFile = new File(filePath);
        fileName = sourceFile.getName();
    } else {
        fileName = getString(R.string.temp_photo_name_with_date).replace("%s",
                String.valueOf(System.currentTimeMillis()));
    }

    String response = null;
    HttpURLConnection conn = null;
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";

        URL url = new URL(uploadServerUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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);

        ProgressOutputStream pos = new ProgressOutputStream(conn.getOutputStream());
        pos.setListener(new OutputStreamListener() {
            @Override
            public void onBytesWrite(int count) {
                bytesSent += count;
                progressBar.setProgress(bytesSent * 100 / imageSize);
            }
        });
        DataOutputStream dos = new DataOutputStream(pos);

        dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        dos.writeBytes(lineEnd);

        file.compress(CompressFormat.JPEG, compressorQuality, dos);

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

        dos.flush();
        dos.close();

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int bytesRead;
        byte[] bytes = new byte[1024];
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();
        is.close();

        response = new String(bytesReceived);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    return response;
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void appendToFile(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {

    if (!isNull(ArgList) && !isUndefined(ArgList)) {
        try {/*from  w w w  .ja  v  a 2s .  co m*/
            FileOutputStream file = new FileOutputStream(Context.toString(ArgList[0]), true);
            DataOutputStream out = new DataOutputStream(file);
            out.writeBytes(Context.toString(ArgList[1]));
            out.flush();
            out.close();
        } catch (Exception er) {
            throw Context.reportRuntimeError(er.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call appendToFile requires arguments.");
    }
}

From source file:IndexService.IndexServer.java

public boolean setindexstatus(String indexloc, int status) {
    if (!testmode) {
        Path indexpath = new Path(indexloc);
        try {//from  w  ww  .ja va  2  s . c om
            String dbname = indexpath.getParent().getParent().getName();
            if (dbname.endsWith(".db")) {
                dbname = dbname.substring(0, dbname.lastIndexOf(".db"));
            }
            return db.setIndexStatus(dbname, indexpath.getParent().getName(), indexpath.getName(), status);
        } catch (HiveException e1) {
            e1.printStackTrace();
            return false;
        }
    } else {
        try {
            ArrayList<IndexItemStatus> statuss = new ArrayList<IndexItemStatus>();
            File file = new File("indexconf");
            boolean exist = false;
            if (file.exists()) {
                DataInputStream dis = new DataInputStream(new FileInputStream(file));
                int num = dis.readInt();
                for (int i = 0; i < num; i++) {
                    IndexItemStatus itemstatus = new IndexItemStatus();
                    itemstatus.read(dis);
                    if (itemstatus.indexlocation.equals(indexloc)) {
                        itemstatus.status = status;
                        exist = true;
                    }
                    statuss.add(itemstatus);
                }
                dis.close();

                DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
                dos.writeInt(statuss.size());
                for (IndexItemStatus indexItemStatus : statuss) {
                    indexItemStatus.write(dos);
                }
                dos.close();
            }
            if (exist)
                return true;
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

From source file:iracing.webapi.IracingWebApi.java

private String doPostRequestUrlEncoded(boolean needForumCookie, String url, String parameters)
        throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return null;
    }//ww  w .j a v a 2  s.  c  o  m
    if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return null;
    }
    String output = null;
    try {
        // URL of CGI-Bin script.
        URL oUrl = new URL(url);
        // URL connection channel.
        HttpURLConnection urlConn = (HttpURLConnection) oUrl.openConnection();
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        // Let the RTS know that we want to do output.
        urlConn.setDoOutput(true);
        // No caching, we want the real thing.
        urlConn.setUseCaches(false);
        urlConn.addRequestProperty(COOKIE, cookie);

        // request to have the response gzipped (bringing a 3.5Mb response down to 175kb)
        urlConn.addRequestProperty("Accept-Encoding", "gzip");

        urlConn.setRequestMethod("POST");
        // Specify the content type.
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream());
        try {
            printout.writeBytes(parameters);
            printout.flush();
        } finally {
            printout.close();
        }

        output = getResponseText(urlConn);
        //            System.out.println(output);

        urlConn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}

From source file:com.intel.xdk.device.Device.java

public void getRemoteDataExt(JSONObject obj) {
    String requestUrl;//from  ww w . j av  a  2s.  com
    String id;
    String method;
    String body;
    String headers;
    try {
        //Request url
        requestUrl = obj.getString("url");

        //ID that correlates the request to the event
        id = obj.getString("id");

        //Request method
        method = obj.getString("method");

        //Request body
        body = obj.getString("body");

        //Request header
        headers = obj.getString("headers");

        String js = null;
        if (method == null || method.length() == 0)
            method = "GET";

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        boolean forceUTF8 = false;

        try {
            if (headers.length() > 0) {
                String[] headerArray = headers.split("&");

                //Set request header
                for (String header : headerArray) {
                    String[] headerPair = header.split("=");
                    if (headerPair.length == 2) {
                        String field = headerPair[0];
                        String value = headerPair[1];
                        if (field != null && value != null) {
                            if (!"content-length".equals(field.toLowerCase())) {//skip Content-Length - causes error because it is managed by the request
                                connection.setRequestProperty(field, value);
                            }

                            field = field.toLowerCase();
                            value = value.toLowerCase();
                            if (field.equals("content-type") && value.indexOf("charset") > -1
                                    && value.indexOf("utf-8") > -1) {
                                forceUTF8 = true;
                            }
                        }
                    }
                }

            }

            if ("POST".equalsIgnoreCase(method)) {
                connection.setRequestMethod(method);
                connection.setDoOutput(true);
                connection.setFixedLengthStreamingMode(body.length());
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(body);
                dStream.flush();
                dStream.close();
            }

            //inject response
            int statusCode = connection.getResponseCode();

            final StringBuilder response = new StringBuilder();
            try {
                InputStream responseStream = connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                br.close();
            } catch (Exception e) {
            }

            String responseBody = null;
            // how to handle UTF8 without EntityUtils?
            //                if (forceUTF8) {
            //                    responseBody = EntityUtils.toString(entity, "UTF-8");
            //                } else {
            //                    responseBody = EntityUtils.toString(entity);
            //                }
            responseBody = response.toString();
            String responseMessage = connection.getResponseMessage();

            char[] bom = { 0xef, 0xbb, 0xbf };
            //check for BOM characters, then strip if present
            if (responseBody.length() >= 3 && responseBody.charAt(0) == bom[0]
                    && responseBody.charAt(1) == bom[1] && responseBody.charAt(2) == bom[2]) {
                responseBody = responseBody.substring(3);
            }

            //escape existing backslashes
            responseBody = responseBody.replaceAll("\\\\", "\\\\\\\\");

            //escape internal double-quotes
            responseBody = responseBody.replaceAll("\"", "\\\\\"");
            responseBody = responseBody.replaceAll("'", "\\\\'");

            //replace linebreaks with \n
            responseBody = responseBody.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

            StringBuilder extras = new StringBuilder("{");
            extras.append(String.format("status:'%d',", statusCode));

            String status = null;
            switch (statusCode) {
            case 200:
                status = "OK";
                break;
            case 201:
                status = "CREATED";
                break;
            case 202:
                status = "Accepted";
                break;
            case 203:
                status = "Partial Information";
                break;
            case 204:
                status = "No Response";
                break;
            case 301:
                status = "Moved";
                break;
            case 302:
                status = "Found";
                break;
            case 303:
                status = "Method";
                break;
            case 304:
                status = "Not Modified";
                break;
            case 400:
                status = "Bad request";
                break;
            case 401:
                status = "Unauthorized";
                break;
            case 402:
                status = "PaymentRequired";
                break;
            case 403:
                status = "Forbidden";
                break;
            case 404:
                status = "Not found";
                break;
            case 500:
                status = "Internal Error";
                break;
            case 501:
                status = "Not implemented";
                break;
            case 502:
                status = "Service temporarily overloaded";
                break;
            case 503:
                status = "Gateway timeout";
                break;
            }
            extras.append(String.format("statusText:'%s',", status));
            extras.append("headers: {");

            List<String> cookieData = new ArrayList<String>();
            Map<String, List<String>> allHeaders = connection.getHeaderFields();
            for (String key : allHeaders.keySet()) {
                if (key == null) {
                    continue;
                }
                String value = connection.getHeaderField(key);
                value = value.replaceAll("'", "\\\\'");
                if (key.toLowerCase().equals("set-cookie"))
                    cookieData.add(value);
                else
                    extras.append(String.format("'%s':'%s',", key, value));
            }

            String concatCookies = cookieData.toString();
            concatCookies = concatCookies.substring(0, concatCookies.length());
            extras.append(String.format("'Set-Cookie':'%s',",
                    concatCookies.substring(1, concatCookies.length() - 1)));

            String cookieArray = "[";
            for (int i = 0; i < cookieData.size(); i++)
                cookieArray += String.format("'%s',", cookieData.get(i));
            cookieArray += "]";

            extras.append("'All-Cookies': " + cookieArray);
            extras.append("} }");

            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=true;e.id='%s';e.response='%s';e.extras=%s;document.dispatchEvent(e);",
                    id, responseBody, extras.toString());

        } catch (Exception ex) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, ex.getMessage());
        } catch (OutOfMemoryError err) {
            js = String.format(
                    "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.remote.data',true,true);e.success=false;e.id='%s';e.response='';e.extras={};e.error='%s';document.dispatchEvent(e);",
                    id, err.getMessage());
        } finally {
            connection.disconnect();
        }

        injectJS(js);

    } catch (Exception e) {
        Log.d("getRemoteDataExt", e.getMessage());
    }
}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

/******************************************************************************************
 * Uploads the note to the server/*  ww w .j av  a2s.  c  om*/
 ******************************************************************************************
 * @param currentNoteId Unique note ID to be uploaded
 * @return True if uploaded, false if not
 ******************************************************************************************/
boolean uploadOneNote(long currentNoteId) {
    boolean result = false;
    final String postUrl = "http://FountainCityCycling.org/post/";

    try {

        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        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("Cycleatl-Protocol-Version", "4");

        /*
        Change protocol to 2 for Note, and change the point where you zip up the body.  (Dont zip up trip body)
        Since notes don't work either, this may not solve it.
         */

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

        JSONObject note = getNoteJSON(currentNoteId);
        deviceId = getDeviceId();

        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"note\"\r\n\r\n" + note.toString() + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
                + String.valueOf(kSaveNoteProtocolVersion) + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"device\"\r\n\r\n" + deviceId + "\r\n");

        if (imageDataNull == false) {
            dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                    + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n"
                    + "Content-Type: image/jpeg\r\n\r\n");
            dos.write(imageData);
            dos.writeBytes("\r\n");
        }

        dos.writeBytes("--cycle*******notedata*******columbus--\r\n");

        dos.flush();
        dos.close();

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        // JSONObject responseData = new JSONObject(serverResponseMessage);
        Log.v("KENNY", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        responseMessage = serverResponseMessage;
        responseCode = serverResponseCode;

        // 200 - 202 means successfully went to server and uploaded
        if (serverResponseCode == 200 || serverResponseCode == 201 || serverResponseCode == 202) {
            mDb.open();
            mDb.updateNoteStatus(currentNoteId, NoteData.STATUS_SENT);
            mDb.close();
            result = true;
        }
    } catch (IllegalStateException e) {
        Log.d("KENNY", "Note Catch: Illegal State Exception: " + e);
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        Log.d("KENNY", "Note Catch: IOException: " + e);
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        Log.d("KENNY", "Note Catch: JSONException: " + e);
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:JavaTron.AudioTron.java

/**
 * Method to execute a POST Request to the Audiotron - JSC
 * /*from   www .  jav a2 s.c o m*/
 * @param address - The requested page
 * @param args - The POST data
 * @param parser - A Parser Object fit for parsing the response
 *
 * @return null on success, a string on error.  The string describes
 *         the error.
 *
 * @throws IOException
 */
protected String post(String address, Vector args, Parser parser) throws IOException {
    String ret = null;
    URL url;
    HttpURLConnection conn;
    String formData = new String();

    // Build the POST data
    for (int i = 0; i < args.size(); i += 2) {
        if (showPost) {
            System.out.print("POST: " + args.get(i).toString() + " = ");
            System.out.println(args.get(i + 1).toString());
        }
        formData += URLEncoder.encode(args.get(i).toString(), "UTF-8") + "="
                + URLEncoder.encode(args.get(i + 1).toString(), "UTF-8");
        if (i + 2 != args.size())
            formData += "&";
    }

    // Build the connection Headers and POST the data
    try {
        url = new URL("http://" + getServer() + address);
        if (showAddress || showPost) {
            System.out.println("POST: " + address);
            System.out.println("POST: " + formData);
        }
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // Authorization header
        String auth = getUsername() + ":" + getPassword();
        conn.setRequestProperty("Authorization", "Basic " + B64Encode(auth.getBytes()));
        // Debug
        if (showAuth) {
            System.out.println("POST: AUTH: " + auth);
        }
        conn.setRequestProperty("Content Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(formData.getBytes().length));
        conn.setRequestProperty("Content-Language", "en-US");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Send the request to the audiotron
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(formData);
        wr.flush();
        wr.close();

        // Process the Response
        if (conn.getResponseCode() != 200 && conn.getResponseCode() != 302) {
            try {
                ret = conn.getResponseMessage();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            if (ret == null) {
                ret = "Unknown Error";
            }
            if (parser != null) {
                parser.begin(ret);
            }
            return ret;
        }

        isr = new InputStreamReader(conn.getInputStream());

        BufferedReader reader = new BufferedReader(isr);
        String s;

        getBuffer = new StringBuffer();

        if (parser != null) {
            parser.begin(null);
        }

        while ((s = reader.readLine()) != null) {
            if (showGet) {
                System.out.println(s);
            }
            getBuffer.append(s);
            getBuffer.append("\n");
            if (parser == null) {
                //  getBuffer.append(s);
            } else {
                if (!parser.parse(s)) {
                    return "Parse Error";
                }
            }
        }

        if (parser == null && showUnparsedOutput) {
            System.out.println(getBuffer);
        }
        if (parser != null) {
            parser.end(false);
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        // if this happens, call the parse method if there is a parser
        // with a null value to indicate an error
        if (parser != null) {
            parser.end(true);
        }
        throw (ioe);
    } finally {
        try {
            isr.close();
        } catch (Exception e) {
            // this is ok
        }
    }

    return ret;
}

From source file:iracing.webapi.IracingWebApi.java

private SendPrivateMessageResult sendPrivateMessage(int customerDefinitionType, String customer, String subject,
        String message) throws IOException, LoginException {
    if (!cookieMap.containsKey(JSESSIONID)) {
        if (login() != LoginResponse.Success)
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }//  w w  w  . ja v a 2 s.co m
    SendPrivateMessageResult output = SendPrivateMessageResult.UNKNOWN_ERROR;
    if (!cookieMap.containsKey(JFORUMSESSIONID)) {
        if (!forumLoginAndGetCookie())
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;
    }
    try {
        // Make a connection
        URL url = new URL(FORUM_POST_PAGE_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //multipart/form-data
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        //conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

        conn.addRequestProperty(COOKIE, cookie);

        StringBuilder data = new StringBuilder();

        // set the multipart form data parameters
        addMultipartFormData(data, "action", "sendSave");
        addMultipartFormData(data, "module", "pm");
        addMultipartFormData(data, "preview", "0");
        addMultipartFormData(data, "start", null);
        if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_ID) {
            addMultipartFormData(data, "toUsername", null);
            addMultipartFormData(data, "toUserId", customer);
        } else if (customerDefinitionType == CUSTOMER_DEFINITION_TYPE_NAME) {
            addMultipartFormData(data, "toUsername", customer);
            addMultipartFormData(data, "toUserId", null);
        }
        addMultipartFormData(data, "disa1ble_html", "on");
        addMultipartFormData(data, "attach_sig", "on");
        addMultipartFormData(data, "subject", subject);
        addMultipartFormData(data, "message", message);
        addMultipartFormData(data, "addbbcode24", "#444444");
        addMultipartFormData(data, "addbbcode26", "12");
        addMultipartFormData(data, "helpbox", "Italic Text: [i]Text[/i]  (alt+i)");

        data.append(twoHyphens).append(BOUNDRY).append(twoHyphens);
        DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
        try {
            dataOS.writeBytes(data.toString());
            dataOS.flush();
        } finally {
            dataOS.close();
        }

        conn.connect();

        if (isMaintenancePage(conn))
            return SendPrivateMessageResult.UNABLE_TO_LOGIN;

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            throw new Exception(String.format("Received the response code %d from the URL %s : %s",
                    responseCode, url, conn.getResponseMessage()));
        }

        String response = getResponseText(conn);
        //            System.out.println(response);

        if (response.contains("Your message was successfully sent.")) {
            output = SendPrivateMessageResult.SUCCESS;
        } else if (response.contains(
                "Could not determine the user id. Please check if you typed the username correctly and try again.")) {
            output = SendPrivateMessageResult.USER_NOT_FOUND;
        } else if (response.contains(
                "Sorry, but this users inbox is currently full and cannot receive private messages at this time.")) {
            output = SendPrivateMessageResult.MAILBOX_FULL;
        }

        conn.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return output;
}

From source file:be.ibridge.kettle.trans.step.sortrows.SortRows.java

private boolean addBuffer(Row r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*from w  w  w.  j  a  v  a  2  s  . com*/
    if (data.files.size() == 0 && r == null) // No more records: sort buffer
    {
        quickSort(data.buffer);
    }

    // time to write to disk: buffer is full!
    if (data.buffer.size() == meta.getSortSize() // Buffer is full: sort & dump to disk 
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk 
    ) {
        // First sort the rows in buffer[]
        quickSort(data.buffer);

        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    StringUtil.environmentSubstitute(meta.getDirectory()));

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = fileObject.getContent().getOutputStream();
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                if (p == 0) {
                    // Save the metadata, keep it in memory
                    data.rowMeta.add(new Row(((Row) data.buffer.get(p))));
                }
                // Just write the data, nothing else
                ((Row) data.buffer.get(p)).writeData(dos);
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing temp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}