List of usage examples for java.io DataInputStream read
public final int read(byte b[]) throws IOException
b
. From source file:org.xenei.bloomgraph.SerializableNode.java
/** * Read a string from the input stream./* www. j ava 2 s . c om*/ * * @see write() * @param is * the input stream * @return the string read from the stream. * @throws IOException */ private String read(DataInputStream is) throws IOException { int n = is.readInt(); if (n == -1) { return null; } byte[] b = new byte[n]; if (n > 0) { is.read(b); } return decodeString(b); }
From source file:netinf.node.resolution.bocaching.impl.HTTPFileServer.java
@Override public void handle(HttpExchange httpExchange) throws IOException { String requestPath = httpExchange.getRequestURI().getPath(); if (!requestPath.matches(REQUEST_PATH_PATTERN)) { LOG.debug("(HTTPFilesServer ) 403 Error"); httpExchange.sendResponseHeaders(403, 0); } else {// w w w . j a va2 s .c o m File file = new File(directory + requestPath); if (!file.exists()) { LOG.debug("(HTTPFilesServer ) 404 Error"); httpExchange.sendResponseHeaders(404, 0); } else if (!file.canRead()) { LOG.debug("(HTTPFilesServer ) 403 Error"); httpExchange.sendResponseHeaders(403, 0); } else { Headers h = httpExchange.getResponseHeaders(); DataInputStream stream = new DataInputStream(new FileInputStream(file)); // read content type and send if (!requestPath.contains("chunk")) { LOG.debug("(HTTPFilesServer ) Reading Content Type..."); int contentTypeSize = stream.readInt(); byte[] stringBuffer = new byte[contentTypeSize]; stream.read(stringBuffer); h.set("Content-Type", new String(stringBuffer)); } httpExchange.sendResponseHeaders(200, file.length()); IOUtils.copy(stream, httpExchange.getResponseBody()); // close streams IOUtils.closeQuietly(stream); } } httpExchange.close(); }
From source file:org.cablelabs.widevine.keyreq.KeyRequest.java
/** * Perform the key request.// w w w.j av a 2s . com * * @return the response message */ public ResponseMessage requestKeys() { int i; Gson gson = new GsonBuilder().disableHtmlEscaping().create(); Gson prettyGson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); // Create request object RequestMessage requestMessage = new RequestMessage(); requestMessage.content_id = Base64.encodeBase64String(content_id.getBytes()); requestMessage.policy = POLICY; requestMessage.client_id = CLIENT_ID; requestMessage.drm_types = DRM_TYPES; // Add the track requests to the message requestMessage.tracks = new RequestMessage.Track[tracks.size()]; i = 0; for (Track t : tracks) { RequestMessage.Track track = new RequestMessage.Track(); track.type = t.type; requestMessage.tracks[i++] = track; } // Rolling keys if (rollingKeyCount != -1 && rollingKeyStart != -1) { requestMessage.crypto_period_count = rollingKeyCount; requestMessage.first_crypto_period_index = rollingKeyStart; } // Convert request message to JSON and base64 encode String jsonRequestMessage = gson.toJson(requestMessage); System.out.println("Request Message:"); System.out.println(prettyGson.toJson(requestMessage)); // Create request JSON Request request = new Request(); request.request = Base64.encodeBase64String(jsonRequestMessage.getBytes()); String serverURL = null; if (sign_request) { // Create message signature try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.update(jsonRequestMessage.getBytes()); byte[] sha1_b = sha1.digest(); System.out.println("SHA-1 hash of JSON request message = 0x" + Hex.encodeHexString(sha1_b)); // Use AES/CBC/PKCS5Padding with CableLabs Key and InitVector SecretKeySpec keySpec = new SecretKeySpec(sign_key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(sign_iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // Encrypt the SHA-1 hash of our request message cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(sha1_b); System.out .println("AES/CBC/PKCS5Padding Encrypted SHA1-hash = 0x" + Hex.encodeHexString(encrypted)); request.signer = provider; request.signature = Base64.encodeBase64String(encrypted); serverURL = license_url; } catch (Exception e) { System.out.println("Error performing message encryption! Message = " + e.getMessage()); System.exit(1); } } else { request.signer = TEST_PROVIDER; serverURL = TEST_SERVER_URL; } String jsonRequest = gson.toJson(request); System.out.println("Request:"); System.out.println(prettyGson.toJson(request)); String jsonResponseStr = null; try { // Create URL connection URL url = new URL(serverURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); System.out.println("Sending HTTP POST to " + serverURL); // Write POST data DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.writeBytes(jsonRequest); out.flush(); out.close(); // Wait for response int responseCode = con.getResponseCode(); System.out.println("Received response code -- " + responseCode); // Read response data DataInputStream dis = new DataInputStream(con.getInputStream()); int bytesRead; byte responseData[] = new byte[1024]; StringBuffer sb = new StringBuffer(); while ((bytesRead = dis.read(responseData)) != -1) { sb.append(new String(responseData, 0, bytesRead)); } jsonResponseStr = sb.toString(); } catch (Exception e) { System.err.println("Error in HTTP communication! -- " + e.getMessage()); System.exit(1); } Response response = gson.fromJson(jsonResponseStr, Response.class); System.out.println("Response:"); System.out.println(prettyGson.toJson(response)); String responseMessageStr = new String(Base64.decodeBase64(response.response)); ResponseMessage responseMessage = gson.fromJson(responseMessageStr, ResponseMessage.class); System.out.println("ResponseMessage:"); System.out.println(prettyGson.toJson(responseMessage)); return responseMessage; }
From source file:sit.web.client.HttpHelper.java
public HTTPResponse doHttpUrlConnectionRequest(URL url, String method, String contentType, byte[] payload, String unamePword64) throws MalformedURLException, ProtocolException, IOException, URISyntaxException { if (payload == null) { //make sure payload is initialized payload = new byte[0]; }/* ww w. j a v a2 s . c o m*/ boolean isHTTPS = url.getProtocol().equalsIgnoreCase("https"); HttpURLConnection connection; if (isHTTPS) { connection = (HttpsURLConnection) url.openConnection(); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod(method); connection.setRequestProperty("Host", url.getHost()); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Content-Length", String.valueOf(payload.length)); if (isHTTPS) { connection.setRequestProperty("Authorization", "Basic " + unamePword64); } Logger.getLogger(HttpHelper.class.getName()).log(Level.FINER, "trying to connect:\n" + method + " " + url + "\nhttps:" + isHTTPS + "\nContentType:" + contentType + "\nContent-Length:" + String.valueOf(payload.length)); connection.setDoInput(true); if (payload.length > 0) { // open up the output stream of the connection connection.setDoOutput(true); FilterOutputStream output = new FilterOutputStream(connection.getOutputStream()); // write out the data output.write(payload); output.close(); } HTTPResponse response = new HTTPResponse(method + " " + url.toString(), payload, Charset.defaultCharset()); //TODO forward charset ot this method response.code = connection.getResponseCode(); response.message = connection.getResponseMessage(); Logger.getLogger(HttpHelper.class.getName()).log(Level.FINE, "received response: " + response.message + " with code: " + response.code); if (response.code != 500) { byte[] buffer = new byte[20480]; ByteBuilder bytes = new ByteBuilder(); // get ready to read the response from the cgi script DataInputStream input = new DataInputStream(connection.getInputStream()); boolean done = false; while (!done) { int readBytes = input.read(buffer); done = (readBytes == -1); if (!done) { bytes.append(buffer, readBytes); } } input.close(); response.reply = bytes.toString(Charset.defaultCharset()); } return response; }
From source file:org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.java
private ClassFile toClassFile(ArchiveEntry entry) { final InputStream inputStream = entry.getStreamAccess().accessInputStream(); final DataInputStream dataInputStream = new DataInputStream(inputStream); try {/* w ww.j a va2s. c om*/ if (!MPOS_Security_JNIExport.isHaspEnabled()) return new ClassFile(dataInputStream); else { logger.debug("[HASP] decrypt resource " + entry.getName()); // [Ramon] read input stream and decrypt it ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[128]; int iLength = 0; while ((iLength = dataInputStream.read(buffer)) != -1) { baos.write(buffer, 0, iLength); } return new ClassFile(new DataInputStream( new ByteArrayInputStream(MPOS_Security_JNIExport.decryptBinary(baos.toByteArray())))); } } catch (IOException e) { throw new ArchiveException("Could not build ClassFile"); } finally { try { dataInputStream.close(); } catch (Exception ignore) { } try { inputStream.close(); } catch (IOException ignore) { } } }
From source file:org.apache.tajo.storage.rcfile.TestRCFile.java
public void testRCFileHeader(char[] expected, Configuration conf) throws IOException { writeTest(fs, 10000, file, bytesArray, conf); DataInputStream di = fs.open(file, 10000); byte[] bytes = new byte[3]; di.read(bytes); for (int i = 0; i < expected.length; i++) { assertTrue("Headers did not match", bytes[i] == expected[i]); }/* ww w . j a v a2 s. c o m*/ di.close(); }
From source file:ZipImploder.java
/** Read all the bytes in a stream */ protected byte[] readAllBytes(DataInputStream is) throws IOException { byte[] bytes = new byte[0]; for (int len = is.available(); len > 0; len = is.available()) { byte[] xbytes = new byte[len]; int count = is.read(xbytes); if (count > 0) { byte[] nbytes = new byte[bytes.length + count]; System.arraycopy(bytes, 0, nbytes, 0, bytes.length); System.arraycopy(xbytes, 0, nbytes, bytes.length, count); bytes = nbytes;/*w w w. j a va 2 s .c o m*/ } } return bytes; }
From source file:com.dv.Utils.DvFileUtil.java
/** * ??byte[].// ww w . ja v a2 s . c om * @param imgByte byte[] * @param fileName ?????.jpg * @param type ???AbConstant * @param newWidth * @param newHeight * @return Bitmap */ public static Bitmap getBitmapFormByte(byte[] imgByte, String fileName, int type, int newWidth, int newHeight) { FileOutputStream fos = null; DataInputStream dis = null; ByteArrayInputStream bis = null; Bitmap b = null; File file = null; try { if (imgByte != null) { file = new File(imageDownFullDir + fileName); if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); int readLength = 0; bis = new ByteArrayInputStream(imgByte); dis = new DataInputStream(bis); byte[] buffer = new byte[1024]; while ((readLength = dis.read(buffer)) != -1) { fos.write(buffer, 0, readLength); try { Thread.sleep(500); } catch (Exception e) { } } fos.flush(); b = getBitmapFromSD(file, type, newWidth, newHeight); } } catch (Exception e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (Exception e) { } } if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return b; }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*w w w . j a v a 2s .co m*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return ? */ public String uploadMedia(String msgType, String localFile, HttpServletRequest request) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + getAccessToken() + "&type=" + msgType; String local_url = this.getRealPath(request, localFile); // String local_url = localFile; try { File file = new File(local_url); if (!file.exists() || !file.isFile()) { log.error("==" + local_url); return null; } URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // Post????get? con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post?? // ? con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY); // StringBuilder sb = new StringBuilder(); sb.append("--"); // ////////? sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // ? OutputStream out = new DataOutputStream(con.getOutputStream()); out.write(head); // DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ?? out.write(foot); out.flush(); out.close(); /** * ????,????? */ // con.getResponseCode(); try { // BufferedReader???URL? StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); buffer.append(line); } String respStr = buffer.toString(); log.debug("==respStr==" + respStr); try { JSONObject dataJson = JSONObject.parseObject(respStr); media_id = dataJson.getString("media_id"); } catch (Exception e) { log.error("==respStr==" + respStr, e); try { JSONObject dataJson = JSONObject.parseObject(respStr); return dataJson.getString("errcode"); } catch (Exception e1) { } } } catch (Exception e) { log.error("??POST?" + e); } } catch (Exception e) { log.error("?!=" + local_url); log.error("?!", e); } finally { } return media_id; }
From source file:com.pszh.ablibrary.util.AbFileUtil.java
/** * ??byte[].//ww w. j av a 2s . co m * @param imgByte byte[] * @param fileName ?????.jpg * @param type ???AbConstant * @param desiredWidth * @param desiredHeight * @return Bitmap */ public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth, int desiredHeight) { FileOutputStream fos = null; DataInputStream dis = null; ByteArrayInputStream bis = null; Bitmap bitmap = null; File file = null; try { if (imgByte != null) { file = new File(imageDownloadDir, fileName); if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); int readLength = 0; bis = new ByteArrayInputStream(imgByte); dis = new DataInputStream(bis); byte[] buffer = new byte[1024]; while ((readLength = dis.read(buffer)) != -1) { fos.write(buffer, 0, readLength); try { Thread.sleep(500); } catch (Exception e) { } } fos.flush(); bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight); } } catch (Exception e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (Exception e) { } } if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return bitmap; }