List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:com.github.gcauchis.scalablepress4j.api.AbstractRestApi.java
/** * Call request for entity./*from ww w . j a v a 2 s. c om*/ * * @param <T> the generic type * @param url the url * @param requestMethod the http request method * @param request the request * @param responseType the response type * @param urlVariables the url variables * @return the response */ private <T> Response<T> forEntity(String url, String requestMethod, Object request, Class<T> responseType, Map<String, ?> urlVariables) { StringBuilder response = new StringBuilder(); HttpURLConnection connection = prepareConnection(url, requestMethod, urlVariables); try { // // Send request DataOutputStream wr = null; if (request != null) { String content = objectMapper.writeValueAsString(request); wr = new DataOutputStream(connection.getOutputStream()); wr.write(content.getBytes(StandardCharsets.UTF_8)); wr.flush(); } // Get Response BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } if (wr != null) { wr.close(); } rd.close(); log.trace("Response {}", response); } catch (IOException e) { log.error("Fail to send request", e); ErrorResponse errorResponse = new ErrorResponse(); try { errorResponse.setStatusCode(connection.getResponseCode() + ""); errorResponse.setMessage(connection.getResponseMessage()); } catch (IOException e1) { errorResponse.setStatusCode("500"); errorResponse.setMessage(e.getMessage()); } throw new ScalablePressBadRequestException(errorResponse); } Response<T> responseEntity = new Response<>(); responseEntity.headers = connection.getHeaderFields(); log.debug("Header: {}", responseEntity.headers); try { responseEntity.body = objectMapper.readValue(response.toString(), responseType); } catch (IOException e) { log.error("Fail to parse response", e); ErrorResponse errorResponse = null; try { log.error("Response error: {} {}", connection.getResponseCode(), connection.getResponseMessage()); errorResponse = objectMapper.readValue(response.toString(), ErrorResponse.class); } catch (IOException ioe) { log.error("Fail to parse error", ioe); } if (errorResponse != null) { log.error("Response error object: {}", errorResponse); throw new ScalablePressBadRequestException(errorResponse); } } return responseEntity; }
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;// www . j av a 2 s . c om 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:hd3gtv.embddb.network.DataBlock.java
byte[] getBytes(Protocol protocol) throws IOException { checkIfNotEmpty();/*from w w w . j ava 2 s . co m*/ ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE); DataOutputStream dos = new DataOutputStream(byte_array_out_stream); dos.write(Protocol.APP_SOCKET_HEADER_TAG); dos.writeInt(Protocol.VERSION); /** * Start header name */ dos.writeByte(0); byte[] request_name_data = request_name.getBytes(Protocol.UTF8); dos.writeInt(request_name_data.length); dos.write(request_name_data); /** * Start datas payload */ dos.writeByte(1); /** * Get datas from zip */ ZipOutputStream zos = new ZipOutputStream(dos); zos.setLevel(3); entries.forEach(entry -> { try { entry.toZip(zos); } catch (IOException e) { log.error("Can't add to zip", e); } }); zos.flush(); zos.finish(); zos.close(); dos.flush(); dos.close(); byte[] result = byte_array_out_stream.toByteArray(); if (log.isTraceEnabled()) { log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result)); } return result; }
From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java
/** * Executes a multipart form upload to the S3 Bucket as described in * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>. * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever * bytes are written to the outgoing connection. May be null. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error *///from w w w .ja va 2s .co m public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener) throws IOException, ClientProtocolException { //unfortunately, we can't use Unirest to execute the call, because there is no support //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26 int bufferSize = 1024; //opening a connection to the S3 Bucket HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection(); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setChunkedStreamingMode(bufferSize); urlConnection.setRequestProperty("Connection", "Keep-Alive"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); String boundary = "*****"; urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //writing the request headers DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); String newline = "\r\n"; String twoHyphens = "--"; dos.writeBytes(twoHyphens + boundary + newline); String attachmentName = "file"; String attachmentFileName = "file"; dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + newline); dos.writeBytes(newline); //sending the actual file byte[] buf = new byte[bufferSize]; FileInputStream fis = new FileInputStream(file); long totalBytes = fis.getChannel().size(); long writtenBytes = 0; int len; while ((len = fis.read(buf)) != -1) { dos.write(buf); writtenBytes += len; s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes, (float) ((double) writtenBytes / totalBytes))); if (interrupt) { fis.close(); dos.close(); return; } } fis.close(); //finish the call dos.writeBytes(newline); dos.writeBytes(twoHyphens + boundary + twoHyphens + newline); dos.close(); urlConnection.disconnect(); }
From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java
private RestResponse sendPostForAcquisitionSearch(String url, String urlParameters) { StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); String postResponse = null;/*from w ww . ja v a 2 s .c om*/ try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); postResponse = response.toString(); } catch (Exception e) { e.printStackTrace(); } RestResponse response = new RestResponse(); response.setContentType("text/html; charset=utf-8"); response.setResponseBody(postResponse); response.setResponse(httpResponse); return response; }
From source file:cn.ac.ncic.mastiff.io.coding.DeltaBinaryPackingStringReader.java
@Override public byte[] ensureDecompressed() throws IOException { System.out.println("280 inBuf.length " + inBuf.getLength()); FlexibleEncoding.Parquet.DeltaByteArrayReader reader = new FlexibleEncoding.Parquet.DeltaByteArrayReader(); DataOutputBuffer transfer = new DataOutputBuffer(); transfer.write(inBuf.getData(), 12, inBuf.getLength() - 12); byte[] data = transfer.getData(); System.out.println("286 byte [] data " + data.length + " numPairs " + numPairs); inBuf.close();//w w w . j a v a 2 s.com Binary[] bin = new Utils().readData(reader, data, numPairs); System.out.println("2998 Binary[] bin " + bin.length); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); DataOutputStream dos1 = new DataOutputStream(bos1); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); DataOutputStream dos2 = new DataOutputStream(bos2); // DataOutputBuffer decoding = new DataOutputBuffer(); // DataOutputBuffer offset = new DataOutputBuffer(); dos1.writeInt(decompressedSize); dos1.writeInt(numPairs); dos1.writeInt(startPos); int dataoffset = 12; String str; for (int i = 0; i < numPairs; i++) { str = bin[i].toStringUsingUTF8(); dos1.writeUTF(str); dataoffset = dos1.size(); dos2.writeInt(dataoffset); } System.out.println("315 offset.size() " + bos2.size() + " decoding.szie " + bos2.toByteArray().length); System.out.println("316 dataoffet " + dataoffset); dos1.write(bos2.toByteArray(), 0, bos2.size()); inBuf.close(); System.out.println("316 bos1 " + bos1.toByteArray().length + " " + bos1.size()); byte[] bytes = bos1.toByteArray(); dos2.close(); bos2.close(); bos1.close(); dos1.close(); return bytes; }
From source file:fedora.test.api.TestRESTAPI.java
public void testAddDatastream() throws Exception { // inline (X) datastream String xmlData = "<foo>bar</foo>"; String dsPath = "/objects/" + pid + "/datastreams/FOO"; url = dsPath + "?controlGroup=X&dsLabel=bar"; assertEquals(SC_UNAUTHORIZED, post(xmlData, false).getStatusCode()); HttpResponse response = post(xmlData, true); assertEquals(SC_CREATED, response.getStatusCode()); Header locationHeader = response.getResponseHeader("location"); assertNotNull(locationHeader);//from w ww .j av a 2 s . c o m assertEquals(new URL(url.substring(0, url.indexOf('?'))).toString(), locationHeader.getValue()); assertEquals("text/xml", response.getResponseHeader("Content-Type").getValue()); url = dsPath + "?format=xml"; assertEquals(response.getResponseBodyString(), get(true).getResponseBodyString()); // managed (M) datastream String mimeType = "text/plain"; dsPath = "/objects/" + pid + "/datastreams/BAR"; url = dsPath + "?controlGroup=M&dsLabel=bar&mimeType=" + mimeType; File temp = File.createTempFile("test", null); DataOutputStream os = new DataOutputStream(new FileOutputStream(temp)); os.write(42); os.close(); assertEquals(SC_UNAUTHORIZED, post(temp, false).getStatusCode()); response = post(temp, true); assertEquals(SC_CREATED, response.getStatusCode()); locationHeader = response.getResponseHeader("location"); assertNotNull(locationHeader); assertEquals(new URL(url.substring(0, url.indexOf('?'))).toString(), locationHeader.getValue()); assertEquals("text/xml", response.getResponseHeader("Content-Type").getValue()); url = dsPath + "?format=xml"; assertEquals(response.getResponseBodyString(), get(true).getResponseBodyString()); Datastream ds = apim.getDatastream(pid.toString(), "BAR", null); assertEquals(ds.getMIMEType(), mimeType); }
From source file:fedora.test.api.TestRESTAPI.java
public void testModifyDatastreamByReference() throws Exception { // Create BAR datastream url = String.format("/objects/%s/datastreams/BAR?controlGroup=M&dsLabel=bar", pid.toString()); File temp = File.createTempFile("test", null); DataOutputStream os = new DataOutputStream(new FileOutputStream(temp)); os.write(42);// w w w . j ava 2 s .c o m os.close(); assertEquals(SC_UNAUTHORIZED, post(temp, false).getStatusCode()); assertEquals(SC_CREATED, post(temp, true).getStatusCode()); // Update the content of the BAR datastream (using PUT) url = String.format("/objects/%s/datastreams/BAR", pid.toString()); assertEquals(SC_UNAUTHORIZED, put(temp, false).getStatusCode()); HttpResponse response = put(temp, true); assertEquals(SC_OK, response.getStatusCode()); assertEquals("text/xml", response.getResponseHeader("Content-Type").getValue()); url = url + "?format=xml"; assertEquals(response.getResponseBodyString(), get(true).getResponseBodyString()); // Ensure 404 on attempt to update BOGUS_DS via PUT url = "/objects/" + pid + "/datastreams/BOGUS_DS"; assertEquals(SC_NOT_FOUND, put(temp, true).getStatusCode()); // Update the content of the BAR datastream (using POST) url = String.format("/objects/%s/datastreams/BAR", pid.toString()); response = post(temp, true); assertEquals(SC_CREATED, response.getStatusCode()); Header locationHeader = response.getResponseHeader("location"); assertNotNull(locationHeader); assertEquals(url, locationHeader.getValue()); assertEquals("text/xml", response.getResponseHeader("Content-Type").getValue()); url = url + "?format=xml"; assertEquals(response.getResponseBodyString(), get(true).getResponseBodyString()); // Update the label of the BAR datastream String newLabel = "tikibar"; url = String.format("/objects/%s/datastreams/BAR?dsLabel=%s", pid.toString(), newLabel); assertEquals(SC_UNAUTHORIZED, put(false).getStatusCode()); assertEquals(SC_OK, put(true).getStatusCode()); assertEquals(newLabel, apim.getDatastream(pid.toString(), "BAR", null).getLabel()); // Update the location of the EXTDS datastream (E type datastream) String newLocation = "http://" + getHost() + ":" + getPort() + "/" + getFedoraAppServerContext() + "/get/demo:REST/DC"; url = String.format("/objects/%s/datastreams/EXTDS?dsLocation=%s", pid.toString(), newLocation); assertEquals(SC_UNAUTHORIZED, put(false).getStatusCode()); assertEquals(SC_OK, put(true).getStatusCode()); assertEquals(newLocation, apim.getDatastream(pid.toString(), "EXTDS", null).getLocation()); String dcDS = new String(apia.getDatastreamDissemination(pid.toString(), "DC", null).getStream()); String extDS = new String(apia.getDatastreamDissemination(pid.toString(), "EXTDS", null).getStream()); assertEquals(dcDS, extDS); // Update DS1 by reference (X type datastream) // Error expected because attempting to access internal DS with API-A auth on url = String.format("/objects/%s/datastreams/DS1?dsLocation=%s", pid.toString(), newLocation); assertEquals(SC_UNAUTHORIZED, put(false).getStatusCode()); assertEquals(SC_INTERNAL_SERVER_ERROR, put(true).getStatusCode()); // Update DS1 by reference (X type datastream) - Success expected newLocation = getBaseURL() + "/ri/index.xsl"; url = String.format("/objects/%s/datastreams/DS1?dsLocation=%s", pid.toString(), newLocation); assertEquals(SC_UNAUTHORIZED, put(false).getStatusCode()); assertEquals(SC_OK, put(true).getStatusCode()); }
From source file:org.wso2.carbon.identity.authenticator.mobileconnect.MobileConnectAuthenticator.java
/** * msisdn based Discovery (Developer app uses Discovery API to send msisdn). *///from w w w . j av a2s . c o m private HttpURLConnection discoveryProcess(String authorizationHeader, String msisdn, Map<String, String> authenticationProperties) throws IOException { //prepare query parameters String queryParameters = MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_REDIRECT_URL + "=" + getCallbackUrl(authenticationProperties); //create url to make the API call String url = MobileConnectAuthenticatorConstants.DISCOVERY_API_URL + "?" + queryParameters; //body parameters for the API call String data = "MSISDN=" + msisdn; URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod(MobileConnectAuthenticatorConstants.POST_METHOD); connection.setRequestProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_AUTHORIZATION, authorizationHeader); connection.setRequestProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_ACCEPT, MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_ACCEPT_VALUE); connection.setDoOutput(true); //write data to the body of the connection DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(data); outputStream.close(); return connection; }
From source file:net.mohatu.bloocoin.miner.SubmitListClass.java
private void submit() { for (int i = 0; i < solved.size(); i++) { try {/* w w w .ja va 2 s .c o 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(); }