List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:com.adaptris.security.StdOutput.java
/** * Return the encrypted message ready for immediate writing to file. * //from w w w.ja va 2 s. c om * @return the bytes ready for writing. * @throws AdaptrisSecurityException if an error occurs */ private byte[] formatBase64() throws EncryptException { DataOutputStream out = null; ByteArrayOutputStream byteStream = null; byte[] returnBytes = null; try { byteStream = new ByteArrayOutputStream(); out = new DataOutputStream(byteStream); write(out, getSessionVector()); write(out, getSessionKey()); write(out, getEncryptedData(false) == null ? getDecryptedData(false) : getEncryptedData(false)); write(out, getSignature()); returnBytes = Base64.encodeBase64(byteStream.toByteArray()); } catch (Exception e) { throw new EncryptException(e); } finally { try { if (out != null) { out.close(); } if (byteStream != null) { byteStream.close(); } } catch (Exception ignored) { ; } } return returnBytes; }
From source file:com.kyne.webby.rtk.web.WebServer.java
@SuppressWarnings("unchecked") public void printJSON(final Map<String, Object> data, final Socket clientSocket) { try {/*from ww w.j av a 2s . c o m*/ final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); out.writeBytes("HTTP/1.1 200 OK\r\n"); out.writeBytes("Content-Type: application/json; charset=utf-8\r\n"); out.writeBytes("Cache-Control: no-cache \r\n"); out.writeBytes("Server: Bukkit Webby\r\n"); out.writeBytes("Connection: Close\r\n\r\n"); final JSONObject json = new JSONObject(); json.putAll(data); out.writeBytes(json.toJSONString()); out.flush(); out.close(); } catch (final SocketException e) { /* .. */ } catch (final Exception e) { LogHelper.error(e.getMessage(), e); } }
From source file:TimestreamsTests.java
/** * Performs HTTP post for a given URL/* w w w . j ava2s. c o m*/ * * @param url * is the URL to get * @param params * is a URL encoded string in the form x=y&a=b... * @return a String with the contents of the get */ private Map<String, List<String>> doPost(URL url, String params) { HttpURLConnection connection; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length)); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); Map<String, List<String>> responseHeaderFields = connection.getHeaderFields(); System.out.println(responseHeaderFields); if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); System.out.println(response); } return responseHeaderFields; } catch (IOException e1) { fail("Post " + url + " failed: " + e1.getLocalizedMessage()); } return null; }
From source file:IntSort.java
public void writeStream(String[] sData, boolean[] bData, int[] iData) { try {/*w w w . j a v a 2 s . c om*/ // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutputStream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream(strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) { // Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } }
From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java
boolean uploadUserInfoV4() { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/* www . ja v a2 s. c o m*/ URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonUser; if (null != (jsonUser = getUserJSON())) { try { String deviceId = userId; dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n"); dos.writeBytes( fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n"); dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(fieldSep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { // TODO: Record somehow that data was uploaded successfully result = true; } } else { result = false; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.plancake.api.client.PlancakeApiClient.java
/** * @param String request/*ww w . j a v a 2 s . c o m*/ * @param String httpMethod * @return String */ private String getResponse(String request, String httpMethod) throws MalformedURLException, IOException, PlancakeApiException { if (!(httpMethod.equals("GET")) && !(httpMethod.equals("POST"))) { throw new PlancakeApiException("httpMethod must be either GET or POST"); } String urlParameters = ""; if (httpMethod == "POST") { String[] requestParts = request.split("\\?"); request = requestParts[0]; urlParameters = requestParts[1]; } URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(httpMethod); if (httpMethod == "POST") { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { connection.setRequestProperty("Content-Type", "text/plain"); } connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setUseCaches(false); connection.connect(); if (httpMethod == "POST") { DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); } StringBuffer text = new StringBuffer(); InputStreamReader in = new InputStreamReader((InputStream) connection.getContent()); BufferedReader buff = new BufferedReader(in); String line = buff.readLine(); while (line != null) { text.append(line + "\n"); line = buff.readLine(); } String response = text.toString(); if (response.length() == 0) { throw new PlancakeApiException("the response is empty"); } connection.disconnect(); return response; }
From source file:net.mybox.mybox.ClientStatus.java
private synchronized boolean updateLastSync() { lastSync = (new Date()).getTime(); try {//from w w w . j av a2 s. c o m FileOutputStream fos = new FileOutputStream(lastSyncFile); DataOutputStream dos = new DataOutputStream(fos); dos.writeLong(lastSync); dos.close(); } catch (Exception e) { return false; } return true; }
From source file:com.momock.http.HttpSession.java
void writeHeaders() { try {/* w w w .j av a 2 s . co m*/ DataOutputStream dout = new DataOutputStream(new FileOutputStream(fileInfo)); int headerCount = headers.size(); dout.writeInt(headerCount); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); dout.writeUTF(key); dout.writeInt(values.size()); for (String value : values) { dout.writeUTF(value); } } dout.close(); } catch (IOException e) { Logger.error(e); } }
From source file:com.haulmont.cuba.core.app.filestorage.amazon.AmazonS3FileStorage.java
@Override public long saveStream(FileDescriptor fileDescr, InputStream inputStream) throws FileStorageException { Preconditions.checkNotNullArgument(fileDescr.getSize()); int chunkSize = amazonS3Config.getChunkSize(); long fileSize = fileDescr.getSize(); URL amazonUrl = getAmazonUrl(fileDescr); // set the markers indicating we're going to send the upload as a series // of chunks: // -- 'x-amz-content-sha256' is the fixed marker indicating chunked // upload // -- 'content-length' becomes the total size in bytes of the upload // (including chunk headers), // -- 'x-amz-decoded-content-length' is used to transmit the actual // length of the data payload, less chunk headers Map<String, String> headers = new HashMap<>(); headers.put("x-amz-storage-class", "REDUCED_REDUNDANCY"); headers.put("x-amz-content-sha256", AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256); headers.put("content-encoding", "aws-chunked"); headers.put("x-amz-decoded-content-length", "" + fileSize); AWS4SignerForChunkedUpload signer = new AWS4SignerForChunkedUpload(amazonUrl, "PUT", "s3", amazonS3Config.getRegionName()); // how big is the overall request stream going to be once we add the signature // 'headers' to each chunk? long totalLength = AWS4SignerForChunkedUpload.calculateChunkedContentLength(fileSize, chunkSize); headers.put("content-length", "" + totalLength); String authorization = signer.computeSignature(headers, null, // no query parameters AWS4SignerForChunkedUpload.STREAMING_BODY_SHA256, amazonS3Config.getAccessKey(), amazonS3Config.getSecretAccessKey()); // place the computed signature into a formatted 'Authorization' header // and call S3 headers.put("Authorization", authorization); // start consuming the data payload in blocks which we subsequently chunk; this prefixes // the data with a 'chunk header' containing signature data from the prior chunk (or header // signing, if the first chunk) plus length and other data. Each completed chunk is // written to the request stream and to complete the upload, we send a final chunk with // a zero-length data payload. try {//from www .j ava 2s . c o m // first set up the connection HttpURLConnection connection = HttpUtils.createHttpConnection(amazonUrl, "PUT", headers); // get the request stream and start writing the user data as chunks, as outlined // above; int bytesRead; byte[] buffer = new byte[chunkSize]; DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); //guarantees that it will read as many bytes as possible, this may not always be the case for //subclasses of InputStream while ((bytesRead = IOUtils.read(inputStream, buffer, 0, chunkSize)) > 0) { // process into a chunk byte[] chunk = signer.constructSignedChunk(bytesRead, buffer); // send the chunk outputStream.write(chunk); outputStream.flush(); } // last step is to send a signed zero-length chunk to complete the upload byte[] finalChunk = signer.constructSignedChunk(0, buffer); outputStream.write(finalChunk); outputStream.flush(); outputStream.close(); // make the call to Amazon S3 HttpUtils.HttpResponse httpResponse = HttpUtils.executeHttpRequest(connection); if (!httpResponse.isStatusOk()) { String message = String.format("Could not save file %s. %s", getFileName(fileDescr), getInputStreamContent(httpResponse)); throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, message); } } catch (IOException e) { throw new RuntimeException("Error when sending chunked upload request", e); } return fileDescr.getSize(); }
From source file:GUI.Starts.java
private void predict() { int i, predict_probability = 0; svm_parameter param = new svm_parameter(); param.svm_type = svm_parameter.EPSILON_SVR; param.kernel_type = svm_parameter.LINEAR; param.coef0 = 0;// w w w.j av a 2 s.co m param.degree = 3; param.gamma = 0; param.nu = 0.5; param.cache_size = 40; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; try { BufferedReader input = new BufferedReader(new FileReader("astra.test.data")); DataOutputStream output = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("astra.out"))); svm_model model = svm.svm_load_model("astra.model"); if (predict_probability == 1) { if (svm.svm_check_probability_model(model) == 0) { System.err.print("Model does not support probabiliy estimates\n"); System.exit(1); } } else if (svm.svm_check_probability_model(model) != 0) { System.out.print("Model supports probability estimates, but disabled in prediction.\n"); } Predict.predict(input, output, model, predict_probability); input.close(); output.close(); } catch (FileNotFoundException e) { System.out.println("File doesnt exitst"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array out of bounds"); } catch (IOException e) { System.out.println("Something went wrong"); } // System.out.println(data); splitArray = data.split(","); for (int j = 0; j < splitArray.length; j++) { doubleArray[j] = Double.parseDouble(splitArray[j]); } splitTarget = targets.replace("null", "").split(","); for (int j = 0; j < splitTarget.length; j++) { doubleTarget[j] = Double.parseDouble(splitTarget[j]); } System.out.println(doubleTarget[3]); }