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:de.ingrid.communication.authentication.BasicSchemeConnector.java
public boolean connect(Socket socket, String host, int port, String userName, String password) throws IOException { DataInputStream dataInput = createInput(socket); DataOutputStream dataOutput = createOutput(socket); StringBuffer errorBuffer = new StringBuffer(); String command = createConnectCommand(host, port, userName, password); errorBuffer.append(command);/*w w w . j a va2 s . c o m*/ dataOutput.write(command.getBytes()); dataOutput.flush(); boolean success = readMessageFromHttpProxy(dataInput, errorBuffer); if (!success) { if (LOG.isEnabledFor(Level.WARN)) { LOG.error(errorBuffer); } } return success; }
From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java
/** * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the given service URL. Currently supports * only HTTP./* w ww . ja va 2 s .c om*/ * * @param serviceUrl URL of the OCSP endpoint. * @param request an OCSP request object. * @return OCSP response encoded in ASN.1 structure. * @throws CertificateVerificationException * */ protected OCSPResp getOCSPResponse(String serviceUrl, OCSPReq request) throws CertificateVerificationException { try { //Todo: Use http client. byte[] array = request.getEncoded(); if (serviceUrl.startsWith("http")) { HttpURLConnection con; URL url = new URL(serviceUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); //Check errors in response: if (con.getResponseCode() / 100 != 2) { throw new CertificateVerificationException( "Error getting ocsp response." + "Response code is " + con.getResponseCode()); } //Get Response InputStream in = (InputStream) con.getContent(); return new OCSPResp(in); } else { throw new CertificateVerificationException("Only http is supported for ocsp calls"); } } catch (IOException e) { throw new CertificateVerificationException("Cannot get ocspResponse from url: " + serviceUrl, e); } }
From source file:org.apache.hadoop.hdfs.BlockReaderTestUtil.java
/** * Create a file of the given size filled with random data. * @return File data./*w w w .j a v a 2 s . c o m*/ */ public byte[] writeFile(Path filepath, int sizeKB) throws IOException { FileSystem fs = cluster.getFileSystem(); // Write a file with the specified amount of data DataOutputStream os = fs.create(filepath); byte data[] = new byte[1024 * sizeKB]; new Random().nextBytes(data); os.write(data); os.close(); return data; }
From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java
/** * Gets an ASN.1 encoded OCSP response (as defined in RFC 2560) from the given service URL. Currently supports * only HTTP./*from w w w . j a v a 2 s. c om*/ * * @param serviceUrl URL of the OCSP endpoint. * @param request an OCSP request object. * @return OCSP response encoded in ASN.1 structure. * @throws CertificateVerificationException * */ protected OCSPResp getOCSPResponce(String serviceUrl, OCSPReq request) throws CertificateVerificationException { try { //Todo: Use http client. byte[] array = request.getEncoded(); if (serviceUrl.startsWith("http")) { HttpURLConnection con; URL url = new URL(serviceUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); //Check errors in response: if (con.getResponseCode() / 100 != 2) { throw new CertificateVerificationException( "Error getting ocsp response." + "Response code is " + con.getResponseCode()); } //Get Response InputStream in = (InputStream) con.getContent(); return new OCSPResp(in); } else { throw new CertificateVerificationException("Only http is supported for ocsp calls"); } } catch (IOException e) { throw new CertificateVerificationException("Cannot get ocspResponse from url: " + serviceUrl, e); } }
From source file:de.kasoki.jfeedly.helper.HTTPConnections.java
private String sendRequest(String apiUrl, String parameters, boolean isAuthenticated, RequestType type, String contentType) {/*from ww w. ja v a 2s . c om*/ try { String url = this.jfeedlyHandler.getBaseUrl() + apiUrl.replaceAll(" ", "%20"); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("User-Agent", "jfeedly"); if (!contentType.isEmpty()) { con.setRequestProperty("Content-Type", contentType); } if (isAuthenticated) { con.setRequestProperty("Authorization", "OAuth " + this.jfeedlyHandler.getConnection().getAccessToken()); } // Send request header if (type == RequestType.POST) { con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream writer = new DataOutputStream(con.getOutputStream()); writer.write(parameters.getBytes()); writer.flush(); writer.close(); } else if (type == RequestType.GET) { con.setRequestMethod("GET"); } else if (type == RequestType.DELETE) { con.setRequestMethod("DELETE"); } else { System.err.println("jfeedly: Unkown RequestType " + type); } int responseCode = con.getResponseCode(); if (jfeedlyHandler.getVerbose()) { System.out.println("\n" + type + " to: " + url); System.out.println("content : " + parameters); System.out.println("\nResponse Code : " + responseCode); } BufferedReader in = null; // if error occurred if (responseCode >= 400) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String serverResponse = response.toString(); if (jfeedlyHandler.getVerbose()) { //print response String printableResponse = format(serverResponse); if (responseCode >= 400) { System.err.println(printableResponse); } else { System.out.println(printableResponse); } } return serverResponse; } catch (IOException ex) { ex.printStackTrace(); } return null; }
From source file:gobblin.metrics.reporter.util.SchemaRegistryVersionWriter.java
@Override public void writeSchemaVersioningInformation(Schema schema, DataOutputStream outputStream) throws IOException { String schemaId = this.schemaId.isPresent() ? this.schemaId.get() : this.getIdForSchema(schema); outputStream.writeByte(KafkaAvroSchemaRegistry.MAGIC_BYTE); try {//from ww w. j ava 2s . c o m outputStream.write(Hex.decodeHex(schemaId.toCharArray())); } catch (DecoderException exception) { throw new IOException(exception); } }
From source file:org.apache.cassandra.service.StorageProxy.java
/** * for each datacenter, send a message to one node to relay the write to other replicas *///from www. j a v a2s. c om private static void sendMessages(String localDataCenter, Map<String, Multimap<Message, InetAddress>> dcMessages, IWriteResponseHandler handler) throws IOException { for (Map.Entry<String, Multimap<Message, InetAddress>> entry : dcMessages.entrySet()) { String dataCenter = entry.getKey(); // send the messages corresponding to this datacenter for (Map.Entry<Message, Collection<InetAddress>> messages : entry.getValue().asMap().entrySet()) { Message message = messages.getKey(); // a single message object is used for unhinted writes, so clean out any forwards // from previous loop iterations message.removeHeader(RowMutation.FORWARD_HEADER); if (dataCenter.equals(localDataCenter) || StorageService.instance.useEfficientCrossDCWrites()) { // direct writes to local DC or old Cassadra versions for (InetAddress destination : messages.getValue()) MessagingService.instance().sendRR(message, destination, handler); } else { // Non-local DC. First endpoint in list is the destination for this group Iterator<InetAddress> iter = messages.getValue().iterator(); InetAddress target = iter.next(); // Add all the other destinations of the same message as a header in the primary message. while (iter.hasNext()) { InetAddress destination = iter.next(); // group all nodes in this DC as forward headers on the primary message ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); // append to older addresses byte[] previousHints = message.getHeader(RowMutation.FORWARD_HEADER); if (previousHints != null) dos.write(previousHints); dos.write(destination.getAddress()); message.setHeader(RowMutation.FORWARD_HEADER, bos.toByteArray()); } // send the combined message + forward headers MessagingService.instance().sendRR(message, target, handler); } } } }
From source file:com.cloudbase.CBHelperRequest.java
public void run() { HttpConnection hc = null;/*from w ww . j ava 2s . c om*/ InputStream is = null; try { hc = (HttpConnection) Connector.open(url + ";deviceside=true"); hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + CBHelperRequest.FIELD_BOUNDARY); hc.setRequestMethod(HttpConnection.POST); ByteArrayOutputStream request = new ByteArrayOutputStream();//hc.openOutputStream(); // Add your data Enumeration params = this.postData.keys(); while (params.hasMoreElements()) { String curKey = (String) params.nextElement(); request.write(this.getParameterPostData(curKey, (String) this.postData.get(curKey))); //entity.addPart(new CBStringPart(curKey, this.postData.get(curKey))); } // if we have file attachments then add each file to the multipart request if (this.files != null && this.files.size() > 0) { for (int i = 0; i < this.files.size(); i++) { CBHelperAttachment curFile = (CBHelperAttachment) this.files.elementAt(i); String name = curFile.getFileName(); request.write(this.getFilePostData(i, name, curFile.getFileData())); } } request.flush(); hc.setRequestProperty("Content-Length", "" + request.toByteArray().length); OutputStream requestStream = hc.openOutputStream(); requestStream.write(request.toByteArray()); requestStream.close(); is = hc.openInputStream(); // if we have a responder then parse the response data into the global CBHelperResponse object if (this.responder != null) { try { resp = new CBHelperResponse(); resp.setFunction(this.function); int ch; ByteArrayOutputStream response = new ByteArrayOutputStream(); while ((ch = is.read()) != -1) { response.write(ch); } // if it's a download then we need to save the file content into a temporary file in // application cache folder. Then return that file to the responder if (this.function.equals("download")) { String filePath = "file:///store/home/user/" + this.fileId; FileConnection fconn = (FileConnection) Connector.open(filePath); if (fconn.exists()) { fconn.delete(); } fconn.create(); DataOutputStream fs = fconn.openDataOutputStream(); fs.write(response.toByteArray()); fs.close(); fconn.close(); resp.setDownloadedFile(filePath); } else { // if it's not a download parse the JSON response and set all // the variables in the CBHelperResponse object String responseString = new String(response.toByteArray());//EntityUtils.toString(response.getEntity()); //System.out.println("Received response string: " + responseString); resp.setResponseDataString(responseString); JSONTokener tokener = new JSONTokener(responseString); JSONObject jsonOutput = new JSONObject(tokener); // Use the cloudbase.io deserializer to get the data in a Map<String, Object> // format. JSONObject outputData = jsonOutput.getJSONObject(this.function); resp.setData(outputData.get("message")); resp.setErrorMessage((String) outputData.get("error")); resp.setSuccess(((String) outputData.get("status")).equals("OK")); } //Application.getApplication().enterEventDispatcher(); responder.handleResponse(resp); } catch (Exception e) { System.out.println("Error while parsing response: " + e.getMessage()); e.printStackTrace(); } } } catch (Exception e) { System.out.println("Error while opening connection and sending data: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java
private String updateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null;//from w w w .ja va 2 s. com String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; try { 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); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(fileContents); wr.flush(); wr.close(); String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); LOG.debug("File updated : " + fileId); } catch (Exception e) { LOG.error("Could not update contents", e); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:org.getspout.spout.packet.PacketCacheFile.java
public void writeData(DataOutputStream output) throws IOException { PacketUtil.writeString(output, fileName); PacketUtil.writeString(output, plugin); output.writeBoolean(compressed);//w w w. j av a 2s. co m output.writeInt(fileData.length); output.write(fileData); }