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.serenegiant.media.TLMediaEncoder.java
/** * write frame header//from w w w. j a v a 2 s . com * @param presentation_time_us * @param size * @throws IOException */ /*package*/static void writeHeader(final DataOutputStream out, final int sequence, final int frame_number, final long presentation_time_us, final int size, final int flag) throws IOException { out.writeInt(sequence); out.writeInt(frame_number); out.writeLong(presentation_time_us); out.writeInt(size); out.writeInt(flag); // out.write(RESERVED, 0, 40); }
From source file:info.magnolia.cms.exchange.simple.Transporter.java
/** * http form multipart form post//from w ww. j av a2 s . c o m * @param connection * @param activationContent * @throws ExchangeException */ public static void transport(URLConnection connection, ActivationContent activationContent) throws ExchangeException { FileInputStream fis = null; DataOutputStream outStream = null; try { byte[] buffer = new byte[BUFFER_SIZE]; connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY); connection.setRequestProperty("Cache-Control", "no-cache"); outStream = new DataOutputStream(connection.getOutputStream()); outStream.writeBytes("--" + BOUNDARY + "\r\n"); // set all resources from activationContent Iterator fileNameIterator = activationContent.getFiles().keySet().iterator(); while (fileNameIterator.hasNext()) { String fileName = (String) fileNameIterator.next(); fis = new FileInputStream(activationContent.getFile(fileName)); outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileName + "\"\r\n"); outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n"); while (true) { synchronized (buffer) { int amountRead = fis.read(buffer); if (amountRead == -1) { break; } outStream.write(buffer, 0, amountRead); } } fis.close(); outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n"); } outStream.flush(); outStream.close(); log.debug("Activation content sent as multipart/form-data"); } catch (Exception e) { throw new ExchangeException( "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.error("Exception caught", e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { log.error("Exception caught", e); } } } }
From source file:org.ohmage.request.image.ImageReadRequest.java
/** * Responds to the request with an image if it was successful or JSON if it * was not./*w ww.ja va2 s . c om*/ */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Writing the image read response."); if (ANDROID_CLIENT_NAME.equals(getClient())) { // TODO move to web server configuration for all image file types? // For now, this allows images to be stored by clients for one year // and specifies private to disable intermediaries from caching the // image. (HTTP 1.1) httpResponse.setHeader("Cache-Control", "max-age=1051200, private"); } else { // Sets the HTTP headers to disable caching expireResponse(httpResponse); } // Open the connection to the image if it is not null. InputStream imageStream = null; try { if (image != null) { imageStream = image.getInputStream(size); } } catch (DomainException e) { LOGGER.error("Could not connect to the image.", e); this.setFailed(ErrorCode.SYSTEM_GENERAL_ERROR, "Image not found."); httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); super.respond(httpRequest, httpResponse, (JSONObject) null); return; } // If the request hasn't failed, attempt to write the file to the // output stream. try { if (isFailed()) { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); super.respond(httpRequest, httpResponse, (JSONObject) null); } else { // Set the type of the value. // FIXME: This isn't necessarily the case. We might want to do // some sort of image inspection to figure out what this should // be. httpResponse.setContentType(image.getType(size)); httpResponse.setHeader("Content-Length", new Long(image.getSizeBytes(size)).toString()); // If available, set the token. if (getUser() != null) { final String token = getUser().getToken(); if (token != null) { CookieUtils.setCookieValue(httpResponse, InputKeys.AUTH_TOKEN, token); } } // Creates the writer that will write the response, success or // fail. OutputStream os; try { os = httpResponse.getOutputStream(); } catch (IOException e) { LOGGER.error("Unable to create writer object. Aborting.", e); return; } // Set the output stream to the response. DataOutputStream dos = new DataOutputStream(os); byte[] bytes = new byte[CHUNK_SIZE]; int currRead; try { while ((currRead = imageStream.read(bytes)) != -1) { dos.write(bytes, 0, currRead); } } finally { // Close the data output stream to which we were writing. try { dos.close(); } catch (ClientAbortException e) { LOGGER.info("The client hung up unexpectedly.", e); } catch (IOException e) { LOGGER.warn("Error closing the data output stream.", e); } } } } // If there was an error getting the image's information, abort // the whole operation and return an error. catch (DomainException e) { LOGGER.error("There was a problem reading or writing the image.", e); setFailed(); httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // If the client hangs up, just print a warning. catch (ClientAbortException e) { LOGGER.info("The client hung up unexpectedly.", e); } // If the error occurred while reading from the input stream or // writing to the output stream, abort the whole operation and // return an error. catch (IOException e) { LOGGER.error("The contents of the file could not be read or written to the response.", e); setFailed(); httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // No matter what, try to close the input stream if it exists. finally { try { if (imageStream != null) { imageStream.close(); } } // If the client hangs up, just print a warning. catch (ClientAbortException e) { LOGGER.info("The client hung up unexpectedly.", e); } catch (IOException e) { LOGGER.warn("Could not close the image stream.", e); // We don't care about failing the request, because, either, it // has already been failed or we wrote everything already. } } }
From source file:org.apache.hadoop.security.SaslRpcClient.java
/** * Do client side SASL authentication with server via the given InputStream * and OutputStream/*w w w .j a v a 2s . co m*/ * * @param inS * InputStream to use * @param outS * OutputStream to use * @return true if connection is set up, or false if needs to switch * to simple Auth. * @throws IOException */ public boolean saslConnect(InputStream inS, OutputStream outS) throws IOException { DataInputStream inStream = new DataInputStream(new BufferedInputStream(inS)); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(outS)); try { byte[] saslToken = new byte[0]; if (saslClient.hasInitialResponse()) saslToken = saslClient.evaluateChallenge(saslToken); if (saslToken != null) { outStream.writeInt(saslToken.length); outStream.write(saslToken, 0, saslToken.length); outStream.flush(); if (LOG.isDebugEnabled()) LOG.debug("Have sent token of size " + saslToken.length + " from initSASLContext."); } if (!saslClient.isComplete()) { readStatus(inStream); int len = inStream.readInt(); if (len == SaslRpcServer.SWITCH_TO_SIMPLE_AUTH) { if (LOG.isDebugEnabled()) LOG.debug("Server asks us to fall back to simple auth."); saslClient.dispose(); return false; } saslToken = new byte[len]; if (LOG.isDebugEnabled()) LOG.debug("Will read input token of size " + saslToken.length + " for processing by initSASLContext"); inStream.readFully(saslToken); } while (!saslClient.isComplete()) { saslToken = saslClient.evaluateChallenge(saslToken); if (saslToken != null) { if (LOG.isDebugEnabled()) LOG.debug("Will send token of size " + saslToken.length + " from initSASLContext."); outStream.writeInt(saslToken.length); outStream.write(saslToken, 0, saslToken.length); outStream.flush(); } if (!saslClient.isComplete()) { readStatus(inStream); saslToken = new byte[inStream.readInt()]; if (LOG.isDebugEnabled()) LOG.debug("Will read input token of size " + saslToken.length + " for processing by initSASLContext"); inStream.readFully(saslToken); } } if (LOG.isDebugEnabled()) { LOG.debug("SASL client context established. Negotiated QoP: " + saslClient.getNegotiatedProperty(Sasl.QOP)); } return true; } catch (IOException e) { try { saslClient.dispose(); } catch (SaslException ignored) { // ignore further exceptions during cleanup } throw e; } }
From source file:com.cypress.cysmart.RDKEmulatorView.MicrophoneEmulatorFragment.java
private void createWavFile(File fileToConvert, String wavFilePath) { try {/*from w w w. jav a2 s .co m*/ long mySubChunk1Size = 16; int myBitsPerSample = 16; int myFormat = 1; long myChannels = 1; long mySampleRate = 16000; long myByteRate = mySampleRate * myChannels * myBitsPerSample / 8; int myBlockAlign = (int) (myChannels * myBitsPerSample / 8); byte[] clipData = getBytesFromFile(fileToConvert); long myDataSize = clipData.length; long myChunk2Size = myDataSize * myChannels * myBitsPerSample / 8; long myChunkSize = 36 + myChunk2Size; OutputStream os; os = new FileOutputStream(new File(wavFilePath)); BufferedOutputStream bos = new BufferedOutputStream(os); DataOutputStream outFile = new DataOutputStream(bos); outFile.writeBytes("RIFF"); // 00 - RIFF outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file? outFile.writeBytes("WAVE"); // 08 - WAVE outFile.writeBytes("fmt "); // 12 - fmt outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???) outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second) outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 outFile.writeBytes("data"); // 36 - data outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers outFile.flush(); outFile.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.serenegiant.media.TLMediaEncoder.java
/** * write raw bit stream into specific intermediate file * @param out/* ww w. jav a 2 s . c o m*/ * @param sequence * @param frame_number * @param info * @param buffer * @param writeBuffer * @throws IOException */ private static final void writeStream(final DataOutputStream out, final int sequence, final int frame_number, final MediaCodec.BufferInfo info, final ByteBuffer buffer, byte[] writeBuffer) throws IOException { if (writeBuffer.length < info.size) { writeBuffer = new byte[info.size]; } buffer.position(info.offset); buffer.get(writeBuffer, 0, info.size); try { writeHeader(out, sequence, frame_number, info.presentationTimeUs, info.size, info.flags); out.write(writeBuffer, 0, info.size); } catch (IOException e) { if (DEBUG) Log.e(TAG_STATIC, "writeStream:", e); throw e; } }
From source file:org.apache.hadoop.hbase.security.HBaseSaslRpcClient.java
/** * Do client side SASL authentication with server via the given InputStream * and OutputStream//from w ww . ja v a 2s .c om * * @param inS * InputStream to use * @param outS * OutputStream to use * @return true if connection is set up, or false if needs to switch * to simple Auth. * @throws IOException */ public boolean saslConnect(InputStream inS, OutputStream outS) throws IOException { DataInputStream inStream = new DataInputStream(new BufferedInputStream(inS)); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(outS)); try { byte[] saslToken = new byte[0]; if (saslClient.hasInitialResponse()) saslToken = saslClient.evaluateChallenge(saslToken); if (saslToken != null) { outStream.writeInt(saslToken.length); outStream.write(saslToken, 0, saslToken.length); outStream.flush(); if (LOG.isDebugEnabled()) LOG.debug("Have sent token of size " + saslToken.length + " from initSASLContext."); } if (!saslClient.isComplete()) { readStatus(inStream); int len = inStream.readInt(); if (len == SaslUtil.SWITCH_TO_SIMPLE_AUTH) { if (!fallbackAllowed) { throw new IOException("Server asks us to fall back to SIMPLE auth, " + "but this client is configured to only allow secure connections."); } if (LOG.isDebugEnabled()) { LOG.debug("Server asks us to fall back to simple auth."); } saslClient.dispose(); return false; } saslToken = new byte[len]; if (LOG.isDebugEnabled()) LOG.debug("Will read input token of size " + saslToken.length + " for processing by initSASLContext"); inStream.readFully(saslToken); } while (!saslClient.isComplete()) { saslToken = saslClient.evaluateChallenge(saslToken); if (saslToken != null) { if (LOG.isDebugEnabled()) LOG.debug("Will send token of size " + saslToken.length + " from initSASLContext."); outStream.writeInt(saslToken.length); outStream.write(saslToken, 0, saslToken.length); outStream.flush(); } if (!saslClient.isComplete()) { readStatus(inStream); saslToken = new byte[inStream.readInt()]; if (LOG.isDebugEnabled()) LOG.debug("Will read input token of size " + saslToken.length + " for processing by initSASLContext"); inStream.readFully(saslToken); } } if (LOG.isDebugEnabled()) { LOG.debug("SASL client context established. Negotiated QoP: " + saslClient.getNegotiatedProperty(Sasl.QOP)); } return true; } catch (IOException e) { try { saslClient.dispose(); } catch (SaslException ignored) { // ignore further exceptions during cleanup } throw e; } }
From source file:com.asto.move.util.qcloud.pic.PicCloud.java
/** * Download ??/* w w w.j a v a2 s. co m*/ * * @param url * @param fileName ? * @return ?0? */ public int Download(String url, String fileName) { if (fileName == null || "".equals(fileName)) { return SetError(-1, "file name is empty."); } String rsp = ""; try { URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setRequestMethod("GET"); connection.setRequestProperty("Host", "web.image.myqcloud.com"); connection.setRequestProperty("user-agent", "qcloud-java-sdk"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); InputStream in = new DataInputStream(connection.getInputStream()); File file = new File(fileName); String path = ""; if (!file.exists()) { path = fileName.substring(0, fileName.lastIndexOf("/")); File catalogFile = new File(path); catalogFile.mkdirs(); } DataOutputStream ops = new DataOutputStream(new FileOutputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) > 0) { ops.write(bufferOut, 0, bytes); } ops.close(); in.close(); } catch (Exception e) { return SetError(-1, "url exception, e=" + e.toString()); } return SetError(0, "success"); }
From source file:org.commoncrawl.hadoop.mergeutils.SequenceFileSpillWriter.java
public void spillRawRecord2(byte[] keyData, int keyOffset, int keyLength, final byte[] valueData, final int valueOffset, final int valueLength) throws IOException { if (_indexWriter != null) _indexWriter.indexItem(keyData, keyOffset, keyLength, valueData, valueOffset, valueLength, writer.getLength());//from w w w .j a v a2s . c o m _recordCount++; writer.appendRaw(keyData, keyOffset, keyLength, new ValueBytes() { @Override public int getSize() { return valueLength; } @Override public void writeCompressedBytes(DataOutputStream outStream) throws IllegalArgumentException, IOException { throw new IOException("UnSupported Method"); } @Override public void writeUncompressedBytes(DataOutputStream outStream) throws IOException { outStream.write(valueData, valueOffset, valueLength); } }); }
From source file:com.vimc.ahttp.HurlWorker.java
/** * write file parameters//w w w . j a va2s. co m */ @SuppressWarnings("rawtypes") private void writeFiles(ArrayList<FileParameter> fileParams, DataOutputStream out, String boundary) throws IOException { for (FileParameter fileParameter : fileParams) { writeDataStart(out, fileParameter.paramName, fileParameter.fileName, boundary); InputStream is = new FileInputStream(fileParameter.file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { out.write(bytes, 0, len); } is.close(); writeDataEnd(out, boundary); } }