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.apache.cassandra.net.OutboundTcpConnection.java
public static void write(Message message, String id, DataOutputStream out) throws IOException { /*/* w w w . j a v a 2s. com*/ Setting up the protocol header. This is 4 bytes long represented as an integer. The first 2 bits indicate the serializer type. The 3rd bit indicates if compression is turned on or off. It is turned off by default. The 4th bit indicates if we are in streaming mode. It is turned off by default. The 5th-8th bits are reserved for future use. The next 8 bits indicate a version number. Remaining 15 bits are not used currently. */ int header = 0; // Setting up the serializer bit header |= MessagingService.serializerType_.ordinal(); // set compression bit. if (false) header |= 4; // Setting up the version bit header |= (message.getVersion() << 8); out.writeInt(MessagingService.PROTOCOL_MAGIC); out.writeInt(header); // compute total Message length for compatibility w/ 0.8 and earlier byte[] bytes = message.getMessageBody(); int total = messageLength(message.header_, id, bytes); out.writeInt(total); out.writeUTF(id); Header.serializer().serialize(message.header_, out, message.getVersion()); out.writeInt(bytes.length); out.write(bytes); }
From source file:it.jnrpe.net.JNRPEProtocolPacket.java
/** * Converts the packet object to its byte array representation. * //from w ww . ja va 2s.c o m * @return The byte array representation of this packet. */ public byte[] toByteArray() { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeShort(packetVersion); dout.writeShort(packetTypeCode); dout.writeInt(crcValue); dout.writeShort(resultCode); dout.write(byteBufferAry); dout.write(dummyBytesAry); dout.close(); } catch (IOException e) { // Never happens... throw new IllegalStateException(e.getMessage(), e); } return bout.toByteArray(); }
From source file:org.dasein.cloud.test.identity.IdentityResources.java
/** * @link http://stackoverflow.com/a/14582408/211197 * @return Encoded generated public key//from w w w .ja va 2s .c om */ private @Nullable String generateKey() { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.genKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray())); return "ssh-rsa " + publicKeyEncoded + " dasein"; } catch (Throwable e) { return null; } }
From source file:net.nym.library.http.UploadImagesRequest.java
/** * ???//from w ww . j a va 2 s . c o m * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws java.io.IOException */ public static String postFile(String url, Map<String, Object> params, Map<String, File> files) throws IOException { String result = ""; String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; StringBuilder sb = new StringBuilder("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { // sb.append(PREFIX); // sb.append(BOUNDARY); // sb.append(LINEND); // sb.append("Content-Disposition: form-data; name=\"" // + entry.getKey() + "\"" + LINEND); // sb.append("Content-Type: text/plain; charset=" + CHARSET // + LINEND); // sb.append("Content-Transfer-Encoding: 8bit" + LINEND); // sb.append(LINEND); // sb.append(entry.getValue()); // sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString())) .append("&"); } sb.deleteCharAt(sb.length() - 1); URL uri = new URL(url + sb.toString()); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setDoInput(true);// ? conn.setDoOutput(true);// ? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // ? // StringBuilder sb = new StringBuilder(); // for (Map.Entry<String, Object> entry : params.entrySet()) { //// sb.append(PREFIX); //// sb.append(BOUNDARY); //// sb.append(LINEND); //// sb.append("Content-Disposition: form-data; name=\"" //// + entry.getKey() + "\"" + LINEND); //// sb.append("Content-Type: text/plain; charset=" + CHARSET //// + LINEND); //// sb.append("Content-Transfer-Encoding: 8bit" + LINEND); //// sb.append(LINEND); //// sb.append(entry.getValue()); //// sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); // } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(sb.toString().getBytes()); // ? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sbFile = new StringBuilder(); sbFile.append(PREFIX); sbFile.append(BOUNDARY); sbFile.append(LINEND); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sbFile.append(LINEND); Log.i(sbFile.toString()); outStream.write(sbFile.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // ? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); } outStream.flush(); // ?? int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sbResult = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sbResult.append((char) ch); } } result = sbResult.toString(); outStream.close(); conn.disconnect(); return result; }
From source file:it.jnrpe.net.JNRPEProtocolPacket.java
/** * Validates the packet CRC./*from ww w.j a v a 2 s .c o m*/ * * @throws BadCRCException * If the CRC can't be validated */ public void validate() throws BadCRCException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { dout.writeShort(packetVersion); dout.writeShort(packetTypeCode); dout.writeInt(0); // NO CRC dout.writeShort(resultCode); dout.write(byteBufferAry); dout.write(dummyBytesAry); dout.close(); byte[] vBytes = bout.toByteArray(); CRC32 crcAlg = new CRC32(); crcAlg.update(vBytes); if (!(((int) crcAlg.getValue()) == crcValue)) { throw new BadCRCException("Bad CRC"); } } catch (IOException e) { // Never happens... throw new IllegalStateException(e.getMessage(), e); } }
From source file:com.zzl.zl_app.cache.Utility.java
public static String uploadFile(File file, String RequestURL, String fileName) { Tools.log("IO", "RequestURL:" + RequestURL); String result = null;/*from w w w .j a v a 2 s .c o m*/ String BOUNDARY = UUID.randomUUID().toString(); // ?? String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT); conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); // ? conn.setRequestProperty("Charset", CHARSET); // ? conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * ? */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); Tools.log("FileSize", "file:" + file.length()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); Tools.log("FileSize", "size:" + len); } dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); dos.close(); is.close(); /** * ??? 200=? ????? */ int res = conn.getResponseCode(); Tools.log("IO", "ResponseCode:" + res); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:com.vimc.ahttp.HurlWorker.java
/** * write byte[] parameters// w w w. jav a2 s . co m */ @SuppressWarnings("rawtypes") private void writeBytes(ArrayList<ByteParameter> byteParams, DataOutputStream out, String boundary) throws IOException { for (ByteParameter byteParameter : byteParams) { writeDataStart(out, byteParameter.paramName, byteParameter.fileName, boundary); out.write(byteParameter.data); writeDataEnd(out, boundary); } }
From source file:org.eclipse.smila.integration.solr.SolrPipelet.java
public Id[] process(Blackboard blackboard, Id[] recordIds) throws ProcessingException { String updateURL = HTTP_LOCALHOST + SOLR_WEBAPP + UPDATE; String updateXMLMessage = null; URL url = null;//from w ww.j av a 2s.c o m HttpURLConnection conn = null; Id _id = null; try { url = new URL(updateURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(POST); conn.setRequestProperty(CONTENT_TYPE, TEXT_XML_CHARSET + UTF8); conn.setUseCaches(false); conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(10000); } catch (Exception e) { String msg = "Error while opening Solr connection: '" + e.getMessage() + "'"; _log.error(msg, e); throw new ProcessingException(msg, e); } try { DOMImplementation impl = DOMImplementationImpl.getDOMImplementation(); Document document = impl.createDocument(null, SolrResponseHandler.SOLR, null); Element add = null; if (_mode == ExecutionMode.ADD) { add = document.createElement(ADD); } else { add = document.createElement(DELETE); } if (_allowDoublets) { add.setAttribute(OVERWRITE, "false"); } else { add.setAttribute(OVERWRITE, "true"); } add.setAttribute(COMMIT_WITHIN, String.valueOf(_commitWithin)); for (Id id : recordIds) { _id = id; Element doc = document.createElement(SolrResponseHandler.DOC); add.appendChild(doc); // Create id attribute Element field = document.createElement(FIELD); field.setAttribute(SolrResponseHandler.NAME, SolrResponseHandler.ID); IdBuilder idBuilder = new IdBuilder(); String idXML = idBuilder.idToString(id); String idEncoded = URLEncoder.encode(idXML, UTF8); Text text = document.createTextNode(idEncoded); field.appendChild(text); doc.appendChild(field); // Create all other attributes Iterator<String> i = blackboard.getAttributeNames(id); while (i.hasNext()) { String attrName = i.next(); if (!attrName.startsWith(META_DATA) && !attrName.startsWith(RESPONSE_HEADER)) { Path path = new Path(attrName); Iterator<Literal> literals = blackboard.getLiterals(id, path).iterator(); while (literals.hasNext()) { Literal value = literals.next(); String stringValue = null; if (Literal.DataType.DATE.equals(value.getDataType())) { SimpleDateFormat df = new SimpleDateFormat(SolrResponseHandler.DATE_FORMAT_PATTERN); stringValue = df.format(value.getDateValue()); } else if (Literal.DataType.DATETIME.equals(value.getDataType())) { SimpleDateFormat df = new SimpleDateFormat(SolrResponseHandler.DATE_FORMAT_PATTERN); stringValue = df.format(value.getDateTimeValue()); } else { stringValue = replaceNonXMLChars(value.getStringValue()); } field = document.createElement(FIELD); field.setAttribute(SolrResponseHandler.NAME, attrName); text = document.createTextNode(stringValue); field.appendChild(text); doc.appendChild(field); } } } } Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); if (_log.isDebugEnabled()) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } DOMSource source = new DOMSource(add); Writer w = new StringWriter(); StreamResult streamResult = new StreamResult(w); transformer.transform(source, streamResult); updateXMLMessage = streamResult.getWriter().toString(); conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(updateXMLMessage.length())); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.write(updateXMLMessage.getBytes(UTF8)); os.flush(); os.close(); System.out.println(updateXMLMessage); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); System.out.println("Response:\n" + response.toString()); } catch (Exception e) { String msg = "Error while processing record '" + _id + "' for index '" + _indexName + "': " + e.getMessage() + "'."; _log.error(msg, e); if (_log.isDebugEnabled()) { try { FileOutputStream fos = new FileOutputStream(_id.getIdHash() + ".xml"); fos.write(updateXMLMessage.getBytes(UTF8)); fos.flush(); fos.close(); } catch (Exception ee) { throw new ProcessingException(msg, ee); } } throw new ProcessingException(msg, e); } finally { if (conn != null) { conn.disconnect(); } } return recordIds; }
From source file:org.gitools.matrix.format.CmatrixMatrixFormat.java
@Override protected void writeResource(IResourceLocator resourceLocator, IMatrix resource, IProgressMonitor progressMonitor) throws PersistenceException { if (!(resource instanceof CompressMatrix)) { throw new UnsupportedOperationException("It is not possible to convert into a compress matrix"); }//from w ww .ja v a 2 s . c om CompressMatrix matrix = (CompressMatrix) resource; try { DataOutputStream out = new DataOutputStream(resourceLocator.openOutputStream(progressMonitor)); int formatVersion = 0; out.writeInt(0); progressMonitor.begin("Writing dictionary...", 1); byte[] dictionary = matrix.getDictionary(); out.writeInt(dictionary.length); out.write(dictionary); progressMonitor.begin("Writing columns...", 1); byte[] buffer = AbstractCompressor.stringToByteArray(matrix.getColumns().getLabels()); out.writeInt(buffer.length); out.write(buffer); progressMonitor.begin("Writing rows...", 1); buffer = AbstractCompressor.stringToByteArray(matrix.getRows().getLabels()); out.writeInt(buffer.length); out.write(buffer); progressMonitor.begin("Writing headers...", 1); String[] headers = new String[resource.getLayers().size()]; for (int i = 0; i < resource.getLayers().size(); i++) { headers[i] = resource.getLayers().get(i).getId(); } buffer = AbstractCompressor.stringToByteArray(headers); out.writeInt(buffer.length); out.write(buffer); Map<Integer, CompressRow> compressRowMap = matrix.getCompressRows(); progressMonitor.begin("Writing values...", compressRowMap.size()); for (Map.Entry<Integer, CompressRow> value : compressRowMap.entrySet()) { progressMonitor.worked(1); // The row position out.writeInt(value.getKey()); // Compress the row CompressRow compressRow = value.getValue(); // Write the length of the buffer before compression out.writeInt(compressRow.getNotCompressedLength()); // The length of the compressed buffer with the columns out.writeInt(compressRow.getContent().length); // The buffer with all the columns out.write(compressRow.getContent()); } out.close(); } catch (IOException e) { throw new PersistenceException(e); } }
From source file:org.darwinathome.server.controller.HubController.java
@RequestMapping(Hub.SET_TARGET_SERVICE) public void setTarget(@PathVariable("session") String session, @RequestParam(Hub.PARAM_LOCATION_X) double x, @RequestParam(Hub.PARAM_LOCATION_Y) double y, @RequestParam(Hub.PARAM_LOCATION_Z) double z, @RequestParam(Hub.PARAM_PREY_NAME) String preyName, OutputStream outputStream) throws IOException { log.info(Hub.SET_TARGET_SERVICE);//from w w w.j av a2 s . co m DataOutputStream dos = new DataOutputStream(outputStream); try { Arrow location = new Arrow(x, y, z); Target target = new Target(location, preyName); WorldHistory.Frozen frozen = worldHistory.setTarget(getEmail(session), target); dos.writeUTF(Hub.SUCCESS); dos.write(frozen.getWorld()); } catch (NoSessionException e) { dos.writeUTF(Hub.FAILURE); dos.writeUTF(Failure.SESSION.toString()); } }