List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:edu.slu.action.ObjectAction.java
public static String getAccessTokenWithAuth(String auth_code) throws UnsupportedEncodingException { System.out.println("Getting an access token"); String token = ""; int rcode = 0; String tokenURL = "https://cubap.auth0.com/oauth/token"; JSONObject body = new JSONObject(); //body.element("grant_type", "authorization_code"); body.element("grant_type", "client_credentials"); body.element("client_id", getRerumProperty("clientID")); body.element("client_secret", getRerumProperty("rerumSecret")); body.element("audience", "http://rerum.io/api"); //body.element("code", auth_code); body.element("redirect_uri", Constant.RERUM_BASE); //System.out.println("I will be using this body: "); //System.out.println(body); try {/*from ww w .j a va 2 s .c o m*/ URL tURL = new URL(tokenURL); HttpURLConnection connection; connection = (HttpURLConnection) tURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); rcode = connection.getResponseCode(); if (connection.getResponseCode() == 401) { //One of the values used was wrong. The secret may have expired, the clientID may be wrong, the auth_code may be wrong or the user may not be a part of the RERUM client. token = "Auth0 responded 401. Contact RERUM."; } else if (connection.getResponseCode() >= 500) { token = "Auth0 had an internal error. Try again later. " + rcode; } else if (connection.getResponseCode() == 200) { DataOutputStream jsonString = new DataOutputStream(connection.getOutputStream()); jsonString.writeBytes(body.toString()); jsonString.flush(); jsonString.close(); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder responseBlob = new StringBuilder(); String line; while ((line = input.readLine()) != null) { responseBlob.append(line); } input.close(); connection.disconnect(); JSONObject responseObj = new JSONObject(); if (responseBlob.length() > 0) { try { responseObj = JSONObject.fromObject(responseBlob.toString()); } catch (Exception e) { //response was not JSON, so let it an empty object. } } if (responseObj.containsKey("access_token")) { token = responseObj.getString("access_token"); if ("".equals(token)) { token = "Auth0 did not respond with a token."; } } else { token = "Auth0 did not respond with a token. "; } } else { token = "There was an issue contacting Auth0. " + rcode + ". Contact RERUM."; } } catch (ProtocolException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } return token; }
From source file:com.cypress.cysmart.RDKEmulatorView.MicrophoneEmulatorFragment.java
private void createWavFile(File fileToConvert, String wavFilePath) { try {// w w w. j a v a 2s .c om long mySubChunk1Size = 16; int myBitsPerSample = 16; int myFormat = 1; long myChannels = 1; long mySampleRate = 16000; long myByteRate = mySampleRate * myChannels * myBitsPerSample / 8; int myBlockAlign = (int) (myChannels * myBitsPerSample / 8); byte[] clipData = getBytesFromFile(fileToConvert); long myDataSize = clipData.length; long myChunk2Size = myDataSize * myChannels * myBitsPerSample / 8; long myChunkSize = 36 + myChunk2Size; OutputStream os; os = new FileOutputStream(new File(wavFilePath)); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream outFile = new DataOutputStream(bos); outFile.writeBytes("RIFF"); // 00 - RIFF outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file? outFile.writeBytes("WAVE"); // 08 - WAVE outFile.writeBytes("fmt "); // 12 - fmt outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???) outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second) outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 outFile.writeBytes("data"); // 36 - data outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers outFile.flush(); outFile.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Starts the video capture of the device desktop by reading frame buffer * using ffmpeg command/*from w w w .j av a 2s . c o m*/ */ private void startScreenVideoCapture() { Process sh = null; DataOutputStream os = null; try { if (DEBUG) { Log.e(TAG, "Starting Video Capture"); } sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String Command = "cd " + ARODataCollector.INTERNAL_DATA_PATH + " \n"; os.writeBytes(Command); Command = "chmod 777 ffmpeg \n"; os.writeBytes(Command); Command = "./ffmpeg -f fbdev -vsync 2 -r 3 -i /dev/graphics/fb0 /sdcard/ARO/" + TRACE_FOLDERNAME + "/video.mp4 2> /data/ffmpegout.txt \n"; os.writeBytes(Command); Command = "exit\n"; os.writeBytes(Command); os.flush(); sh.waitFor(); } catch (IOException e) { Log.e(TAG, "exception in startScreenVideoCapture", e); } catch (InterruptedException e) { Log.e(TAG, "exception in startScreenVideoCapture", e); } finally { try { if (DEBUG) { Log.e(TAG, "Stopped Video Capture in startScreenVideoCapture"); } os.close(); // Reading start time of Video from ffmpegout file mApp.readffmpegStartTimefromFile(); } catch (IOException e) { Log.e(TAG, "IOException in reading video start time", e); } catch (NumberFormatException e) { Log.e(TAG, "NumberFormatException in reading video start time", e); } try { // Recording start time of video mApp.writeVideoTraceTime(Double.toString(mApp.getAROVideoCaptureStartTime())); mApp.closeVideoTraceTimeFile(); } catch (IOException e) { Log.e(TAG, "IOException in writing video start time", e); } if (mApp.getTcpDumpStartFlag() && !mApp.getARODataCollectorStopFlag()) { mApp.setVideoCaptureFailed(true); } try { mApp.setAROVideoCaptureRunningFlag(false); sh.destroy(); } catch (Exception e) { Log.e(TAG, "Failed to destroy shell during Video Capture termination"); } } }
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; }// w ww.j av a 2 s .c om 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=\"" + 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(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:com.appcelerator.titanium.desktop.ui.wizard.Packager.java
private IStatus invokeCloudService(URL baseURL, Map<String, String> data, String type) { DataOutputStream outputStream = null; try {//w w w . ja v a 2 s . c o m if (type == null) { type = "POST"; //$NON-NLS-1$ } if (data == null) { data = new HashMap<String, String>(); } // always pass MID data.put("mid", TitaniumCorePlugin.getMID()); //$NON-NLS-1$ ITitaniumUser user = TitaniumCorePlugin.getDefault().getUserManager().getSignedInUser(); data.put("sid", user.getSessionID()); //$NON-NLS-1$ data.put("token", user.getToken()); //$NON-NLS-1$ data.put("uid", user.getUID()); //$NON-NLS-1$ data.put("uidt", user.getUIDT()); //$NON-NLS-1$ // If this is not a POST, append query params don't put as data in body! if (!"POST".equals(type)) //$NON-NLS-1$ { baseURL = makeURL(baseURL.toString(), data); } HttpURLConnection con = (HttpURLConnection) baseURL.openConnection(); con.setUseCaches(false); con.setRequestMethod(type); con.setRequestProperty("User-Agent", TitaniumConstants.USER_AGENT); //$NON-NLS-1$ if ("POST".equals(type)) //$NON-NLS-1$ { con.setDoOutput(true); // Write the data to the connection outputStream = new DataOutputStream(con.getOutputStream()); outputStream.writeBytes(getQueryString(data)); outputStream.flush(); } IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Request: {0}", baseURL), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); // Force to finish, grab response code int code = con.getResponseCode(); // If the http code is 200 from POST, parse response as JSON. Else display error if (code == 200) { String responseText = IOUtil.read(con.getInputStream()); IdeLog.logInfo(DesktopPlugin.getDefault(), MessageFormat.format("API Response: {0}:{1}", code, responseText), //$NON-NLS-1$ com.appcelerator.titanium.core.IDebugScopes.API); return new Status(IStatus.OK, DesktopPlugin.PLUGIN_ID, code, responseText, null); } // TODO Read from connection to populate message! return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, code, null, null); } catch (Exception e) { return new Status(IStatus.ERROR, DesktopPlugin.PLUGIN_ID, 0, e.getMessage(), e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // ignores the exception } } } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops collecting kernel log//w w w . j a va 2 s. c o m * * Requires root permission. * * pre: there is only one "cat" process running */ private void stopDmesg() { Process sh = null; DataOutputStream os = null; int pid = 0; try { pid = mAroUtils.getProcessID("cat"); } catch (IOException e1) { Log.e(TAG, "IOException in stopDmesg", e1); } catch (IndexOutOfBoundsException e1) { Log.e(TAG, "IndexOutOfBoundsException in stopDmesg", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopDmesg", e1); } if (DEBUG) { Log.d(TAG, "stopDmesg=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); final String Command = "kill -15 " + pid + "\n"; os.writeBytes(Command); os.flush(); sh.waitFor(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopDmesg", e); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "exception in stopDmesg DataOutputStream close", e); } if (DEBUG) { Log.d(TAG, "Stopped stopDmesg"); } sh.destroy(); } } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * issue the kill -9 command if ffmpeg couldn't be stopped with kill -15 */// w ww . ja va 2s . co m private void kill9Ffmpeg() { Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { //have a 1 sec delay since it takes some time for the kill -15 to end ffmpeg Thread.sleep(1000); pid = mAroUtils.getProcessID("ffmpeg"); if (pid != 0) { //ffmpeg still running if (DEBUG) { Log.i(TAG, "ffmpeg still running after kill -15. Will issue kill -9 " + pid); } sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String Command = "kill -9 " + pid + "\n"; os.writeBytes(Command); Command = "exit\n"; os.writeBytes(Command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } else { Log.e(TAG, "could not kill ffmpeg in kill9Ffmpeg, exitValue=" + exitValue); } } else { mVideoRecording = false; if (DEBUG) { Log.i(TAG, "ffmpeg had been ended successfully by kill -15"); } } } catch (Exception e1) { Log.e(TAG, "exception in kill9Ffmpeg", e1); } finally { try { if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in kill9Ffmpeg DataOutputStream close", e); } } }
From source file:my.swingconnect.SwingConnectUI.java
public int uploadFile(String User, String Pass) { int set = 0;/* w w w . ja v a2 s. c om*/ String upLoadServerUri = null; upLoadServerUri = "http://photo-drop.com/clientlogin.php"; final String USER_AGENT = "Mozilla/5.0"; 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; if (User.isEmpty() && Pass.isEmpty()) { System.out.println("Please enter the valid User and Pass :"); return set; } else { try { //String upLoadServerUri = null; int serverResponseCode = 0; URL url = new URL(upLoadServerUri); //Passing the server complete URL // Open a HTTP connection to the URL 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("User-Agent", USER_AGENT); conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //conn.setRequestProperty("Cookie", "Username=Mavericks;"); String urlParameters = "Username=" + User + "&Password=" + Pass + "&submit=Login"; dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(urlParameters); dos.flush(); dos.close(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); System.out.println("HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { System.out.println("Posted success"); set = 1; } else if (serverResponseCode == 401) { System.out.println("Invalid Login"); } else { System.out.println("Error check"); } } catch (MalformedURLException ex) { ex.printStackTrace(); System.out.println("Error"); } catch (Exception e) { e.printStackTrace(); System.out.println("Error"); } return set; } }
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the Screen video capture/*from w w w . java 2 s. c o m*/ */ private void stopScreenVideoCapture() { Log.i(TAG, "enter stopScreenVideoCapture at " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { pid = mAroUtils.getProcessID("ffmpeg"); } catch (IOException e1) { Log.e(TAG, "IOException in stopScreenVideoCapture", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopScreenVideoCapture", e1); } if (DEBUG) { Log.i(TAG, "stopScreenVideoCapture=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String command = "kill -15 " + pid + "\n"; os.writeBytes(command); command = "exit\n"; os.writeBytes(command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } if (DEBUG) { Log.i(TAG, "successfully returned from kill -15; exitValue= " + exitValue); } } catch (IOException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } finally { try { kill9Ffmpeg(); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in stopScreenVideoCapture finally block", e); } if (DEBUG) { Log.i(TAG, "Stopped Video Capture in stopScreenVideoCapture()"); } } } if (DEBUG) { Log.i(TAG, "exit stopScreenVideoCapture"); } }
From source file:org.motechproject.mobile.web.OXDFormDownloadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @RequestMapping(method = RequestMethod.POST) public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get our raw input and output streams InputStream input = request.getInputStream(); OutputStream output = response.getOutputStream(); // Wrap the streams for compression ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION); // Wrap the streams so we can use logical types DataInputStream dataInput = new DataInputStream(input); DataOutputStream dataOutput = new DataOutputStream(zOutput); try { // Read the common submission data from mobile phone String name = dataInput.readUTF(); String password = dataInput.readUTF(); String serializer = dataInput.readUTF(); String locale = dataInput.readUTF(); byte action = dataInput.readByte(); // TODO: add authentication, possible M6 enhancement log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer + ", locale=" + locale + ", action=" + action); EpihandyXformSerializer serObj = new EpihandyXformSerializer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Perform the action specified by the mobile phone try { if (action == ACTION_DOWNLOAD_STUDY_LIST) { serObj.serializeStudies(baos, studyService.getStudies()); } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) { serObj.serializeUsers(baos, userService.getUsers()); int studyId = dataInput.readInt(); String studyName = studyService.getStudyName(studyId); List<String> studyForms = formService.getStudyForms(studyId); serObj.serializeForms(baos, studyForms, studyId, studyName); } } catch (Exception e) { dataOutput.writeByte(RESPONSE_ERROR); throw new ServletException("failed to serialize data", e); } // Write out successful upload response dataOutput.writeByte(RESPONSE_SUCCESS); dataOutput.write(baos.toByteArray()); response.setStatus(HttpServletResponse.SC_OK); } finally { // Should always do this dataOutput.flush(); zOutput.finish(); response.flushBuffer(); } }