List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:com.tonchidot.nfc_contact_exchanger.lib.PictureUploader.java
private String doFileUploadJson(String url, String fileParamName, byte[] data) { try {// w w w . java 2 s . com String boundary = "BOUNDARY" + new Date().getTime() + "BOUNDARY"; String lineEnd = "\r\n"; String twoHyphens = "--"; URL connUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); 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=\"" + fileParamName + "\";filename=\"photo.jpg\"" + lineEnd); dos.writeBytes(lineEnd); dos.write(data, 0, data.length); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } catch (IOException e) { if (Config.LOGD) { Log.d(TAG, "IOException : " + e); } } return null; }
From source file:UnmanagedAMLauncher.java
public void launchAM(ApplicationAttemptId attemptId) throws IOException, YarnException { Credentials credentials = new Credentials(); Token<AMRMTokenIdentifier> token = rmClient.getAMRMToken(attemptId.getApplicationId()); // Service will be empty but that's okay, we are just passing down only // AMRMToken down to the real AM which eventually sets the correct // service-address. credentials.addToken(token.getService(), token); File tokenFile = File.createTempFile("unmanagedAMRMToken", "", new File(System.getProperty("user.dir"))); try {//from ww w. ja v a 2s. co m FileUtil.chmod(tokenFile.getAbsolutePath(), "600"); } catch (InterruptedException ex) { throw new RuntimeException(ex); } tokenFile.deleteOnExit(); DataOutputStream os = new DataOutputStream(new FileOutputStream(tokenFile, true)); credentials.writeTokenStorageToStream(os); os.close(); Map<String, String> env = System.getenv(); ArrayList<String> envAMList = new ArrayList<String>(); boolean setClasspath = false; for (Map.Entry<String, String> entry : env.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key.equals("CLASSPATH")) { setClasspath = true; if (classpath != null) { value = value + File.pathSeparator + classpath; } } envAMList.add(key + "=" + value); } if (!setClasspath && classpath != null) { envAMList.add("CLASSPATH=" + classpath); } ContainerId containerId = ContainerId.newContainerId(attemptId, 0); String hostname = InetAddress.getLocalHost().getHostName(); envAMList.add(Environment.CONTAINER_ID.name() + "=" + containerId); envAMList.add(Environment.NM_HOST.name() + "=" + hostname); envAMList.add(Environment.NM_HTTP_PORT.name() + "=0"); envAMList.add(Environment.NM_PORT.name() + "=0"); envAMList.add(Environment.LOCAL_DIRS.name() + "= /tmp"); envAMList.add(ApplicationConstants.APP_SUBMIT_TIME_ENV + "=" + System.currentTimeMillis()); envAMList.add(ApplicationConstants.CONTAINER_TOKEN_FILE_ENV_NAME + "=" + tokenFile.getAbsolutePath()); String[] envAM = new String[envAMList.size()]; Process amProc = Runtime.getRuntime().exec(amCmd, envAMList.toArray(envAM)); final BufferedReader errReader = new BufferedReader(new InputStreamReader(amProc.getErrorStream())); final BufferedReader inReader = new BufferedReader(new InputStreamReader(amProc.getInputStream())); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { System.err.println(line); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; Thread outThread = new Thread() { @Override public void run() { try { String line = inReader.readLine(); while ((line != null) && !isInterrupted()) { System.out.println(line); line = inReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the out stream", ioe); } } }; try { errThread.start(); outThread.start(); } catch (IllegalStateException ise) { } // wait for the process to finish and check the exit code try { int exitCode = amProc.waitFor(); LOG.info("AM process exited with value: " + exitCode); } catch (InterruptedException e) { e.printStackTrace(); } finally { amCompleted = true; } try { // make sure that the error thread exits // on Windows these threads sometimes get stuck and hang the execution // timeout and join later after destroying the process. errThread.join(); outThread.join(); errReader.close(); inReader.close(); } catch (InterruptedException ie) { LOG.info("ShellExecutor: Interrupted while reading the error/out stream", ie); } catch (IOException ioe) { LOG.warn("Error while closing the error/out stream", ioe); } amProc.destroy(); }
From source file:com.mbrlabs.mundus.assets.EditorAssetManager.java
public TerrainAsset createTerrainAsset(int vertexResolution, int size) throws IOException { String terraFilename = "terrain_" + UUID.randomUUID().toString() + ".terra"; String metaFilename = terraFilename + ".meta"; // create meta file String metaPath = FilenameUtils.concat(rootFolder.path(), metaFilename); MetaFile meta = createNewMetaFile(new FileHandle(metaPath), AssetType.TERRAIN); meta.setTerrainSize(size);//from w ww. ja v a2 s .c om meta.save(); // create terra file String terraPath = FilenameUtils.concat(rootFolder.path(), terraFilename); File terraFile = new File(terraPath); FileUtils.touch(terraFile); // create initial height data float[] data = new float[vertexResolution * vertexResolution]; for (int i = 0; i < data.length; i++) { data[i] = 0; } // write terra file DataOutputStream outputStream = new DataOutputStream( new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(terraFile)))); for (float f : data) { outputStream.writeFloat(f); } outputStream.flush(); outputStream.close(); // load & apply standard chessboard texture TerrainAsset asset = new TerrainAsset(meta, new FileHandle(terraFile)); asset.load(); TextureAsset chessboard = (TextureAsset) findAssetByID(STANDARD_ASSET_TEXTURE_CHESSBOARD); if (chessboard != null) { // create splatmap PixmapTextureAsset splatmap = createPixmapTextureAsset(SplatMap.DEFAULT_SIZE); asset.setSplatmap(splatmap); asset.setSplatBase(chessboard); asset.applyDependencies(); } addAsset(asset); return asset; }
From source file:prince.app.ccm.tools.Task.java
private void sendPost(String url, String postParams) throws Exception { URL obj = new URL(url); conn = (HttpURLConnection) obj.openConnection(); // Acts like a browser conn.setUseCaches(false);/*from w w w .j a v a 2 s . c om*/ conn.setRequestMethod("POST"); conn.setRequestProperty("Host", "www.iglesiamallorca.com"); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6,ca;q=0.4"); if (cookies != null) { for (String cookie : this.cookies) { conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]); } } conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Referer", log); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); conn.setDoOutput(true); conn.setDoInput(true); // Send post request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); Log.d(TAG, "sendPost: " + conn.getResponseCode()); int responseCode = conn.getResponseCode(); if (conn.getHeaderField("Cache-Control") == null) { Log.e(TAG, "An error occurred"); } else { Log.e(TAG, "Everything worked out well"); } Log.e(TAG, conn.getHeaderFields().toString()); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postParams); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // System.out.println(response.toString()); Log.d(TAG, "Done in sendPost"); }
From source file:me.cybermaxke.merchants.v16r3.SMerchant.java
protected void sendUpdate() { if (this.customers.isEmpty()) { return;//from w w w. j a v a 2 s.c o m } ByteArrayOutputStream baos0 = new ByteArrayOutputStream(); DataOutputStream dos0 = new DataOutputStream(baos0); // Write the recipe list this.offers.a(dos0); try { dos0.flush(); dos0.close(); } catch (IOException e) { e.printStackTrace(); } // Get the bytes byte[] data = baos0.toByteArray(); // Send a packet to all the players Iterator<Player> it = this.customers.iterator(); while (it.hasNext()) { EntityPlayer player0 = ((CraftPlayer) it.next()).getHandle(); // Every player has a different window id ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); DataOutputStream dos1 = new DataOutputStream(baos1); try { dos1.writeInt(player0.activeContainer.windowId); dos1.write(data); dos1.flush(); dos1.close(); } catch (IOException e) { e.printStackTrace(); } player0.playerConnection.sendPacket(new Packet250CustomPayload("MC|TrList", baos1.toByteArray())); } }
From source file:com.netflix.zeno.examples.MultipleImageSerializationExample.java
private byte[] writeDelta(FastBlobWriter writer) { /// Again create an output stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); try {//w w w . j a v a 2 s . c o m /// 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:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {/*from w w w . ja va 2s .c o m*/ URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:com.magicmod.mmweather.engine.WeatherEngine.java
private boolean flushCache(String string) { DataOutputStream out = null; File file = null;// w w w .j a v a2s . c o m try { file = new File(mCacheDir, CACHE_NAME); out = new DataOutputStream(new FileOutputStream(file)); out.write(string.getBytes()); if (out != null) { out.flush(); out.close(); } } catch (Exception e) { // TODO: handle exception Log.e(TAG, "Write to Cache fail"); e.printStackTrace(); if (file != null) { file.delete(); } return false; } finally { if (out != null) { try { out.flush(); out.close(); } catch (Exception e2) { // TODO: handle exception if (file != null) { file.delete(); } } } } return true; }
From source file:J2MEWriteReadMixedDataTypesExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);//from www. j a va2s. c om notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString = "First Record"; int outputInteger = 15; boolean outputBoolean = true; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); outputDataStream.writeUTF(outputString); outputDataStream.writeBoolean(outputBoolean); outputDataStream.writeInt(outputInteger); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); outputStream.close(); outputDataStream.close(); String inputString = null; int inputInteger = 0; boolean inputBoolean = false; byte[] byteInputData = new byte[100]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); for (int x = 1; x <= recordstore.getNumRecords(); x++) { recordstore.getRecord(x, byteInputData, 0); inputString = inputDataStream.readUTF(); inputBoolean = inputDataStream.readBoolean(); inputInteger = inputDataStream.readInt(); inputStream.reset(); } inputStream.close(); inputDataStream.close(); alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:com.wlcg.aroundme.cc.weather.WeatherEngine.java
/** * //from ww w. ja v a2 s. com * <h1></h1> * 2014-3-18 * @param string * @return */ private synchronized boolean flushCache(String string) { DataOutputStream out = null; File file = null; try { file = new File(mCacheDir, CACHE_NAME); out = new DataOutputStream(new FileOutputStream(file)); out.write(string.getBytes()); if (out != null) { out.flush(); out.close(); } } catch (Exception e) { // TODO: handle exception Log.e(TAG, "Write to Cache fail"); e.printStackTrace(); if (file != null) { file.delete(); } return false; } finally { if (out != null) { try { out.flush(); out.close(); } catch (Exception e2) { // TODO: handle exception if (file != null) { file.delete(); } } } } return true; }