List of usage examples for java.io DataInputStream read
public final int read(byte b[]) throws IOException
b
. From source file:XmlUtils.java
public static Document parse(URL url) throws DocumentException, IOException { URLConnection urlConnection;/*from w w w .j av a 2 s . c o m*/ DataInputStream inStream; urlConnection = url.openConnection(); ((HttpURLConnection) urlConnection).setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(false); urlConnection.setUseCaches(false); inStream = new DataInputStream(urlConnection.getInputStream()); byte[] bytes = new byte[1024]; int read; StringBuilder builder = new StringBuilder(); while ((read = inStream.read(bytes)) >= 0) { String readed = new String(bytes, 0, read, "UTF-8"); builder.append(readed); } SAXReader reader = new SAXReader(); XmlUtils.createIgnoreErrorHandler(reader); // InputSource inputSource = new InputSource(new InputStreamReader(inStream, "UTF-8")); // inputSource.setEncoding("UTF-8"); Document dom = reader.read(new StringReader(builder.toString())); inStream.close(); // new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("retrieval.xml"), "UTF-8") return dom; }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*from ww w . j av a 2 s. co m*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return */ @Deprecated public static String uploadMedia(String access_token, String msgType, String localFile) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + msgType; 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); // con.setRequestProperty("Content-Type", // "multipart/mixed; boundary=" + BOUNDARY); // con.setRequestProperty("content-type", "text/html"); // ? // 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:Messenger.TorLib.java
/** * This method opens a TOR socket, and does an anonymous DNS resolve through it. * Since Tor caches things, this is a very fast lookup if we've already connected there * The resolve does a gethostbyname() on the exit node. * @param targetHostname String containing the hostname to look up. * @return String representation of the IP address: "x.x.x.x" *//*from ww w . java 2 s. co m*/ static String TorResolve(String targetHostname) { int targetPort = 0; // we dont need a port to resolve try { Socket s = TorSocketPre(targetHostname, targetPort, TOR_RESOLVE); DataInputStream is = new DataInputStream(s.getInputStream()); byte version = is.readByte(); byte status = is.readByte(); if (status != (byte) 90) { //failed for some reason, return useful exception throw (new IOException(ParseSOCKSStatus(status))); } int port = is.readShort(); byte[] ipAddrBytes = new byte[4]; is.read(ipAddrBytes); InetAddress ia = InetAddress.getByAddress(ipAddrBytes); //System.out.println("Resolved into:"+ia); is.close(); String addr = ia.toString().substring(1); // clip off the "/" return (addr); } catch (Exception e) { e.printStackTrace(); } return (null); }
From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java
private static String decodeString(DataInputStream dataInputStream) throws IOException { int length = dataInputStream.readInt(); if (length == 0) { return StringUtils.EMPTY; } else {/*from w w w . ja v a 2 s . c o m*/ byte[] buffer = new byte[length]; int numBytesRead = dataInputStream.read(buffer); assert numBytesRead == length; return new String(buffer, UTF_8); } }
From source file:org.rifidi.edge.adapter.csl.util.CslRfidTagServer.java
public static void clearReadBuffer(DataInputStream data) { byte[] inData = new byte[1024]; try {/*from ww w . j a v a2 s .c o m*/ while (data.available() != 0) data.read(inData); } catch (IOException e) { logger.error("Could not clear buffer: " + e.getMessage()); } }
From source file:at.tugraz.sss.serv.SSFileU.java
public static String readPNGToBase64Str(final String pngFilePath) throws Exception { final DataInputStream fileReader = new DataInputStream(new FileInputStream(new File(pngFilePath))); final List<Byte> bytes = new ArrayList<>(); byte[] chunk = new byte[SSSocketU.socketTranmissionSize]; int fileChunkLength; while (true) { fileChunkLength = fileReader.read(chunk); if (fileChunkLength == -1) { break; }// w ww.j a va 2 s . c om for (int counter = 0; counter < fileChunkLength; counter++) { bytes.add(chunk[counter]); } } return "data:image/png;base64," + DatatypeConverter .printBase64Binary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()]))); }
From source file:org.ctuning.openme.openme.java
public static JSONObject remote_access(JSONObject i) throws JSONException { /*/*from ww w . j a v a 2 s . c o m*/ Input: { remote_server_url - remote server URL (module_uoa) - module to run (action) - action to perform if =='download', prepare entry/file download through Internet (save_to_file) - if web_action==download, save output to this file (out) - if 'json', treat output as json if 'json_after_text', strip everything before json if 'txt', output to stdout ... - all other request parameters //FGG TBD - should add support for proxy } Output: { return - return code = 0 if successful > 0 if error < 0 if warning (rarely used at this moment) (error) - error text, if return > 0 (stdout) - if out='txt', output there } */ // Prepare return object JSONObject r = new JSONObject(); URL u; HttpURLConnection c = null; // Prepare request String x = ""; String post = ""; String con = ""; x = ""; if (i.has("out")) x = (String) i.get("out"); if (x != null && x != "") con = x; String url = ""; if (i.has("remote_server_url")) { url = (String) i.get("remote_server_url"); i.remove("remote_server_url"); } if (url == null || url == "") { r.put("return", new Integer(1)); r.put("error", "'remote_server_url is not defined"); return r; } String save_to_file = ""; if (i.has("save_to_file")) { save_to_file = (String) i.get("save_to_file"); i.remove("save_to_file"); } // Check if data download, not json and convert it to download request boolean download = false; x = ""; if (i.has("action")) { x = (String) i.get("action"); } if (x == "download" || x == "show") { download = true; if (post != "") post += "&"; post += "module_uoa=web&action=" + x; if (i.has("module_uoa")) i.remove("module_uoa"); if (i.has("out")) i.remove("out"); i.remove("action"); } // Prepare dict to transfer through Internet JSONObject ii = new JSONObject(); ii.put("dict", i); JSONObject rx = convert_array_to_uri(ii); if ((Integer) rx.get("return") > 0) return rx; if (post != "") post += "&"; post += "ck_json=" + ((String) rx.get("string")); // Prepare URL request String s = ""; try { u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length)); c.setUseCaches(false); c.setDoInput(true); c.setDoOutput(true); //Send request DataOutputStream dos = new DataOutputStream(c.getOutputStream()); dos.writeBytes(post); dos.flush(); dos.close(); } catch (IOException e) { if (c != null) c.disconnect(); r.put("return", new Integer(1)); r.put("error", "Failed sending request to remote server (" + e.getMessage() + ") ..."); return r; } r.put("return", new Integer(0)); // Check if download, not json! if (download) { String name = "default_download_name.dat"; x = ""; if (i.has("filename")) { x = ((String) i.get("filename")); } if (x != null && x != "") { File xf = new File(x); name = xf.getName(); } if (save_to_file != null && save_to_file != "") name = save_to_file; //Reading response in binary and at the same time saving to file try { //Read response DataInputStream dis = new DataInputStream(c.getInputStream()); DataOutputStream dos = new DataOutputStream(new FileOutputStream(name)); byte[] buf = new byte[16384]; int len; while ((len = dis.read(buf)) != -1) dos.write(buf, 0, len); dos.close(); dis.close(); } catch (Exception e) { if (c != null) c.disconnect(); r.put("return", new Integer(1)); r.put("error", "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ..."); return r; } } else { //Reading response in text try { //Read response InputStream is = c.getInputStream(); BufferedReader f = new BufferedReader(new InputStreamReader(is)); StringBuffer ss = new StringBuffer(); while ((x = f.readLine()) != null) { ss.append(x); ss.append('\r'); } f.close(); s = ss.toString(); } catch (Exception e) { if (c != null) c.disconnect(); r.put("return", new Integer(1)); r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ..."); return r; } if (con == "json_after_text") { String json_sep = "*** ### --- CM JSON SEPARATOR --- ### ***"; int li = s.lastIndexOf(json_sep); if (li >= 0) { s = s.substring(li + json_sep.length()); s = s.trim(); } } if (con == "json_after_text" || con == "json") r = new JSONObject(s); else r.put("stdout", s); } if (c != null) c.disconnect(); return r; }
From source file:org.openme_ck.openme_ck.java
public static JSONObject remote_access(JSONObject i) { /*/*from ww w . java 2s. c o m*/ Input: { remote_server_url - remote server URL (module_uoa) - module to run (action) - action to perform if =='download', prepare entry/file download through Internet (save_to_file) - if web_action==download, save output to this file (out) - if 'json', treat output as json if 'json_after_text', strip everything before json if 'txt', output to stdout ... - all other request parameters //FGG TBD - should add support for proxy } Output: { return - return code = 0 if successful > 0 if error < 0 if warning (rarely used at this moment) (error) - error text, if return > 0 (stdout) - if out='txt', output there } */ // Prepare return object JSONObject r = new JSONObject(); URL u; HttpURLConnection c = null; // Prepare request String x = ""; String post = ""; String con = ""; x = (String) i.get("out"); if (x != null && x != "") con = x; String url = (String) i.get("remote_server_url"); if (url == null || url == "") { r.put("return", new Long(1)); r.put("error", "'remote_server_url is not defined"); return r; } i.remove("remote_server_url"); String save_to_file = (String) i.get("save_to_file"); if (save_to_file != null) i.remove("save_to_file"); // Check if data download, not json and convert it to download request boolean download = false; x = (String) i.get("action"); if (x == "download" || x == "show") { download = true; if (post != "") post += "&"; post += "module_uoa=web&action=" + x; i.remove("action"); if (((String) i.get("module_uoa")) != null) i.remove("module_uoa"); if (((String) i.get("out")) != null) i.remove("out"); } // Prepare dict to transfer through Internet JSONObject ii = new JSONObject(); ii.put("dict", i); JSONObject rx = convert_array_to_uri(ii); if ((Long) rx.get("return") > 0) return rx; if (post != "") post += "&"; post += "ck_json=" + ((String) rx.get("string")); // Prepare URL request String s = ""; try { //Connect u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Content-Length", Integer.toString(post.getBytes().length)); c.setUseCaches(false); c.setDoInput(true); c.setDoOutput(true); //Send request DataOutputStream dos = new DataOutputStream(c.getOutputStream()); dos.writeBytes(post); dos.flush(); dos.close(); } catch (Exception e) { if (c != null) c.disconnect(); r.put("return", new Long(1)); r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ..."); return r; } r.put("return", new Long(0)); // Check if download, not json! if (download) { String name = "default_download_name.dat"; x = ((String) i.get("filename")); if (x != null && x != "") { File xf = new File(x); name = xf.getName(); } if (save_to_file != null && save_to_file != "") name = save_to_file; //Reading response in binary and at the same time saving to file try { //Read response DataInputStream dis = new DataInputStream(c.getInputStream()); DataOutputStream dos = new DataOutputStream(new FileOutputStream(name)); byte[] buf = new byte[16384]; int len; while ((len = dis.read(buf)) != -1) dos.write(buf, 0, len); dos.close(); dis.close(); } catch (Exception e) { if (c != null) c.disconnect(); r.put("return", new Long(1)); r.put("error", "Failed reading stream from remote server or writing to file (" + e.getMessage() + ") ..."); return r; } } else { //Reading response in text try { //Read response InputStream is = c.getInputStream(); BufferedReader f = new BufferedReader(new InputStreamReader(is)); StringBuffer ss = new StringBuffer(); while ((x = f.readLine()) != null) { ss.append(x); ss.append('\r'); } f.close(); s = ss.toString(); } catch (Exception e) { if (c != null) c.disconnect(); r.put("return", new Long(1)); r.put("error", "Failed reading stream from remote server (" + e.getMessage() + ") ..."); return r; } if (con == "json_after_text") { int li = s.lastIndexOf(json_sep); if (li >= 0) { s = s.substring(li + json_sep.length()); li = s.lastIndexOf(json_sep2); if (li > 0) { s = s.substring(0, li); } s = s.trim(); } } if (con == "json_after_text" || con == "json") { //Parsing json try { JSONParser parser = new JSONParser(); r = (JSONObject) parser.parse(s); } catch (ParseException ex) { r.put("return", new Long(1)); r.put("error", "can't parse json output (" + ex + ") ..."); return r; } } else r.put("stdout", s); } if (c != null) c.disconnect(); return r; }
From source file:isl.FIMS.utils.Utils.java
public static void downloadZip(ServletOutputStream outStream, File file) { DataInputStream in = null; int BUFSIZE = 8192; try {/* ww w . j a v a 2 s . com*/ byte[] byteBuffer = new byte[BUFSIZE]; in = new DataInputStream(new FileInputStream(file)); int bytesRead; while ((bytesRead = in.read(byteBuffer)) != -1) { outStream.write(byteBuffer, 0, bytesRead); } in.close(); outStream.close(); } catch (IOException ex) { } finally { try { in.close(); } catch (IOException ex) { } } }
From source file:at.tugraz.sss.serv.util.SSFileU.java
public static String readImageToBase64Str(final String filePath, final Integer transmissionSize) throws SSErr { try {//from ww w.j a va 2 s .c om final DataInputStream fileReader = new DataInputStream(new FileInputStream(new File(filePath))); final List<Byte> bytes = new ArrayList<>(); byte[] chunk = new byte[transmissionSize]; int fileChunkLength; while (true) { fileChunkLength = fileReader.read(chunk); if (fileChunkLength == -1) { break; } for (int counter = 0; counter < fileChunkLength; counter++) { bytes.add(chunk[counter]); } } return "data:image/png;base64," + DatatypeConverter .printBase64Binary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()]))); } catch (Exception error) { SSServErrReg.regErrThrow(error); return null; } }