List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:com.netease.qa.emmagee.service.EmmageeService.java
public void getlog() { new Thread(new Runnable() { @Override//from ww w. j a v a 2s. c o m public void run() { try { Process process = null; DataOutputStream os = null; String logcatCommand; if (packageName.contains("elong")) { logcatCommand = "logcat -v time |grep --line-buffered -E \"GreenDaoHelper_insert_e|Displayed\" | grep -v -E \"show|logs|back|info\""; } else { logcatCommand = "logcat -v time |grep --line-buffered -E \"Displayed\""; } Runtime.getRuntime().exec("logcat -c"); process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); os.write(logcatCommand.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); bufferedWriter = new BufferedWriter(new FileWriter(new File("/sdcard/logcat.log"))); String line = null; while (!isServiceStop) { while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line + Constants.LINE_END); } try { Thread.currentThread().sleep(Settings.SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } os.close(); bufferedWriter.flush(); bufferedReader.close(); process.destroy(); } catch (IOException e) { e.printStackTrace(); } finally { } } }).start(); }
From source file:com.p2p.misc.DeviceUtility.java
private void WriteData(OutputStream out, int cid, int lac) throws IOException { DataOutputStream dataOutputStream = new DataOutputStream(out); dataOutputStream.writeShort(21);/* w w w. j a v a 2s. c o m*/ dataOutputStream.writeLong(0); dataOutputStream.writeUTF("en"); dataOutputStream.writeUTF("Android"); dataOutputStream.writeUTF("1.0"); dataOutputStream.writeUTF("Mobile"); dataOutputStream.writeByte(27); dataOutputStream.writeInt(0); dataOutputStream.writeInt(0); dataOutputStream.writeInt(3); dataOutputStream.writeUTF(""); dataOutputStream.writeInt(cid); dataOutputStream.writeInt(lac); dataOutputStream.writeInt(0); dataOutputStream.writeInt(0); dataOutputStream.writeInt(0); dataOutputStream.writeInt(0); dataOutputStream.flush(); }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Starts collecting kernel log/*from ww w .j ava 2 s . c o m*/ * * Requires root permission. * * @param file kernel log output filename */ private void startDmesg(String file) { Process sh = null; DataOutputStream os = null; try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); // Appending String Command = "cat /proc/kmsg >> " + mApp.getTcpDumpTraceFolderName() + file + "\n"; os.writeBytes(Command); os.flush(); } catch (IOException e) { Log.e(TAG, "exception in startDmesg ", e); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "exception in startDmesg closing output stream ", e); } } }
From source file:com.orange.labs.sdk.RestUtils.java
public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers, final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress, final OrangeListener.Error failure) { // open a URL connection to the Server FileInputStream fileInputStream = null; try {// www . j av a2 s .c o m fileInputStream = new FileInputStream(file); // Open a HTTP connection to the URL HttpURLConnection conn = (HttpsURLConnection) url.openConnection(); // Allow Inputs & Outputs conn.setDoInput(true); conn.setDoOutput(true); // Don't use a Cached Copy conn.setUseCaches(false); conn.setRequestMethod("POST"); // // Define headers // // Create an unique boundary String boundary = "UploadBoundary"; conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); for (String key : headers.keySet()) { conn.setRequestProperty(key.toString(), headers.get(key)); } // // Write body part // DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); int bytesAvailable = fileInputStream.available(); String marker = "\r\n--" + boundary + "\r\n"; dos.writeBytes(marker); dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n"); // Create JSonObject : JSONObject params = new JSONObject(); params.put("name", file.getName()); params.put("size", String.valueOf(bytesAvailable)); params.put("folder", folderIdentifier); dos.writeBytes(params.toString()); dos.writeBytes(marker); dos.writeBytes( "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n"); dos.writeBytes("Content-Type: image/jpeg\r\n\r\n"); int progressValue = 0; int bytesRead = 0; byte buf[] = new byte[1024]; BufferedInputStream bufInput = new BufferedInputStream(fileInputStream); while ((bytesRead = bufInput.read(buf)) != -1) { // write output dos.write(buf, 0, bytesRead); dos.flush(); progressValue += bytesRead; // update progress bar progress.onProgress((float) progressValue / bytesAvailable); } dos.writeBytes(marker); // // Responses from the server (code and message) // int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // close streams fileInputStream.close(); dos.flush(); dos.close(); if (serverResponseCode == 200 || serverResponseCode == 201) { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = rd.readLine()) != null) { Log.i("FileUpload", "Response: " + line); response += line; } rd.close(); JSONObject object = new JSONObject(response); success.onResponse(object); } else { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String response = ""; String line; while ((line = rd.readLine()) != null) { Log.i("FileUpload", "Error: " + line); response += line; } rd.close(); JSONObject errorResponse = new JSONObject(response); failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.intel.xdk.device.Device.java
public void getRemoteDataExt(JSONObject obj) { String requestUrl;//w w w . ja v a2s . c o m 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.pdx.cecs.orcycle.NoteUploader.java
boolean uploadOneNote(long noteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {//from w w w .j ava 2 s.com JSONArray jsonNoteResponses = getNoteResponsesJSON(noteId); 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"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonNote; if (null != (jsonNote = getNoteJSON(noteId))) { try { String deviceId = userId; dos.writeBytes(notesep + ContentField("note") + jsonNote.toString() + "\r\n"); dos.writeBytes( notesep + ContentField("version") + String.valueOf(kSaveNoteProtocolVersion) + "\r\n"); dos.writeBytes(notesep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(notesep + ContentField("noteResponses") + jsonNoteResponses.toString() + "\r\n"); if (null != imageData) { dos.writeBytes(notesep + "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(notesep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { mDb.open(); mDb.updateNoteStatus(noteId, NoteData.STATUS_SENT); mDb.close(); result = true; } } else { result = false; } } catch (IllegalStateException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (IOException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } catch (JSONException ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { NoteUploader.setPending(noteId, false); } return result; }
From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java
private void writeFileCTimes(final DataOutput header) throws IOException { int numCreationDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { ++numCreationDates;// w ww .j a va 2 s. c o m } } if (numCreationDates > 0) { header.write(NID.kCTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numCreationDates != files.size()) { out.write(0); final BitSet cTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { cTimes.set(i, files.get(i).getHasCreationDate()); } writeBits(out, cTimes, files.size()); } else { out.write(1); // "allAreDefined" == true } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { out.writeLong( Long.reverseBytes(SevenZArchiveEntry.javaTimeToNtfsTime(entry.getCreationDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } }
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; }//from w ww. j a va 2 s.c om 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:edu.auburn.ppl.cyclecolumbus.NoteUploader.java
/****************************************************************************************** * Uploads the note to the server//ww w .j ava 2 s . c o m ****************************************************************************************** * @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:bobs.is.compress.sevenzip.SevenZOutputFile.java
private void writeFileMTimes(final DataOutput header) throws IOException { int numLastModifiedDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { ++numLastModifiedDates;//from w ww. jav a2s . co m } } if (numLastModifiedDates > 0) { header.write(NID.kMTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numLastModifiedDates != files.size()) { out.write(0); final BitSet mTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { mTimes.set(i, files.get(i).getHasLastModifiedDate()); } writeBits(out, mTimes, files.size()); } else { out.write(1); // "allAreDefined" == true } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { out.writeLong( Long.reverseBytes(SevenZArchiveEntry.javaTimeToNtfsTime(entry.getLastModifiedDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } }