List of usage examples for java.io DataOutputStream write
public synchronized void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to the underlying output stream. From source file:com.androidex.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { ProgressListener progressListener = null; if (request instanceof ProgressListener) { progressListener = (ProgressListener) request; }//from ww w .java 2s . c o m connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (progressListener != null) { int transferredBytes = 0; int totalSize = body.length; int offset = 0; int chunkSize = Math.min(2048, Math.max(totalSize - offset, 0)); while (chunkSize > 0 && offset + chunkSize <= totalSize) { out.write(body, offset, chunkSize); transferredBytes += chunkSize; progressListener.onProgress(transferredBytes, totalSize); offset += chunkSize; chunkSize = Math.min(chunkSize, Math.max(totalSize - offset, 0)); } } else { out.write(body); } out.close(); } }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?url/*from w ww.j ava 2 s.co m*/ * * @param inputStream ? * @param fileName ?? * @param fileType * @param contentType * @param identity * @return */ public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName, String fileType, String contentType, String identity) { String lineEnd = System.getProperty("line.separator"); String twoHyphens = "--"; String boundary = "*****"; String result = null; try { //? URL submit = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) submit.openConnection(); // conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); //? conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", DEFAULT_CHARSET); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //?? DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + ";Content-Type=\"" + contentType + lineEnd); dos.writeBytes(lineEnd); byte[] buffer = new byte[8192]; // 8k int count = 0; while ((count = inputStream.read(buffer)) != -1) { dos.write(buffer, 0, count); } inputStream.close(); //? dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET); BufferedReader br = new BufferedReader(isr); result = br.readLine(); dos.close(); is.close(); } catch (IOException e) { logger.error("", e); } return result; }
From source file:org.alfresco.webservice.util.ContentUtils.java
/** * Streams content into the repository. Once done a content details string is returned and this can be used to update * a content property in a CML statement. * //www. jav a 2s.c o m * @param file the file to stream into the repository * @param host the host name of the destination repository * @param port the port name of the destination repository * @param webAppName the name of the target web application (default 'alfresco') * @param mimetype the mimetype of the file, ignored if null * @param encoding the encoding of the file, ignored if null * @return the content data that can be used to set the content property in a CML statement */ @SuppressWarnings("deprecation") public static String putContent(File file, String host, int port, String webAppName, String mimetype, String encoding) { String result = null; try { String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket=" + AuthenticationUtils.getTicket(); if (mimetype != null) { url = url + "&mimetype=" + mimetype; } if (encoding != null) { url += "&encoding=" + encoding; } String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID=" + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: " + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n" + "\n"; // Open sockets and streams Socket socket = new Socket(host, port); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); DataInputStream is = new DataInputStream(socket.getInputStream()); try { if (socket != null && os != null && is != null) { // Write the request header os.writeBytes(request); // Stream the content onto the server InputStream fileInputStream = new FileInputStream(file); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); byteCount += bytesRead; } os.flush(); fileInputStream.close(); // Read the response and deal with any errors that might occur boolean firstLine = true; String responseLine; while ((responseLine = is.readLine()) != null) { if (firstLine == true) { if (responseLine.contains("200") == true) { firstLine = false; } else if (responseLine.contains("401") == true) { throw new RuntimeException( "Content could not be uploaded because invalid credentials have been supplied."); } else if (responseLine.contains("403") == true) { throw new RuntimeException( "Content could not be uploaded because user does not have sufficient privileges."); } else { throw new RuntimeException( "Error returned from upload servlet (" + responseLine + ")"); } } else if (responseLine.contains("contentUrl") == true) { result = responseLine; break; } } } } finally { try { // Close the streams and socket if (os != null) { os.close(); } if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (Exception e) { throw new RuntimeException("Error closing sockets and streams", e); } } } catch (Exception e) { throw new RuntimeException("Error writing content to repository server", e); } return result; }
From source file:com.facebook.infrastructure.db.CommitLogEntry.java
public void serialize(CommitLogEntry logEntry, DataOutputStream dos) throws IOException { int length = logEntry.length(); dos.writeInt(length);//from w ww. j av a 2 s .com dos.write(logEntry.value(), 0, length); }
From source file:org.apache.sqoop.integration.server.InvalidRESTCallsTest.java
@Test public void test() throws Exception { LOG.info("Start: " + getTestName()); URL url = new URL(getServerUrl() + desc.rest); HttpURLConnection connection = new DelegationTokenAuthenticatedURL().openConnection(url, new DelegationTokenAuthenticatedURL.Token()); connection.setRequestMethod(desc.method); if (desc.data != null) { connection.setDoOutput(true);//from ww w .j a v a 2 s . c o m byte[] byteData = desc.data.getBytes(Charset.forName("UTF-8")); connection.setRequestProperty("Content-Length", Integer.toString(byteData.length)); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(byteData, byteData.length, 0); wr.flush(); wr.close(); } desc.validator.setConnection(connection); LOG.info("error = " + desc.validator.error); LOG.info("input = " + desc.validator.input); desc.validator.validate(); }
From source file:org.apache.hadoop.tools.mapred.lib.TestDynamicInputFormatByChunk.java
private static void touchFile(String path, long totalFileSize, boolean preserveBlockSize, Options.ChecksumOpt checksumOpt) throws Exception { FileSystem fs;/* w ww .jav a2 s. co m*/ DataOutputStream outputStream = null; try { fs = cluster.getFileSystem(); final Path qualifiedPath = new Path(path).makeQualified(fs.getUri(), fs.getWorkingDirectory()); final long blockSize = preserveBlockSize ? NON_DEFAULT_BLOCK_SIZE : fs.getDefaultBlockSize(qualifiedPath) * 2; FsPermission permission = FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(fs.getConf())); outputStream = fs.create(qualifiedPath, permission, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), 0, (short) (fs.getDefaultReplication(qualifiedPath) * 2), blockSize, null, checksumOpt); byte[] bytes = new byte[DEFAULT_FILE_SIZE]; long curFileSize = 0; int bufferLen = DEFAULT_FILE_SIZE; while (curFileSize < totalFileSize) { if (totalFileSize - curFileSize < DEFAULT_FILE_SIZE) bufferLen = (int) (totalFileSize - curFileSize); outputStream.write(bytes, 0, bufferLen); outputStream.flush(); curFileSize += bufferLen; } FileStatus fileStatus = fs.getFileStatus(qualifiedPath); System.out.println(fileStatus.getBlockSize()); System.out.println(fileStatus.getReplication()); } finally { IOUtils.cleanup(null, outputStream); } }
From source file:org.apache.sqoop.integration.server.rest.RestTest.java
@Test public void test() throws Exception { LOG.info("Start: " + getTestName()); URL url = new URL(getSqoopServerUrl() + desc.rest); HttpURLConnection connection = new DelegationTokenAuthenticatedURL().openConnection(url, new DelegationTokenAuthenticatedURL.Token()); connection.setRequestMethod(desc.method); if (desc.data != null) { connection.setDoOutput(true);/*from w w w . jav a 2 s .c o m*/ byte[] byteData = desc.data.getBytes(Charset.forName("UTF-8")); connection.setRequestProperty("Content-Length", Integer.toString(byteData.length)); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(byteData, 0, byteData.length); wr.flush(); wr.close(); } desc.validator.setConnection(connection); LOG.info("error = " + desc.validator.error); LOG.info("input = " + desc.validator.input); desc.validator.validate(); LOG.info("End: " + getTestName()); }
From source file:com.symbian.driver.remoting.master.TestResultSet.java
/** * Purpose : To write the byte contents of zip file to file Input : Absolute * path of file/*ww w .jav a 2s .co m*/ * * @param aFileName * String : afile path. * @throws IOException */ public void ExtractToFile(String aFileName) throws IOException { // Create stream to file FileOutputStream lFos = new FileOutputStream(aFileName); DataOutputStream lDos = new DataOutputStream(lFos); // Read contents into byte array lDos.write(contents, 0, numberOfBytes.intValue()); // Close the stream lFos.close(); }
From source file:org.apache.hadoop.hbase.util.TestCompressionTest.java
/** * Verify CompressionTest.testCompression() on a native codec. *///from w w w.jav a2 s . c o m private void nativeCodecTest(String codecName, String libName, String codecClassName) { if (isCompressionAvailable(codecClassName)) { try { if (libName != null) { System.loadLibrary(libName); } try { Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils .newInstance(conf.getClassByName(codecClassName), conf); DataOutputBuffer compressedDataBuffer = new DataOutputBuffer(); CompressionOutputStream deflateFilter = codec.createOutputStream(compressedDataBuffer); byte[] data = new byte[1024]; DataOutputStream deflateOut = new DataOutputStream(new BufferedOutputStream(deflateFilter)); deflateOut.write(data, 0, data.length); deflateOut.flush(); deflateFilter.finish(); // Codec class, codec nativelib and Hadoop nativelib with codec JNIs are present assertTrue(CompressionTest.testCompression(codecName)); } catch (UnsatisfiedLinkError e) { // Hadoop nativelib does not have codec JNIs. // cannot assert the codec here because the current logic of // CompressionTest checks only classloading, not the codec // usage. LOG.debug("No JNI for codec '" + codecName + "' " + e.getMessage()); } catch (Exception e) { LOG.error(codecName, e); } } catch (UnsatisfiedLinkError e) { // nativelib is not available LOG.debug("Native lib not available: " + codecName); assertFalse(CompressionTest.testCompression(codecName)); } } else { // Compression Codec class is not available LOG.debug("Codec class not available: " + codecName); assertFalse(CompressionTest.testCompression(codecName)); } }
From source file:im.vector.util.BugReporter.java
/** * Send a bug report.//from ww w . java2 s.c o m * * @param context the application context * @param withDevicesLogs true to include the device logs * @param withCrashLogs true to include the crash logs */ private static void sendBugReport(final Context context, final boolean withDevicesLogs, final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) { new AsyncTask<Void, Integer, String>() { @Override protected String doInBackground(Void... voids) { File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report"); if (bugReportFile.exists()) { bugReportFile.delete(); } String serverError = null; FileWriter fileWriter = null; try { fileWriter = new FileWriter(bugReportFile); JsonWriter jsonWriter = new JsonWriter(fileWriter); jsonWriter.beginObject(); // android bug report jsonWriter.name("user_agent").value("Android"); // logs list jsonWriter.name("logs"); jsonWriter.beginArray(); // the logs are optional if (withDevicesLogs) { List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>()); for (File f : files) { if (!mIsCancelled) { jsonWriter.beginObject(); jsonWriter.name("lines").value(convertStreamToString(f)); jsonWriter.endObject(); jsonWriter.flush(); } } } if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) { jsonWriter.beginObject(); jsonWriter.name("lines").value(getLogCatError()); jsonWriter.endObject(); jsonWriter.flush(); } jsonWriter.endArray(); jsonWriter.name("text").value(bugDescription); String version = ""; if (null != Matrix.getInstance(context).getDefaultSession()) { version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n"; } version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " " + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n"; version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n"; version += "SDK version: " + Matrix.getInstance(context).getDefaultSession().getVersion(true) + "\n"; version += "Olm version: " + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true) + "\n"; jsonWriter.name("version").value(version); jsonWriter.endObject(); jsonWriter.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage()); serverError = e.getLocalizedMessage(); } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage()); serverError = oom.getMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out of memory"; } } try { if (null != fileWriter) { fileWriter.close(); } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage()); } if (TextUtils.isEmpty(serverError) && !mIsCancelled) { // the screenshot is defined here // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg"); InputStream inputStream = null; HttpURLConnection conn = null; try { inputStream = new FileInputStream(bugReportFile); final int dataLen = inputStream.available(); // should never happen if (0 == dataLen) { return "No data"; } URL url = new URL(context.getResources().getString(R.string.bug_report_url)); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", Integer.toString(dataLen)); // avoid caching data before really sending them. conn.setFixedLengthStreamingMode(inputStream.available()); conn.connect(); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); byte[] buffer = new byte[8192]; // read file and write it into form... int bytesRead; int totalWritten = 0; while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) { dos.write(buffer, 0, bytesRead); totalWritten += bytesRead; publishProgress(totalWritten * 100 / dataLen); } dos.flush(); dos.close(); int mResponseCode; try { // Read the SERVER RESPONSE mResponseCode = conn.getResponseCode(); } catch (EOFException eofEx) { mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR; } // if the upload failed, try to retrieve the reason if (mResponseCode != HttpURLConnection.HTTP_OK) { serverError = null; InputStream is = conn.getErrorStream(); if (null != is) { int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } serverError = b.toString(); is.close(); // check if the error message try { JSONObject responseJSON = new JSONObject(serverError); serverError = responseJSON.getString("error"); } catch (JSONException e) { Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage()); } // should never happen if (null == serverError) { serverError = "Failed with error " + mResponseCode; } is.close(); } } } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage()); serverError = e.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Failed to upload"; } } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage()); serverError = oom.getLocalizedMessage(); if (TextUtils.isEmpty(serverError)) { serverError = "Out ouf memory"; } } finally { try { if (null != conn) { conn.disconnect(); } } catch (Exception e2) { Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage()); } } if (null != inputStream) { try { inputStream.close(); } catch (Exception e) { Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage()); } } } return serverError; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); if (null != listener) { try { listener.onProgress((null == progress) ? 0 : progress[0]); } catch (Exception e) { Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage()); } } } @Override protected void onPostExecute(String reason) { if (null != listener) { try { if (mIsCancelled) { listener.onUploadCancelled(); } else if (null == reason) { listener.onUploadSucceed(); } else { listener.onUploadFailed(reason); } } catch (Exception e) { Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage()); } } } }.execute(); }