List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:im.vector.util.BugReporter.java
/** * Send a bug report./*from ww w . jav a 2 s . c om*/ * * @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:buildhappy.tools.DownloadFile.java
/** * ?filepath???/*from w ww .j a va 2 s . c o m*/ */ private void saveToLocal(byte[] data, String filePath) { FileOutputStream fileOut = null; DataOutputStream dataOut = null; try { fileOut = new FileOutputStream(new File(filePath)); dataOut = new DataOutputStream(fileOut); for (int i = 0; i < data.length; i++) { dataOut.write(data[i]); } dataOut.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (dataOut != null) { try { dataOut.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.mendhak.gpslogger.senders.gdocs.GDocsHelper.java
private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null;/* w ww .j ava 2s .com*/ HttpURLConnection conn = null; String createFileUrl = "https://www.googleapis.com/drive/v2/files"; String createFilePayload = " {\n" + " \"title\": \"" + fileName + "\",\n" + " \"mimeType\": \"" + mimeType + "\",\n" + " \"parents\": [\n" + " {\n" + " \"id\": \"" + parentFolderId + "\"\n" + " }\n" + " ]\n" + " }"; try { if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(createFileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(createFilePayload); wr.flush(); wr.close(); fileId = null; String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); Utilities.LogDebug("File created with ID " + fileId); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:org.scigap.iucig.controller.ScienceDisciplineController.java
@ResponseBody @RequestMapping(value = "/updateScienceDiscipline", method = RequestMethod.POST) public void updateScienceDiscipline(@RequestBody ScienceDiscipline discipline, HttpServletRequest request) throws Exception { try {/* w w w . j a v a 2 s .co m*/ String remoteUser; if (request != null) { remoteUser = request.getRemoteUser(); } else { throw new Exception("Remote user is null"); } int primarySubDisId = 0; int secondarySubDisId = 0; int tertiarySubDisId = 0; String urlParameters = "user=" + remoteUser; if (discipline != null) { Map<String, String> primarySubDisc = discipline.getPrimarySubDisc(); if (primarySubDisc != null && !primarySubDisc.isEmpty()) { for (String key : primarySubDisc.keySet()) { if (key.equals("id")) { primarySubDisId = Integer.valueOf(primarySubDisc.get(key)); urlParameters += "&discipline1=" + primarySubDisId; } } } else { Map<String, Object> primaryDiscipline = discipline.getPrimaryDisc(); if (primaryDiscipline != null && !primaryDiscipline.isEmpty()) { Object subdisciplines = primaryDiscipline.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { primarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline1=" + primarySubDisId; } } } Map<String, String> secondarySubDisc = discipline.getSecondarySubDisc(); if (secondarySubDisc != null && !secondarySubDisc.isEmpty()) { for (String key : secondarySubDisc.keySet()) { if (key.equals("id")) { secondarySubDisId = Integer.valueOf(secondarySubDisc.get(key)); urlParameters += "&discipline2=" + secondarySubDisId; } } } else { Map<String, Object> secondaryDisc = discipline.getSecondaryDisc(); if (secondaryDisc != null && !secondaryDisc.isEmpty()) { Object subdisciplines = secondaryDisc.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { secondarySubDisId = Integer .valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline2=" + secondarySubDisId; } } } Map<String, String> tertiarySubDisc = discipline.getTertiarySubDisc(); if (tertiarySubDisc != null && !tertiarySubDisc.isEmpty()) { for (String key : tertiarySubDisc.keySet()) { if (key.equals("id")) { tertiarySubDisId = Integer.valueOf(tertiarySubDisc.get(key)); urlParameters += "&discipline3=" + tertiarySubDisId; } } } else { Map<String, Object> tertiaryDisc = discipline.getTertiaryDisc(); if (tertiaryDisc != null && !tertiaryDisc.isEmpty()) { Object subdisciplines = tertiaryDisc.get("subdisciplines"); if (subdisciplines instanceof ArrayList) { for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) { Object disc = ((ArrayList) subdisciplines).get(i); if (disc instanceof HashMap) { if (((HashMap) disc).get("name").equals("Other / Unspecified")) { tertiarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString()); } } } urlParameters += "&discipline3=" + tertiarySubDisId; } } } URL obj = new URL(SCIENCE_DISCIPLINE_URL + "discipline/"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); urlParameters += "&date=" + discipline.getDate() + "&source=cybergateway&commit=Update&cluster=" + discipline.getCluster(); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + SCIENCE_DISCIPLINE_URL); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.geotrackin.gpslogger.senders.gdocs.GDocsHelper.java
private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null;// ww w . j a v a 2s . co m String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(fileUpdateUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", GetMimeTypeFromFileName(fileName)); conn.setRequestProperty("Content-Length", String.valueOf(fileContents.length)); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); tracer.debug("File updated : " + fileId); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:com.ryan.ryanreader.cache.PersistentCookieStore.java
public synchronized byte[] toByteArray() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos); try {/*from ww w .j a v a 2 s. co m*/ dos.writeInt(cookies.size()); for (final Cookie cookie : cookies) { dos.writeUTF(cookie.getName()); dos.writeUTF(cookie.getValue()); dos.writeUTF(cookie.getDomain()); dos.writeUTF(cookie.getPath()); dos.writeBoolean(cookie.isSecure()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); }
From source file:com.geotrackin.gpslogger.senders.gdocs.GDocsHelper.java
private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null;//w w w .j a v a 2s . c o m HttpURLConnection conn = null; String createFileUrl = "https://www.googleapis.com/drive/v2/files"; String createFilePayload = " {\n" + " \"title\": \"" + fileName + "\",\n" + " \"mimeType\": \"" + mimeType + "\",\n" + " \"parents\": [\n" + " {\n" + " \"id\": \"" + parentFolderId + "\"\n" + " }\n" + " ]\n" + " }"; try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); } URL url = new URL(createFileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(createFilePayload); wr.flush(); wr.close(); fileId = null; String fileMetadata = Utilities.GetStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); tracer.debug("File created with ID " + fileId + " of type " + mimeType); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:edu.pdx.cecs.orcycle.Uploader.java
private boolean uploadOneSegment(long currentNoteId) { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from w w w. j a va2 s . c o m*/ 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"); SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId); JSONObject json = segmentData.getJSON(); String deviceId = userId; DataOutputStream stream = new DataOutputStream(conn.getOutputStream()); stream.writeBytes(makeContentField("ratesegment", json.toString())); stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion))); stream.writeBytes(makeContentField("device", deviceId)); stream.writeBytes(contentFieldPrefix); stream.flush(); stream.close(); int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { segmentData.updateSegmentStatus(SegmentData.STATUS_SENT); result = true; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.netflix.zeno.examples.BasicSerializationExample.java
public byte[] createDelta() { /// The following call informs the state engine that we have finished writing /// all of our snapshot / delta files, and we are ready to begin adding fresh /// object instances for the next cycle. stateEngine.prepareForNextCycle();//from w w w . j a v a 2s . c o m // Again, we add each of our object instances to the state engine. // This operation is still thread safe and can be called from multiple processing threads. stateEngine.add("A", getExampleA1()); stateEngine.add("A", getExampleA2Prime()); /// We must again let the state engine know that we have finished adding all of our /// objects to the state. stateEngine.prepareForWrite(); /// Create a writer, which will be responsible for creating snapshot and/or delta blobs. FastBlobWriter writer = new FastBlobWriter(stateEngine); /// Again create an output stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); try { /// This time write the delta file. writer.writeDelta(outputStream); } catch (IOException e) { /// thrown if the FastBlobWriter was unable to write to the provided stream. } finally { try { outputStream.close(); } catch (IOException ignore) { } } byte delta[] = baos.toByteArray(); return delta; }
From source file:calliope.db.CouchConnection.java
/** * PUT a json file to the database//from w ww . ja v a2 s. c om * @param db the database name * @param docID the docID of the resource * @param json the json to put there * @return the server response */ @Override public String putToDb(String db, String docID, String json) throws AeseException { HttpURLConnection conn = null; try { docIDCheck(db, docID); docID = convertDocID(docID); String login = (user == null) ? "" : user + ":" + password + "@"; String url = "http://" + login + host + ":" + dbPort + "/" + db + "/" + docID; String revid = getRevId(db, docID); if (revid != null) json = addRevId(json, revid); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); byte[] jData = json.getBytes(); conn.setRequestProperty("Content-Length", Integer.toString(jData.length)); conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); //Get Response return readResponse(conn, 0L, ""); } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }