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:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
@Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { try {/* w w w .ja v a 2 s . c om*/ final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer); String expandedUrl = formatter.format(url); String querystring = ""; if (!params.isEmpty()) { querystring = params.entrySet().stream().map( e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue())) .collect(Collectors.joining("&")); expandedUrl = expandedUrl.concat("?").concat(querystring); } StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ") .append(expandedUrl); URL requestUrl = new URL(expandedUrl); HttpURLConnection httpURLConnection; if (truststorePath != null && expandedUrl.startsWith("https://")) { httpURLConnection = openSecureConnection(requestUrl); } else { httpURLConnection = (HttpURLConnection) requestUrl.openConnection(); } callDump.append("\n ").append("Method: " + method); callDump.append("\n ").append("Connection timeout: " + connectionTimeout); callDump.append("\n ").append("Read timeout: " + readTimeout); httpURLConnection.setRequestMethod(method); httpURLConnection.setConnectTimeout(connectionTimeout); httpURLConnection.setReadTimeout(readTimeout); for (Entry<String, String> header : headers.entrySet()) { String k = formatter.format(header.getKey()); String v = formatter.format(header.getValue()); httpURLConnection.setRequestProperty(k, v); callDump.append("\n ").append("Header: " + k + "=" + v); if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) { body = querystring; } } if (sendGVBufferObject && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length)); callDump.append("\n ").append("Content-Length: " + requestData.length); callDump.append("\n ").append("Request body: binary"); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(requestData); dataOutputStream.flush(); dataOutputStream.close(); } else if (Objects.nonNull(body) && body.length() > 0) { String expandedBody = formatter.format(body); callDump.append("\n ").append("Request body: " + expandedBody); logger.debug(callDump.toString()); httpURLConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(expandedBody); outputStreamWriter.flush(); outputStreamWriter.close(); } httpURLConnection.connect(); InputStream responseStream = null; try { httpURLConnection.getResponseCode(); responseStream = httpURLConnection.getInputStream(); } catch (IOException connectionFail) { responseStream = httpURLConnection.getErrorStream(); } for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) { if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) { gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()), header.getValue().stream().collect(Collectors.joining(";"))); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { // No content gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode())); gvBuffer.setProperty(RESPONSE_MESSAGE, Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL")); httpURLConnection.disconnect(); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }
From source file:me.cybermaxke.merchants.v16r3.SMerchant.java
protected void sendUpdate() { if (this.customers.isEmpty()) { return;/* w w w . j a v a2 s . com*/ } 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:net.sf.keystore_explorer.crypto.x509.X509ExtensionSet.java
private void saveExtensions(Map<String, byte[]> extensions, DataOutputStream dos) throws IOException { dos.writeInt(extensions.size());/*from ww w. j a v a2 s .com*/ for (String oid : extensions.keySet()) { dos.writeInt(oid.length()); dos.writeChars(oid); byte[] value = extensions.get(oid); dos.writeInt(value.length); dos.write(value); } }
From source file:net.mohatu.bloocoin.miner.SubmitList.java
private void submit() { for (int i = 0; i < solved.size(); i++) { try {/*from www . j a va 2 s. c om*/ Socket sock = new Socket(this.url, this.port); String result = new String(); DataInputStream is = new DataInputStream(sock.getInputStream()); DataOutputStream os = null; BufferedReader in = new BufferedReader(new InputStreamReader(is)); solution = solved.get(i); hash = DigestUtils.sha512Hex(solution); String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}"; os = new DataOutputStream(sock.getOutputStream()); os.write(command.getBytes()); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } if (result.contains("\"success\": true")) { System.out.println("Result: Submitted"); Main.updateStatusText(solution + " submitted", Color.blue); Thread gc = new Thread(new Coins()); gc.start(); } else if (result.contains("\"success\": false")) { System.out.println("Result: Failed"); Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red); } is.close(); os.close(); os.flush(); sock.close(); } catch (UnknownHostException e) { e.printStackTrace(); Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red); } catch (IOException e) { e.printStackTrace(); Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red); } } Thread gc = new Thread(new Coins()); gc.start(); }
From source file:net.mohatu.bloocoin.miner.SubmitListClass.java
private void submit() { for (int i = 0; i < solved.size(); i++) { try {/*from w w w . ja v a 2s .co m*/ Socket sock = new Socket(this.url, this.port); String result = new String(); DataInputStream is = new DataInputStream(sock.getInputStream()); DataOutputStream os = null; BufferedReader in = new BufferedReader(new InputStreamReader(is)); solution = solved.get(i); hash = DigestUtils.sha512Hex(solution); String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}"; os = new DataOutputStream(sock.getOutputStream()); os.write(command.getBytes()); String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } if (result.contains("\"success\": true")) { System.out.println("Result: Submitted"); MainView.updateStatusText(solution + " submitted"); Thread gc = new Thread(new CoinClass()); gc.start(); } else if (result.contains("\"success\": false")) { System.out.println("Result: Failed"); MainView.updateStatusText("Submission of " + solution + " failed, already exists!"); } is.close(); os.close(); os.flush(); sock.close(); } catch (UnknownHostException e) { MainView.updateStatusText("Submission of " + solution + " failed, connection failed!"); } catch (IOException e) { MainView.updateStatusText("Submission of " + solution + " failed, connection failed!"); } } Thread gc = new Thread(new CoinClass()); gc.start(); }
From source file:com.jivesoftware.os.amza.service.replication.http.HttpRowsTaker.java
private void flushQueues(RingHost ringHost, Ackable ackable, long currentVersion) throws Exception { Map<VersionedPartitionName, RowsTakenPayload> rowsTaken; PongPayload pong;//from w w w . ja va 2 s .c om ackable.semaphore.acquire(Short.MAX_VALUE); try { rowsTaken = ackable.rowsTakenPayloads.getAndSet(Maps.newConcurrentMap()); pong = ackable.pongPayloads.getAndSet(null); } finally { ackable.semaphore.release(Short.MAX_VALUE); } if (rowsTaken != null && !rowsTaken.isEmpty()) { LOG.inc("flush>rowsTaken>pow>" + UIO.chunkPower(rowsTaken.size(), 0)); } if (rowsTaken != null && !rowsTaken.isEmpty() || pong != null) { flushExecutor.submit(() -> { try { String endpoint = "/amza/ackBatch"; ringClient.call("", new ConnectionDescriptorSelectiveStrategy( new HostPort[] { new HostPort(ringHost.getHost(), ringHost.getPort()) }), "ackBatch", httpClient -> { HttpResponse response = httpClient.postStreamableRequest(endpoint, out -> { try { DataOutputStream dos = new DataOutputStream(out); if (rowsTaken.isEmpty()) { dos.write((byte) 0); // hasMore for rowsTaken stream } else { for (Entry<VersionedPartitionName, RowsTakenPayload> e : rowsTaken .entrySet()) { dos.write((byte) 1); // hasMore for rowsTaken stream VersionedPartitionName versionedPartitionName = e.getKey(); byte[] bytes = versionedPartitionName.toBytes(); dos.writeShort(bytes.length); dos.write(bytes); RowsTakenPayload rowsTakenPayload = e.getValue(); bytes = rowsTakenPayload.ringMember.toBytes(); dos.writeShort(bytes.length); dos.write(bytes); dos.writeLong(rowsTakenPayload.takeSessionId); dos.writeLong(rowsTakenPayload.takeSharedKey); dos.writeLong(rowsTakenPayload.txId); dos.writeLong(rowsTakenPayload.leadershipToken); } dos.write((byte) 0); // EOS for rowsTaken stream } if (pong == null) { dos.write((byte) 0); // has pong } else { dos.write((byte) 1); // has pong byte[] bytes = pong.ringMember.toBytes(); dos.writeShort(bytes.length); dos.write(bytes); dos.writeLong(pong.takeSessionId); dos.writeLong(pong.takeSharedKey); } } catch (Exception x) { throw new RuntimeException("Failed while streaming ackBatch.", x); } finally { out.flush(); out.close(); } }, null); if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) { throw new NonSuccessStatusCodeException(response.getStatusCode(), response.getStatusReasonPhrase()); } Boolean result = (Boolean) conf.asObject(response.getResponseBody()); return new ClientResponse<>(result, true); }); } catch (Exception x) { LOG.warn("Failed to deliver acks for remote:{}", new Object[] { ringHost }, x); } finally { ackable.running.set(false); LOG.inc("flush>version>consume>" + name); synchronized (flushVersion) { if (currentVersion != flushVersion.get()) { flushVersion.notify(); } } } }); } else { ackable.running.set(false); LOG.inc("flush>version>consume>" + name); synchronized (flushVersion) { if (currentVersion != flushVersion.get()) { flushVersion.notify(); } } } }
From source file:com.skcraft.launcher.util.HttpRequest.java
/** * Execute the request./*from ww w . java 2s.c o m*/ * <p/> * After execution, {@link #close()} should be called. * * @return this object * @throws java.io.IOException on I/O error */ public HttpRequest execute() throws IOException { boolean successful = false; try { if (conn != null) { throw new IllegalArgumentException("Connection already executed"); } conn = (HttpURLConnection) reformat(url).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java) SKMCLauncher"); if (body != null) { conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Content-Length", Integer.toString(body.length)); conn.setDoInput(true); } for (Map.Entry<String, String> entry : headers.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } conn.setRequestMethod(method); conn.setUseCaches(false); conn.setDoOutput(true); conn.setReadTimeout(READ_TIMEOUT); conn.connect(); if (body != null) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(body); out.flush(); out.close(); } inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(); successful = true; } finally { if (!successful) { close(); } } return this; }
From source file:com.sk89q.squirrelid.util.HttpRequest.java
/** * Execute the request./*from w ww.ja v a 2 s . com*/ * <p/> * After execution, {@link #close()} should be called. * * @return this object * @throws java.io.IOException on I/O error */ public HttpRequest execute() throws IOException { boolean successful = false; try { if (conn != null) { throw new IllegalArgumentException("Connection already executed"); } conn = (HttpURLConnection) reformat(url).openConnection(); if (body != null) { conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Content-Length", Integer.toString(body.length)); conn.setDoInput(true); } for (Map.Entry<String, String> entry : headers.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } conn.setRequestMethod(method); conn.setUseCaches(false); conn.setDoOutput(true); conn.setReadTimeout(READ_TIMEOUT); conn.connect(); if (body != null) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(body); out.flush(); out.close(); } inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(); successful = true; } finally { if (!successful) { close(); } } return this; }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
private static byte[] createTcpMessage(byte[] msg) throws IOException { ByteArrayOutputStream bao = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bao); // 0 is pkiReq int msgType = 0; int len = msg.length; // return msg length = msg.length + 3; 1 byte version, 1 byte flags and // 1 byte message type dos.writeInt(len + 3);/* ww w.ja v a 2 s . c o m*/ dos.writeByte(10); dos.writeByte(0); // 1 if we should close, 0 otherwise dos.writeByte(msgType); dos.write(msg); dos.flush(); return bao.toByteArray(); }
From source file:com.anyonavinfo.commonuserregister.MainActivity.java
/** * Post?//from ww w .j ava 2 s. c o m */ public static String doPost(String urlStr, File file) { URL url = null; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; String BOUNDARY = UUID.randomUUID().toString(); // ?? String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestProperty("encoding", "utf-8"); 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?????? */ sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream IS = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = IS.read(bytes)) != -1) { dos.write(bytes, 0, len); } IS.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); } if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); Log.d("Sjj--->", len + ""); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { // if (e instanceof SocketTimeoutException) { return "SocketTimeoutException"; } else if (e instanceof UnknownHostException) { return "UnknownHostException"; } e.printStackTrace(); } finally { try { if (is != null) is.close(); if (baos != null) baos.close(); if (conn != null) { conn.disconnect(); } } catch (IOException e) { } } return null; }