List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
protected static void assembleMultipart(DataOutputStream out, Map<String, String> vars, String fileKey, String fileName, InputStream istream) throws IOException { for (String key : vars.keySet()) { out.writeBytes("--" + BOUNDARY + CRLF); out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF); out.writeBytes(CRLF);//from w ww. j a v a 2 s. c o m out.writeBytes(vars.get(key) + CRLF); } out.writeBytes("--" + BOUNDARY + CRLF); out.writeBytes( "Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + fileName + "\"" + CRLF); out.writeBytes("Content-Type: application/octet-stream" + CRLF); out.writeBytes(CRLF); // write stream //http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html int maxBufferSize = 1024; int bytesAvailable = istream.available(); int bufferSize = Math.min(maxBufferSize, bytesAvailable); byte[] buffer = new byte[bufferSize]; int bytesRead = istream.read(buffer, 0, bufferSize); while (bytesRead > 0) { out.write(buffer, 0, bufferSize); out.flush(); bytesAvailable = istream.available(); bufferSize = Math.min(maxBufferSize, bytesAvailable); bytesRead = istream.read(buffer, 0, bufferSize); } out.writeBytes(CRLF); out.writeBytes("--" + BOUNDARY + "--" + CRLF); out.writeBytes(CRLF); }
From source file:com.elit2.app.control.FileUpload.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {//from w w w .j a v a2 s .c om FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); InputStream is = item.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b); response.getWriter().println(fieldName + ":" + value + "<br/>"); } else { String path = getServletContext().getRealPath("/"); if (com.elit2.app.model.FileUpload.proccessFile(path, item)) { response.getWriter().print("Deu certo"); } else { response.getWriter().print("Deu errado"); } } } } catch (FileUploadException ex) { ex.printStackTrace(); } } }
From source file:com.uwsoft.editor.data.manager.DataManager.java
public static String getMyDocumentsLocation() { String myDocuments = null;//from w w w. j a v a2 s . c o m try { if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) { myDocuments = System.getProperty("user.home") + File.separator + "Documents"; } if (SystemUtils.IS_OS_WINDOWS) { Process p = Runtime.getRuntime().exec( "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); p.waitFor(); InputStream in = p.getInputStream(); byte[] b = new byte[in.available()]; in.read(b); in.close(); myDocuments = new String(b); myDocuments = myDocuments.split("\\s\\s+")[4]; } if (SystemUtils.IS_OS_LINUX) { myDocuments = System.getProperty("user.home") + File.separator + "Documents"; } } catch (Throwable t) { t.printStackTrace(); } return myDocuments; }
From source file:im.vector.util.BugReporter.java
/** * Send a bug report.//from w w w .j av a 2s . co 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(); }
From source file:com.anrisoftware.sscontrol.scripts.versionlimits.ReadVersion.java
/** * Reads the version./*from w w w .j a va 2 s . c o m*/ * * @return the {@link Version} or {@code null}. * * @throws IOException * if there was an error reading the version file. * * @throws ParseException * if there was an error parsing the version file. */ public Version readVersion() throws IOException, ParseException { InputStream stream = versionResource.toURL().openStream(); if (stream.available() > 0) { List<String> lines = readLines(stream, charset); if (lines.size() > 0) { return versionFormatFactory.create().parse(lines.get(0)); } else { return null; } } else { return null; } }
From source file:org.busko.routemanager.web.RoutePlotterController.java
@RequestMapping(method = RequestMethod.GET) public ResponseEntity<byte[]> handheldApk(Model uiModel, HttpServletRequest httpServletRequest) throws Exception { InputStream input = getClass().getClassLoader().getResourceAsStream("BuskoPlotter.apk"); int fileSize = input.available(); byte[] bytes = new byte[fileSize]; input.read(bytes);// w ww . ja v a 2 s . c o m input.close(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-Disposition", "attachment;filename=BuskoPlotter.apk"); responseHeaders.set("Content-Length", Integer.toString(fileSize)); responseHeaders.set("Content-Type", "application/vnd.android.package-archive"); return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK); }
From source file:org.jasig.cas.util.PrivateKeyFactoryBean.java
protected Object createInstance() throws Exception { final InputStream privKey = this.location.getInputStream(); try {/*from ww w . j av a 2 s.co m*/ final byte[] bytes = new byte[privKey.available()]; privKey.read(bytes); privKey.close(); final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(this.algorithm); return factory.generatePrivate(privSpec); } finally { privKey.close(); } }
From source file:com.clican.pluto.dataprocess.engine.processes.MvelExecProcessor.java
public void setMvelExpressionInputStream(InputStream mvelExpressionInputStream) { try {//from w w w . j a v a 2 s .c o m byte[] data = new byte[mvelExpressionInputStream.available()]; mvelExpressionInputStream.read(data); mvelExpression = new String(data, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } finally { if (mvelExpressionInputStream != null) { try { mvelExpressionInputStream.close(); } catch (Exception e) { log.error("", e); } } } }
From source file:griffon.plugins.preferences.persistors.JsonPreferencesPersistor.java
@Nonnull @SuppressWarnings("unchecked") private JSONObject doRead(@Nonnull InputStream inputStream) throws IOException { if (inputStream.available() > 0) { return new JSONObject(new JSONTokener(inputStream)); }/*from w ww . j av a 2 s.c om*/ return new JSONObject(); }
From source file:cc.arduino.packages.ssh.SSH.java
private void consumeStream(byte[] buffer, InputStream in, PrintStream out) throws IOException { while (in.available() > 0) { int length = in.read(buffer, 0, buffer.length); if (length < 0) { break; }//from www. ja v a 2s. c o m if (out != null) { out.print(new String(buffer, 0, length)); } } }