List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:io.lavagna.model.CardFullWithCounts.java
private static String hash(CardFullWithCounts cwc) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); try {// www . j av a2 s .c om // card daos.writeChars(Integer.toString(cwc.getId())); writeNotNull(daos, cwc.getName()); writeInts(daos, cwc.getSequence(), cwc.getOrder(), cwc.getColumnId(), cwc.getUserId()); // end card writeNotNull(daos, cwc.creationUser); writeNotNull(daos, cwc.creationDate); if (cwc.counts != null) { for (Map.Entry<String, CardDataCount> count : cwc.counts.entrySet()) { writeNotNull(daos, count.getKey()); CardDataCount dataCount = count.getValue(); daos.writeChars(Integer.toString(dataCount.getCardId())); if (dataCount.getCount() != null) { daos.writeChars(Long.toString(dataCount.getCount().longValue())); } writeNotNull(daos, dataCount.getType()); } } for (LabelAndValue lv : cwc.labels) { // writeInts(daos, lv.getLabelId(), lv.getLabelProjectId()); writeNotNull(daos, lv.getLabelName()); writeInts(daos, lv.getLabelColor()); writeEnum(daos, lv.getLabelType()); writeEnum(daos, lv.getLabelDomain()); // writeInts(daos, lv.getLabelValueId(), lv.getLabelValueCardId(), lv.getLabelValueLabelId()); writeNotNull(daos, lv.getLabelValueUseUniqueIndex()); writeEnum(daos, lv.getLabelValueType()); writeNotNull(daos, lv.getLabelValueString()); writeNotNull(daos, lv.getLabelValueTimestamp()); writeNotNull(daos, lv.getLabelValueInt()); writeNotNull(daos, lv.getLabelValueCard()); writeNotNull(daos, lv.getLabelValueUser()); } daos.flush(); return DigestUtils.sha256Hex(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:com.project.qrypto.keymanagement.KeyManager.java
/** * Saves the Keystore. Uses either internal or external memory depending on settings. * @param context the context to use/*from w w w . j a v a 2 s.com*/ * * @throws IOException if the outstream is somehow bad or interrupted * @throws InvalidCipherTextException if the key is bad or the data is bad */ public void commit(Context context) throws IOException, InvalidCipherTextException { //Commit Preferences Editor edit = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit(); edit.putBoolean(USE_INTERNAL_STORAGE, internalStorage); edit.putBoolean(PASSWORD_PROTECTED, passwordProtected); edit.putBoolean(SETUP_COMPLETE, true); edit.commit(); //Commit Key Data DataOutputStream writer = null; ByteArrayOutputStream output = null; //Create the proper streams if (passwordProtected) { output = new ByteArrayOutputStream(); writer = new DataOutputStream(output); } else { writer = new DataOutputStream(getAssociatedOutFileStream(context)); } //Write everything out to the stream writer.writeUTF("RCYTHR1"); //Special indicator to determine if we decrypt properly writer.writeInt(lookup.size()); for (Entry<String, Key> entry : lookup.entrySet()) { writer.writeUTF(entry.getKey()); entry.getValue().writeData(writer); } writer.writeByte(1); //Prevent null padding from causing too much truncation. writer.flush(); //If we're password protecting we still need to encrypt and output to file if (passwordProtected) { OutputStream finalOut = getAssociatedOutFileStream(context); finalOut.write(AES.handle(true, output.toByteArray(), keyStoreKey)); finalOut.close(); } writer.close(); }
From source file:au.org.ala.spatial.util.RecordsSmall.java
private void makeUniquePoints() throws Exception { //make unique points and index points = new RandomAccessFile(filename + "records.csv.small.points", "r"); double[] allPoints = getPointsAll(); Coord[] p = new Coord[allPoints.length / 2]; for (int i = 0; i < allPoints.length; i += 2) { p[i / 2] = new Coord(allPoints[i], allPoints[i + 1], i / 2); }/* ww w .j a v a 2 s . com*/ allPoints = null; //make available to GC Arrays.sort(p, new Comparator<Coord>() { public int compare(Coord o1, Coord o2) { return o1.longitude == o2.longitude ? (o1.latitude == o2.latitude ? 0 : (o1.latitude - o2.latitude > 0.0 ? 1 : -1)) : (o1.longitude - o2.longitude > 0.0 ? 1 : -1); } }); DataOutputStream outputUniquePoints = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniquePoints"))); DataOutputStream outputUniqueIdx = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniqueIdx"))); int pos = -1; //first point is set after pos++ int[] newPos = new int[p.length]; for (int i = 0; i < p.length; i++) { if (i == 0 || p[i].latitude != p[i - 1].latitude || p[i].longitude != p[i - 1].longitude) { outputUniquePoints.writeDouble(p[i].latitude); outputUniquePoints.writeDouble(p[i].longitude); pos++; } newPos[p[i].pos] = pos; } for (int i = 0; i < p.length; i++) { outputUniqueIdx.writeInt(newPos[i]); } outputUniqueIdx.flush(); outputUniqueIdx.close(); outputUniquePoints.flush(); outputUniquePoints.close(); points.close(); }
From source file:com.mellanox.r4h.DataXceiverBase.java
private void processOPRHeaderRequest(Msg msg) throws IOException, NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException { if (serverSession.getIsClosing()) { LOG.warn("Process OPRHeaderRequest for a closed session, discarding..."); return;//from w w w. j a va2 s . c o m } if (LOG.isTraceEnabled()) { LOG.trace("Processing block header request. uri=" + DataXceiverBase.this.uri); } msg.getIn().position(0); DataInputStream in = new DataInputStream(new ByteBufferInputStream(msg.getIn())); final short version = in.readShort(); if (version != DataTransferProtocol.DATA_TRANSFER_VERSION) { in.close(); throw new IOException("Version Mismatch (Expected: " + DataTransferProtocol.DATA_TRANSFER_VERSION + ", Received: " + version + " )"); } Op op = Op.read(in); if (op != Op.WRITE_BLOCK) { throw new IOException("Unknown op " + op + " in data stream"); } parseOpWriteBlock(in); // check single target for transfer-RBW/Finalized if (oprHeader.isTransfer() && oprHeader.getTargets().length > 0) { throw new IOException(oprHeader.getStage() + " does not support multiple targets " + Arrays.asList(oprHeader.getTargets())); } if (LOG.isDebugEnabled()) { LOG.debug("uri= " + DataXceiverBase.this.uri + "\nopWriteBlock: stage=" + oprHeader.getStage() + ", clientname=" + oprHeader.getClientName() + "\n block =" + oprHeader.getBlock() + ", newGs=" + oprHeader.getLatestGenerationStamp() + ", bytesRcvd=[" + oprHeader.getMinBytesRcvd() + ", " + oprHeader.getMaxBytesRcvd() + "]" + "\n targets=" + Arrays.asList(oprHeader.getTargets()) + "; pipelineSize=" + oprHeader.getPipelineSize() + ", srcDataNode=" + oprHeader.getSrcDataNode() + ", isDatanode=" + oprHeader.isDatanode() + ", isClient=" + oprHeader.isClient() + ", isTransfer=" + oprHeader.isTransfer() + ", writeBlock receive buf size " + msg.getIn().limit()); } // We later mutate block's generation stamp and length, but we need to // forward the original version of the block to downstream mirrors, so // make a copy here. final ExtendedBlock originalBlock = new ExtendedBlock(oprHeader.getBlock()); oprHeader.getBlock().setNumBytes(dnBridge.getEstimateBlockSize()); LOG.info("Receiving " + oprHeader.getBlock() + " src: " + uri); boolean isTokenAccessOk = checkAccess(oprHeader.isClient(), oprHeader.getBlock(), oprHeader.getBlockToken(), Op.WRITE_BLOCK, BlockTokenSecretManager.AccessMode.WRITE, msg); if (isTokenAccessOk) { if (oprHeader.isDatanode() || oprHeader.getStage() != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) { // open a block receiver createBlockReciver(in, NUM_OF_BLOCK_RECEIVER_CREATION_ATTEMPTS); if (LOG.isTraceEnabled()) { LOG.trace("After BlockReceiver creation: " + blockReceiver); } } else { dnBridge.recoverClose(oprHeader.getBlock(), oprHeader.getLatestGenerationStamp(), oprHeader.getMinBytesRcvd()); } // // Connect to downstream machine, if appropriate // if (hasPipeline()) { try { blockReceiver.setMirrorOut(new DummyDataOutputStream()); // we send to pipeline with RDMA and then keep using vanila's // original // receivePacket function by modifying mirror stream with dummy // stream to // avoid sending to pipeline from vanila's flow // openPipelineConnection(); // sendOprHeaderToPipeline(msg, originalBlock); ClientSession.Callbacks csCBs = DataXceiverBase.this.new CSCallbacks(); String clientURI = DataXceiverBase.this.uri.toString(); spw.queueAsyncPipelineConnection(csCBs, clientURI, oprHeader, DataXceiverBase.this); /* queue request to send OPR Header to pipeline */ Msg mirror = msg.getMirror(false); mirror.getOut().clear(); DataOutputStream mirrorOut = new DataOutputStream(new ByteBufferOutputStream(mirror.getOut())); senderWriteBlock(mirrorOut, originalBlock); mirrorOut.flush(); spw.queueAsyncRequest(mirror, this); } catch (Exception e) { if (oprHeader.isClient()) { replyHeaderAck(msg, ERROR, oprHeader.getTargetByIndex(0).getXferAddr()); // NB: Unconditionally using the xfer addr w/o hostname LOG.error(dnBridge.getDN() + ":Exception transfering block " + oprHeader.getBlock() + " to mirror " + oprHeader.getTargetByIndex(0).getInfoAddr() + ": " + StringUtils.stringifyException(e)); } else { LOG.info(dnBridge.getDN() + ":Exception transfering " + oprHeader.getBlock() + " to mirror " + oprHeader.getTargetByIndex(0).getInfoAddr() + "- continuing without the mirror", e); } } } else if (oprHeader.isClient() && !oprHeader.isTransfer()) { replyHeaderAck(msg); // async } } }
From source file:com.jamsuni.jamsunicodescan.MainActivity.java
public void testTTS(String msg) { String apiURL = "https://openapi.naver.com/v1/voice/tts.bin"; BookInfo bookInfo = new BookInfo(); try {/*from ww w. ja v a 2 s. c o m*/ String text = URLEncoder.encode(msg, "UTF-8"); URL url = new URL(apiURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("X-Naver-Client-Id", clientId); con.setRequestProperty("X-Naver-Client-Secret", clientSecret); // post request String postParams = "speaker=mijin&speed=0&text=" + text; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader br; if (responseCode == 200) { // ? InputStream is = con.getInputStream(); int read = 0; byte[] bytes = new byte[1024]; // ? ? mp3 ? ? String tempname = Long.valueOf(new Date().getTime()).toString(); File f = new File(Environment.getExternalStorageDirectory() + "/" + tempname + ".mp3"); f.createNewFile(); OutputStream outputStream = new FileOutputStream(f); while ((read = is.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } is.close(); } else { // ? ? br = new BufferedReader(new InputStreamReader(con.getErrorStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = br.readLine()) != null) { response.append(inputLine); } br.close(); System.out.println(response.toString()); } } catch (Exception e) { System.out.println(e); } return; }
From source file:com.chaosinmotion.securechat.server.messages.NotificationSocket.java
/** * Internal method for sending a message to the specified device. This * encodes the message as a binary array and transmits it as a single * packet to the listening device. This allows users to receive messages * during chat as soon as we are able to, for (more or less) just in time * messaging.//from w ww . j a va 2s . c om * * The packet returned here is similar to the packet returned by the * getmessages api, except we serialize as binary. * * @param messageid * @param senderid * @param sendername * @param ts * @param message * @throws IOException */ void sendMessage(int messageid, int senderid, String sendername, boolean toflag, Timestamp ts, byte[] message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); /* * Encode. First byte is 0x20 */ String date; synchronized (format) { date = format.format(ts); } /* * Formulate packet in expected format */ dos.writeByte(0x20); // marker dos.writeBoolean(toflag); dos.writeInt(messageid); dos.writeInt(senderid); dos.writeUTF(date); dos.writeUTF(sendername); dos.writeInt(message.length); dos.write(message); /* * Flush and write packet to device. Our protocol does not depend on * the device actually receiving this message, as we wait until the * device deletes the messages by a separate command. */ dos.flush(); out.writeData(baos.toByteArray()); }
From source file:net.nym.library.http.UploadImagesRequest.java
/** * ???// w ww . ja v a2 s .co m * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws java.io.IOException */ public static String postFile(String url, Map<String, Object> params, Map<String, File> files) throws IOException { String result = ""; String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; StringBuilder sb = new StringBuilder("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { // sb.append(PREFIX); // sb.append(BOUNDARY); // sb.append(LINEND); // sb.append("Content-Disposition: form-data; name=\"" // + entry.getKey() + "\"" + LINEND); // sb.append("Content-Type: text/plain; charset=" + CHARSET // + LINEND); // sb.append("Content-Transfer-Encoding: 8bit" + LINEND); // sb.append(LINEND); // sb.append(entry.getValue()); // sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString())) .append("&"); } sb.deleteCharAt(sb.length() - 1); URL uri = new URL(url + sb.toString()); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setDoInput(true);// ? conn.setDoOutput(true);// ? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // ? // StringBuilder sb = new StringBuilder(); // for (Map.Entry<String, Object> entry : params.entrySet()) { //// sb.append(PREFIX); //// sb.append(BOUNDARY); //// sb.append(LINEND); //// sb.append("Content-Disposition: form-data; name=\"" //// + entry.getKey() + "\"" + LINEND); //// sb.append("Content-Type: text/plain; charset=" + CHARSET //// + LINEND); //// sb.append("Content-Transfer-Encoding: 8bit" + LINEND); //// sb.append(LINEND); //// sb.append(entry.getValue()); //// sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); // } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(sb.toString().getBytes()); // ? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sbFile = new StringBuilder(); sbFile.append(PREFIX); sbFile.append(BOUNDARY); sbFile.append(LINEND); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sbFile.append(LINEND); Log.i(sbFile.toString()); outStream.write(sbFile.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // ? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); } outStream.flush(); // ?? int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sbResult = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sbResult.append((char) ch); } } result = sbResult.toString(); outStream.close(); conn.disconnect(); return result; }
From source file:com.anyonavinfo.commonuserregister.MainActivity.java
/** * Post?/*from w ww . j a v a 2 s . co 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; }
From source file:UploadTest.java
@Test public void put_data_test() { String pid = "frl:6376979"; try {// w w w. jav a 2 s . com System.out.println(url); String charset = "UTF-8"; File file = new File("/home/raul/test/frl%3A6376984/6376986.pdf"); FileInputStream fi = new FileInputStream(file); httpCon.setDoOutput(true); httpCon.setDoInput(true); httpCon.setRequestMethod("PUT"); httpCon.setRequestProperty("Connection", "Keep-Alive"); httpCon.setRequestProperty("Content-Type", "application/pdf"); httpCon.setRequestProperty("type", "multipart/form-data"); httpCon.setRequestProperty("Accept", "application/data"); httpCon.setRequestProperty("uploaded_file", file.getPath()); System.out.println(file.getPath()); DataOutputStream out = new DataOutputStream(httpCon.getOutputStream()); System.out.println("130"); Files.copy(file.toPath(), out); int bytesRead; byte[] dataBuffer = new byte[1024]; while ((bytesRead = fi.read(dataBuffer)) != -1) { out.write(dataBuffer, 0, bytesRead); } System.out.println("137"); out.flush(); out.close(); System.out.println("140"); System.out.println("142"); } catch (Exception e) { throw new RuntimeException(e); } }
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;/* w w w . j a v a2 s . c o m*/ 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; }