List of usage examples for java.io DataOutputStream write
public synchronized void write(int b) throws IOException
b
) to the underlying output stream. From source file:org.eclipse.gyrex.cloud.internal.queue.Message.java
public byte[] toByteArray() throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(bos); try {// w w w . ja v a2 s . co m dos.writeInt(1); // serialized format version dos.writeLong(invisibleTimeoutTS); // invisible timeout dos.writeInt(body.length); // body size dos.write(body); // body return bos.toByteArray(); } finally { IOUtils.closeQuietly(dos); } }
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 va2 s . c om*/ 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:gobblin.metrics.kafka.KafkaAvroReporter.java
/** * Implementation of {@link gobblin.metrics.SerializedMetricReportReporter#writeSchemaVersioningInformation} supporting * a {@link gobblin.metrics.kafka.KafkaAvroSchemaRegistry}. * * <p>/* w w w . j a va 2 s.co m*/ * If a {@link gobblin.metrics.kafka.KafkaAvroSchemaRegistry} is provided to the reporter, this method writes * the {@link gobblin.metrics.kafka.KafkaAvroSchemaRegistry} id for the {@link gobblin.metrics.MetricReport} schema * instead of the static {@link gobblin.metrics.MetricReportUtils#SCHEMA_VERSION}. This allows processors like * Camus to retrieve the correct {@link org.apache.avro.Schema} from a REST schema registry. This method will also * automatically register the {@link org.apache.avro.Schema} to the REST registry. It is assumed that calling * {@link gobblin.metrics.kafka.KafkaAvroSchemaRegistry#register} more than once for the same * {@link org.apache.avro.Schema} is not a problem, as it will be called at least once per JVM. * * If no {@link gobblin.metrics.kafka.KafkaAvroSchemaRegistry} is provided, this method simply calls the super method. * </p> * * @param outputStream Empty {@link java.io.DataOutputStream} that will hold the serialized * {@link gobblin.metrics.MetricReport}. Any data written by this method * will appear at the beginning of the emitted message. * @throws IOException */ @Override protected void writeSchemaVersioningInformation(DataOutputStream outputStream) throws IOException { if (this.registry.isPresent()) { if (!this.registrySchemaId.isPresent()) { this.registrySchemaId = Optional.of(this.registry.get().register(MetricReport.SCHEMA$)); } outputStream.writeByte(KafkaAvroSchemaRegistry.MAGIC_BYTE); try { outputStream.write(Hex.decodeHex(this.registrySchemaId.get().toCharArray())); } catch (DecoderException exception) { throw new IOException(exception); } } else { super.writeSchemaVersioningInformation(outputStream); } }
From source file:com.magicmod.mmweather.engine.WeatherEngine.java
private boolean flushCache(String string) { DataOutputStream out = null; File file = null;/*from w ww . java 2 s.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:org.apache.apex.malhar.lib.function.FunctionOperator.java
private byte[] functionClassData(Function f) { Class<? extends Function> classT = f.getClass(); byte[] classBytes = null; byte[] classNameBytes = null; String className = classT.getName(); try {//from w w w . j av a 2 s . c o m classNameBytes = className.replace('.', '/').getBytes(); classBytes = IOUtils.toByteArray( classT.getClassLoader().getResourceAsStream(className.replace('.', '/') + ".class")); int cursor = 0; for (int j = 0; j < classBytes.length; j++) { if (classBytes[j] != classNameBytes[cursor]) { cursor = 0; } else { cursor++; } if (cursor == classNameBytes.length) { for (int p = 0; p < classNameBytes.length; p++) { if (classBytes[j - p] == '$') { classBytes[j - p] = '_'; } } cursor = 0; } } ClassReader cr = new ClassReader(new ByteArrayInputStream(classBytes)); ClassWriter cw = new ClassWriter(0); AnnonymousClassModifier annonymousClassModifier = new AnnonymousClassModifier(Opcodes.ASM4, cw); cr.accept(annonymousClassModifier, 0); classBytes = cw.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } int dataLength = classNameBytes.length + 4 + 4; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(dataLength); DataOutputStream output = new DataOutputStream(byteArrayOutputStream); try { output.writeInt(classNameBytes.length); output.write(className.replace('$', '_').getBytes()); output.writeInt(classBytes.length); output.write(classBytes); } catch (IOException e) { throw new RuntimeException(e); } finally { try { output.flush(); output.close(); } catch (IOException e) { throw new RuntimeException(e); } } return byteArrayOutputStream.toByteArray(); }
From source file:ro.bmocanu.trafficproxy.peers.PacketSenderImpl.java
/** * {@inheritDoc}//from w w w .j a v a2s. co m */ @Override protected void internalRun() { DataOutputStream targetOutputStream = peerChannel.getOutputStream(); Packet packet = packetQueue.poll(); if (packet != null) { try { targetOutputStream.writeInt(packet.getConnectorId()); targetOutputStream.writeInt(packet.getWorkerId()); targetOutputStream.writeInt(packet.getCommand().getCode()); targetOutputStream.writeInt(packet.getContentLength()); targetOutputStream.write(packet.getContent()); targetOutputStream.flush(); } catch (IOException exception) { LOG.error("Missed one packet; command=" + packet.getCommand().name() + ", connectorId=" + packet.getConnectorId(), exception); } } }
From source file:com.wlcg.aroundme.cc.weather.WeatherEngine.java
/** * //from ww w.j a v a 2 s . c o m * <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; }
From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java
public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception { boolean isNew = false; if (cfg.getProcess() != null || isNew) { LOG.info("Stopping Launchpad " + cfg.getId()); boolean destroy = true; final int twoMinutes = 2 * 60 * 1000; final File controlPortFile = getControlPortFile(cfg.getDirectory()); LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists()); if (controlPortFile.exists()) { // reading control port int controlPort = -1; String secretKey = null; LineNumberReader lnr = null; String serverName = null; try { lnr = new LineNumberReader(new FileReader(controlPortFile)); final String portLine = lnr.readLine(); final int pos = portLine.indexOf(':'); controlPort = Integer.parseInt(portLine.substring(pos + 1)); if (pos > 0) { serverName = portLine.substring(0, pos); }/*from w ww . j a v a 2 s .co m*/ secretKey = lnr.readLine(); } catch (final NumberFormatException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } catch (final IOException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } finally { IOUtils.closeQuietly(lnr); } if (controlPort != -1) { final List<String> hosts = new ArrayList<String>(); if (serverName != null) { hosts.add(serverName); } hosts.add("localhost"); hosts.add("127.0.0.1"); LOG.debug("Found control port " + controlPort); int index = 0; while (destroy && index < hosts.size()) { final String hostName = hosts.get(index); Socket clientSocket = null; DataOutputStream out = null; BufferedReader in = null; try { LOG.debug("Trying to connect to " + hostName + ":" + controlPort); clientSocket = new Socket(); // set a socket timeout clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes); // without that, read() call on the InputStream associated with this Socket is infinite clientSocket.setSoTimeout(twoMinutes); LOG.debug(hostName + ":" + controlPort + " connection estabilished, sending the 'stop' command..."); out = new DataOutputStream(clientSocket.getOutputStream()); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); if (secretKey != null) { out.writeBytes(secretKey); out.write(' '); } out.writeBytes("stop\n"); in.readLine(); destroy = false; LOG.debug("'stop' command sent to " + hostName + ":" + controlPort); } catch (final Throwable ignore) { // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions // we ignore this for now LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort + " due to: " + ignore.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(clientSocket); } index++; } } } if (cfg.getProcess() != null) { final Process process = cfg.getProcess(); if (!destroy) { // as shutdown might block forever, we use a timeout final long now = System.currentTimeMillis(); final long end = now + twoMinutes; LOG.debug("Waiting for process to stop..."); while (isAlive(process) && (System.currentTimeMillis() < end)) { try { Thread.sleep(2500); } catch (InterruptedException e) { // ignore } } if (isAlive(process)) { LOG.debug("Process timeout out after 2 minutes"); destroy = true; } else { LOG.debug("Process stopped"); } } if (destroy) { LOG.debug("Destroying process..."); process.destroy(); LOG.debug("Process destroyed"); } cfg.setProcess(null); } } else { LOG.warn("Launchpad already stopped"); } }
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 {/* 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:org.syncany.operations.init.ApplicationLink.java
private byte[] getPlaintextStorageXml() throws Exception { ByteArrayOutputStream plaintextByteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream plaintextOutputStream = new DataOutputStream(plaintextByteArrayOutputStream); plaintextOutputStream.writeInt(transferSettings.getType().getBytes().length); plaintextOutputStream.write(transferSettings.getType().getBytes()); GZIPOutputStream plaintextGzipOutputStream = new GZIPOutputStream(plaintextOutputStream); new Persister(new Format(0)).write(transferSettings, plaintextGzipOutputStream); plaintextGzipOutputStream.close();//from w w w . j a va 2s.c o m return plaintextByteArrayOutputStream.toByteArray(); }