List of usage examples for java.io DataOutputStream write
public synchronized void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to the underlying output stream. From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }//w w w . j ava2 s . c om int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }
From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java
private void cacheCrawlHistoryLog(File localCacheDir, long timestamp) throws IOException { SequenceFile.Reader reader = null; Path mapFilePath = new Path(_remoteDataDirectory, CRAWL_HISTORY_HDFS_LOGFILE_PREFIX + timestamp); Path indexFilePath = new Path(mapFilePath, "index"); Path dataFilePath = new Path(mapFilePath, "data"); File cacheFilePath = new File(localCacheDir, CRAWL_HISTORY_HDFS_LOGFILE_PREFIX + timestamp); SequenceFile.Reader indexReader = new SequenceFile.Reader(_remoteFileSystem, dataFilePath, CrawlEnvironment.getHadoopConfig()); ValueBytes valueBytes = indexReader.createValueBytes(); DataOutputBuffer keyBytes = new DataOutputBuffer(); DataInputBuffer keyBuffer = new DataInputBuffer(); DataOutputBuffer finalOutputStream = new DataOutputBuffer(); DataOutputBuffer uncompressedValueBytes = new DataOutputBuffer(); URLFP fp = new URLFP(); try {//w ww.j ava2 s. c o m while (indexReader.nextRaw(keyBytes, valueBytes) != -1) { keyBuffer.reset(keyBytes.getData(), 0, keyBytes.getLength()); // read fingerprint ... fp.readFields(keyBuffer); // write hash only finalOutputStream.writeLong(fp.getUrlHash()); uncompressedValueBytes.reset(); // write value bytes to intermediate buffer ... valueBytes.writeUncompressedBytes(uncompressedValueBytes); // write out uncompressed length WritableUtils.writeVInt(finalOutputStream, uncompressedValueBytes.getLength()); // write out bytes finalOutputStream.write(uncompressedValueBytes.getData(), 0, uncompressedValueBytes.getLength()); } // delete existing ... cacheFilePath.delete(); // compute crc ... CRC32 crc = new CRC32(); crc.update(finalOutputStream.getData(), 0, finalOutputStream.getLength()); // open final output stream DataOutputStream fileOutputStream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(cacheFilePath))); try { fileOutputStream.writeLong(crc.getValue()); fileOutputStream.write(finalOutputStream.getData(), 0, finalOutputStream.getLength()); fileOutputStream.flush(); } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); fileOutputStream.close(); fileOutputStream = null; cacheFilePath.delete(); throw e; } finally { if (fileOutputStream != null) { fileOutputStream.close(); } } } finally { if (indexReader != null) { indexReader.close(); } } }
From source file:UploadTest.java
@Test public void java_lib_put() { try {/* www . j ava 2 s .c om*/ URL myurl; HttpURLConnection conn; String port = "9000"; String user = "edoweb-admin"; String password = "admin"; String encoding = Base64.encodeBase64String((user + ":" + password).getBytes()); String boundary = "" + System.currentTimeMillis() + ""; String crlf = "\r\n"; String twoHyphens = "--"; String attachmentName = "data"; File uploadFile = new File("/home/raul/test/frl%3A6376984/123.txt"); String attachmentFileName = uploadFile.getName(); DataOutputStream request; myurl = new URL("http://localhost:9000/resource/frl:6376984/data"); System.out.println(myurl.toString()); conn = (HttpURLConnection) myurl.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Authorization", " Basic " + encoding); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Content-Length", String.valueOf(uploadFile.length())); conn.setRequestProperty("Accept", "*/*"); conn.connect(); FileInputStream fis = new FileInputStream(uploadFile); // BufferedInputStream buf = new BufferedInputStream(fis); request = new DataOutputStream(conn.getOutputStream()); request.writeBytes(twoHyphens + boundary + crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf); request.writeBytes("Content-Type: application/pdf"); request.writeBytes(crlf); byte[] streamFileBytes = new byte[4096]; int bytesRead = -1; while ((bytesRead = fis.read(streamFileBytes)) != -1) { request.write(streamFileBytes, 0, bytesRead); } request.writeBytes(crlf); request.writeBytes(twoHyphens + boundary + crlf); request.close(); conn.disconnect(); System.out.println(conn.getResponseCode()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.webarch.common.net.http.HttpService.java
/** * /*from www . j a v a 2 s. co m*/ * * @param media_id ?ID * @param identity * @param filepath ?(????) * @return ?(???)error */ public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) { String mediaLocalURL = "error"; InputStream inputStream = null; FileOutputStream fileOutputStream = null; DataOutputStream dataOutputStream = null; try { URL downLoadURL = new URL(requestUrl); // URL HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection(); //? connection.setRequestMethod("GET"); // connection.connect(); //?,?text,json if (connection.getContentType().equalsIgnoreCase("text/plain")) { // BufferedReader???URL? inputStream = connection.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET)); String valueString = null; StringBuffer bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } inputStream.close(); String errMsg = bufferRes.toString(); JSONObject jsonObject = JSONObject.parseObject(errMsg); logger.error("???" + (jsonObject.getInteger("errcode"))); mediaLocalURL = "error"; } else { BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); String ds = connection.getHeaderField("Content-disposition"); //?? String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1); //?--?? String preffix = fullName.substring(0, fullName.lastIndexOf(".")); //? String suffix = fullName.substring(preffix.length() + 1); // String length = connection.getHeaderField("Content-Length"); // String type = connection.getHeaderField("Content-Type"); // byte[] buffer = new byte[8192]; // 8k int count = 0; mediaLocalURL = filepath + File.separator; File file = new File(mediaLocalURL); if (!file.exists()) { file.mkdirs(); } File mediaFile = new File(mediaLocalURL, fullName); fileOutputStream = new FileOutputStream(mediaFile); dataOutputStream = new DataOutputStream(fileOutputStream); while ((count = bis.read(buffer)) != -1) { dataOutputStream.write(buffer, 0, count); } //? mediaLocalURL += fullName; bis.close(); dataOutputStream.close(); fileOutputStream.close(); } } catch (IOException e) { logger.error("?", e); } return mediaLocalURL; }
From source file:ffx.xray.parsers.MTZWriter.java
/** * <p>/*from www . j av a 2s . c o m*/ * write</p> */ public void write() { ByteOrder byteOrder = ByteOrder.nativeOrder(); FileOutputStream fileOutputStream; DataOutputStream dataOutputStream; try { if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(format("\n Writing MTZ HKL file: \"%s\"\n", fileName)); logger.info(sb.toString()); } fileOutputStream = new FileOutputStream(fileName); dataOutputStream = new DataOutputStream(fileOutputStream); byte bytes[] = new byte[80]; int offset = 0; int writeLen = 0; int iMapData; float fMapData; // Header. StringBuilder sb = new StringBuilder(); sb.append("MTZ "); dataOutputStream.writeBytes(sb.toString()); // Header offset. int headerOffset = n * nCol + 21; ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); byteBuffer.order(byteOrder).putInt(headerOffset); // Machine code: double, float, int, uchar // 0x4441 for LE, 0x1111 for BE if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { iMapData = 0x4441; } else { iMapData = 0x1111; } byteBuffer.order(byteOrder).putInt(iMapData); dataOutputStream.write(bytes, offset, 8); sb = new StringBuilder(); sb.append(" "); sb.setLength(68); dataOutputStream.writeBytes(sb.toString()); // Data. Vector<String> colname = new Vector<>(nCol); char colType[] = new char[nCol]; double res[] = new double[2]; res[0] = Double.POSITIVE_INFINITY; res[1] = Double.NEGATIVE_INFINITY; float colMinMax[][] = new float[nCol][2]; for (int i = 0; i < nCol; i++) { colMinMax[i][0] = Float.POSITIVE_INFINITY; colMinMax[i][1] = Float.NEGATIVE_INFINITY; } ReflectionSpline sigmaASpline = new ReflectionSpline(reflectionList, refinementData.sigmaa.length); int col = 0; colname.add("H"); colType[col++] = 'H'; colname.add("K"); colType[col++] = 'H'; colname.add("L"); colType[col++] = 'H'; writeLen += 12; if (mtzType != MTZType.FCONLY) { colname.add("FO"); colType[col++] = 'F'; colname.add("SIGFO"); colType[col++] = 'Q'; colname.add("FreeR"); colType[col++] = 'I'; writeLen += 12; } if (mtzType != MTZType.DATAONLY) { colname.add("Fs"); colType[col++] = 'F'; colname.add("PHIFs"); colType[col++] = 'P'; colname.add("Fc"); colType[col++] = 'F'; colname.add("PHIFc"); colType[col++] = 'P'; writeLen += 16; } if (mtzType == MTZType.ALL) { colname.add("FOM"); colType[col++] = 'W'; colname.add("PHIW"); colType[col++] = 'P'; colname.add("SigmaAs"); colType[col++] = 'F'; colname.add("SigmaAw"); colType[col++] = 'Q'; colname.add("FWT"); colType[col++] = 'F'; colname.add("PHWT"); colType[col++] = 'P'; colname.add("DELFWT"); colType[col++] = 'F'; colname.add("PHDELWT"); colType[col++] = 'P'; writeLen += 32; } for (HKL ih : reflectionList.hkllist) { col = 0; int i = ih.index(); // Skip the 0 0 0 reflection. if (ih.h() == 0 && ih.k() == 0 && ih.l() == 0) { continue; } double ss = Crystal.invressq(crystal, ih); res[0] = min(ss, res[0]); res[1] = max(ss, res[1]); // HKL first (3) fMapData = ih.h(); colMinMax[col][0] = min(fMapData, colMinMax[0][0]); colMinMax[col][1] = max(fMapData, colMinMax[0][1]); byteBuffer.rewind(); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = ih.k(); colMinMax[col][0] = min(fMapData, colMinMax[1][0]); colMinMax[col][1] = max(fMapData, colMinMax[1][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = ih.l(); colMinMax[col][0] = min(fMapData, colMinMax[2][0]); colMinMax[col][1] = max(fMapData, colMinMax[2][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; if (mtzType != MTZType.FCONLY) { // F/sigF (2) fMapData = (float) refinementData.getF(i); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) refinementData.getSigF(i); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; // Free R (1) fMapData = (float) refinementData.getFreeR(i); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; } if (mtzType == MTZType.FCONLY) { // Fs (2) fMapData = (float) refinementData.fsF(i); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.fsPhi(i)); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; // Fc (unscaled!) (2) fMapData = (float) refinementData.fcF(i); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) Math.toDegrees(refinementData.fcPhi(i)); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; } if (mtzType == MTZType.ALL) { // Fs (2) fMapData = (float) refinementData.fsF(i); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.fsPhi(i)); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; // Fctot (2) fMapData = (float) refinementData.fcTotF(i); if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.fcTotPhi(i)); if (!isNaN(fMapData)) { colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]); colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; // FOM/phase (2) fMapData = (float) refinementData.fomphi[i][0]; if (!isNaN(fMapData)) { colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]); colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.fomphi[i][1]); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; // Spline setup. double fh = spline.f(ss, refinementData.spline); double sa = sigmaASpline.f(ss, refinementData.sigmaa); double wa = sigmaASpline.f(ss, refinementData.sigmaw); // sigmaA/w (2) fMapData = (float) sa; if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) wa; if (!isNaN(fMapData)) { colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); } byteBuffer.order(byteOrder).putFloat(fMapData); col++; // Map coeffs (4). fMapData = (float) refinementData.FoFc2F(i); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.FoFc2Phi(i)); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) refinementData.foFc1F(i); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; fMapData = (float) toDegrees(refinementData.foFc1Phi(i)); colMinMax[col][0] = min(fMapData, colMinMax[col][0]); colMinMax[col][1] = max(fMapData, colMinMax[col][1]); byteBuffer.order(byteOrder).putFloat(fMapData); col++; } dataOutputStream.write(bytes, offset, writeLen); } // Header. sb = new StringBuilder(); sb.append("VERS MTZ:V1.1 "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss "); sb = new StringBuilder(); sb.append("TITLE FFX output: " + sdf.format(now)); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append(String.format("NCOL %8d %12d %8d", nCol, n, 0)); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("SORT 0 0 0 0 0 "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); char cdata = spaceGroup.shortName.charAt(0); if (cdata == 'H') { cdata = 'R'; } sb.append(String.format("SYMINF %3d %2d %c %5d %22s %5s", spaceGroup.getNumberOfSymOps(), spaceGroup.numPrimitiveSymEquiv, cdata, spaceGroup.number, "'" + spaceGroup.shortName + "'", spaceGroup.pointGroupName)); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); for (int i = 0; i < spaceGroup.symOps.size(); i++) { sb = new StringBuilder(); sb.append("SYMM "); SymOp symop = spaceGroup.symOps.get(i); sb.append(symop.toXYZString()); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); } sb = new StringBuilder(); sb.append(String.format("RESO %8.6f%13s%8.6f", res[0], " ", res[1])); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("VALM NAN "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("NDIF 1 "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("PROJECT 1 project "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("CRYSTAL 1 crystal "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("DATASET 1 dataset "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); for (int j = 0; j < nCol; j++) { sb = new StringBuilder(); sb.append(String.format("COLUMN %-30s %c %17.4f %17.4f 1", colname.get(j), colType[j], colMinMax[j][0], colMinMax[j][1])); dataOutputStream.writeBytes(sb.toString()); } sb = new StringBuilder(); sb.append(String.format("CELL %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", crystal.a, crystal.b, crystal.c, crystal.alpha, crystal.beta, crystal.gamma)); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append(String.format("DCELL %9d %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", 1, crystal.a, crystal.b, crystal.c, crystal.alpha, crystal.beta, crystal.gamma)); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("DWAVEL 1 1.00000 "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("END "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); sb = new StringBuilder(); sb.append("MTZENDOFHEADERS "); while (sb.length() < 80) { sb.append(" "); } dataOutputStream.writeBytes(sb.toString()); dataOutputStream.close(); } catch (Exception e) { String message = "Fatal exception evaluating structure factors.\n"; logger.log(Level.SEVERE, message, e); } }
From source file:fyp.project.uploadFile.UploadFile.java
public int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; }/* ww w. ja va 2 s .c o m*/ try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 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("file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd); m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}", new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd }); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}", new Object[] { serverResponseMessage, serverResponseCode }); // close streams m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); } //this block will give the response of upload link return serverResponseCode; // like 200 (Ok) }
From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageDecompressor.java
/** * Process image file.//from w w w. ja v a2 s .c o m */ private void go() throws IOException { long start = System.currentTimeMillis(); System.out.println("Decompressing image file: " + inputFile + " to " + outputFile); DataInputStream in = null; DataOutputStream out = null; try { // setup in PositionTrackingInputStream ptis = new PositionTrackingInputStream( new FileInputStream(new File(inputFile))); in = new DataInputStream(ptis); // read header information int imgVersion = in.readInt(); if (!LayoutVersion.supports(Feature.FSIMAGE_COMPRESSION, imgVersion)) { System.out.println("Image is not compressed. No output will be produced."); return; } int namespaceId = in.readInt(); long numFiles = in.readLong(); long genstamp = in.readLong(); long imgTxId = -1; if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) { imgTxId = in.readLong(); } FSImageCompression compression = FSImageCompression.readCompressionHeader(new Configuration(), in); if (compression.isNoOpCompression()) { System.out.println("Image is not compressed. No output will be produced."); return; } in = BufferedByteInputStream.wrapInputStream(compression.unwrapInputStream(in), FSImage.LOAD_SAVE_BUFFER_SIZE, FSImage.LOAD_SAVE_CHUNK_SIZE); System.out.println("Starting decompression."); // setup output out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); // write back the uncompressed information out.writeInt(imgVersion); out.writeInt(namespaceId); out.writeLong(numFiles); out.writeLong(genstamp); if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) { out.writeLong(imgTxId); } // no compression out.writeBoolean(false); // copy the data long size = new File(inputFile).length(); // read in 1MB chunks byte[] block = new byte[1024 * 1024]; while (true) { int bytesRead = in.read(block); if (bytesRead <= 0) break; out.write(block, 0, bytesRead); printProgress(ptis.getPos(), size); } out.close(); long stop = System.currentTimeMillis(); System.out.println("Input file : " + inputFile + " size: " + size); System.out.println("Output file: " + outputFile + " size: " + new File(outputFile).length()); System.out.println("Decompression completed in " + (stop - start) + " ms."); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
From source file:com.sandklef.coachapp.http.HttpAccess.java
public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName) throws HttpAccessException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; DataInputStream inputStream = null; String pathToOurFile = fileName; String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.UPLOAD_PATH;//from w ww .ja va 2 s .c om Log.d(LOG_TAG, "Upload server url: " + urlServer); Log.d(LOG_TAG, "Upload file: " + fileName); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); Log.d(LOG_TAG, "connection: " + connection + " uploading data to video: " + videoUuid); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod(HttpSettings.HTTP_POST); // int timeout = LocalStorage.getInstance().getnetworkTimeout(); Log.d(LOG_TAG, "timeout: " + timeout); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken()); connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub()); connection.setRequestProperty("Connection", "close"); Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties()); outputStream = new DataOutputStream(connection.getOutputStream()); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { Log.d(LOG_TAG, " writing data to stream (" + bytesRead + " / " + bytesAvailable + ")"); outputStream.write(buffer, 0, bufferSize); Log.d(LOG_TAG, " writing data to stream -"); bytesAvailable = fileInputStream.available(); Log.d(LOG_TAG, " writing data to stream -"); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.flush(); outputStream.close(); // Responses from the server (code and message) fileInputStream.close(); int serverResponseCode = 0; long before = System.currentTimeMillis(); try { Log.d(LOG_TAG, " ... writing done, getting response code"); serverResponseCode = connection.getResponseCode(); Log.d(LOG_TAG, " ... writing done, getting response message"); String serverResponseMessage = connection.getResponseMessage(); Log.d(LOG_TAG, "ServerCode:" + serverResponseCode); Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage); } catch (java.net.SocketTimeoutException e) { Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace"); e.printStackTrace(); throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW); } long after = System.currentTimeMillis(); long diff = after - before; Log.d(LOG_TAG, "diff: " + diff + "ms " + diff / 1000 + "s"); if (diff > LocalStorage.getInstance().getnetworkTimeout()) { throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW); } if (serverResponseCode >= 409) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.CONFLICT_ERROR); } if (serverResponseCode < 500 && serverResponseCode >= 400) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.ACCESS_ERROR); } try { Log.d(LOG_TAG, " ... disconnecting"); connection.disconnect(); } catch (Exception e) { Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace"); e.printStackTrace(); } }
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). */// ww w . j av a2 s . c om public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL 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("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:com.etalio.android.EtalioBase.java
protected String multipartRequest(String urlTo, InputStream fileInputStream, String filefield, String filename) throws ParseException, IOException, EtalioHttpException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try {//from w w w .jav a2s .com URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Authorization", " Bearer " + getEtalioToken().getAccessToken()); connection.setRequestProperty("User-Agent", getEtalioUserAgent()); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + filename + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + MimeTypeUtil.getMimeType(filename) + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); inputStream = connection.getInputStream(); if (connection.getResponseCode() > 300) { result = convertStreamToString(connection.getErrorStream()); } else { result = this.convertStreamToString(inputStream); } fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { throw new EtalioHttpException(connection.getResponseCode(), connection.getResponseMessage(), e.getMessage()); } }