/** * Loads the drawing. By convention this method is invoked on a worker thread. * * @param progress A ProgressIndicator to inform the user about the progress of the operation. * @return The Drawing that was loaded. */ protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); // Disable caching. This ensures that we always request the // newest version of the drawing from the server. // (Note: The server still needs to set the proper HTTP caching // properties to prevent proxies from caching the drawing). if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } // Read the data into a buffer int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); // Read the data using all supported input formats // until we succeed IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; }
public void start() throws Exception { URL url = new URL("http://localhost:5000/gameInit"); URLConnection urlCon = url.openConnection(); GameInitMessage gim = GameInitMessage.parseFrom(urlCon.getInputStream()); urlCon.getInputStream().close(); this.properties = new PropertyWrapper(gim); gameId = gim.getGameId(); }
public static String sendGet(String url, String params) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + params; URL realUrl = new URL(urlName); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.connect(); Map<String, List<String>> map = conn.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
// postToRestfulApi - // Note: params in the addr field need to be URLEncoded private String postToRestfulApi( String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try { URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { // System.out.println("Exception: " + e.getMessage()); } return result; } // TESTED
// callRestfulApi - Calls restful API and returns results as a string public String callRestfulApi( String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } } // TESTED
public void init() { try { url = new URL(urlStr); // 创建一个代理服务器对象 proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); // 使用指定的代理服务器打开连接 conn = url.openConnection(proxy); // 设置超时时长。 conn.setConnectTimeout(5000); scan = new Scanner(conn.getInputStream()); // 初始化输出流 ps = new PrintStream("Index.htm"); while (scan.hasNextLine()) { String line = scan.nextLine(); // 在控制台输出网页资源内容 System.out.println(line); // 将网页资源内容输出到指定输出流 ps.println(line); } } catch (MalformedURLException ex) { System.out.println(urlStr + "不是有效的网站地址!"); } catch (IOException ex) { ex.printStackTrace(); } // 关闭资源 finally { if (ps != null) { ps.close(); } } }
private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException { if (processedLinks.contains(url)) { return false; } else { processedLinks.add(url); } URLConnection connection = url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); ArrayList list = processPage(in, baseDir, url); if ((status != null) && (list.size() > 0)) { status.setMaximum(list.size()); } for (int i = 0; i < list.size(); i++) { if (status != null) { status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i); } if ((!((String) list.get(i)).startsWith("RUN")) && (!((String) list.get(i)).startsWith("SAVE")) && (!((String) list.get(i)).startsWith("LOAD"))) { processURL( new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)), baseDir, status); } } in.close(); return true; }
byte[] getJar(String address) { // System.out.println("getJar: "+address); byte[] data; try { URL url = new URL(address); IJ.showStatus("Connecting to " + IJ.URL); URLConnection uc = url.openConnection(); int len = uc.getContentLength(); if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len); if (len <= 0) return null; String name = address.contains("wsr") ? "daily build (" : "ij.jar ("; IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)"); InputStream in = uc.getInputStream(); data = new byte[len]; int n = 0; while (n < len) { int count = in.read(data, n, len - n); if (count < 0) throw new EOFException(); n += count; IJ.showProgress(n, len); } in.close(); } catch (IOException e) { if (IJ.debugMode) IJ.log("" + e); return null; } if (IJ.debugMode) IJ.wait(6000); return data; }
public void fun(URLConnection connection) { try { connection.connect(); // print header fields Map<String, List<String>> headers = connection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) System.out.println(key + ": " + value); } // print convenience functions System.out.println("----------"); System.out.println("getContentType: " + connection.getContentType()); System.out.println("getContentLength: " + connection.getContentLength()); System.out.println("getContentEncoding: " + connection.getContentEncoding()); System.out.println("getDate: " + connection.getDate()); System.out.println("getExpiration: " + connection.getExpiration()); System.out.println("getLastModifed: " + connection.getLastModified()); System.out.println("----------"); Scanner in = new Scanner(connection.getInputStream()); // print first ten lines of contents for (int n = 1; in.hasNextLine() && n <= 10; n++) System.out.println(in.nextLine()); if (in.hasNextLine()) System.out.println(". . ."); } catch (IOException e) { e.printStackTrace(); } }
public static String readURIToLocalURI(String uri) throws URISyntaxException, IOException { final PipelineContext pipelineContext = StaticExternalContext.getStaticContext().getPipelineContext(); final URLConnection urlConnection = new URI(uri).toURL().openConnection(); InputStream inputStream = null; try { inputStream = urlConnection.getInputStream(); return inputStreamToAnyURI(pipelineContext, inputStream, REQUEST_SCOPE); } finally { if (inputStream != null) inputStream.close(); } }
public UrlNode(String location) { parser = new JSONParser(); try { try { URLConnection conn = new URL(location).openConnection(); InputStream response = conn.getInputStream(); // STUPID hack to convert an InputStream to a String in one line: InputStream input = conn.getInputStream(); try { this.content = new java.util.Scanner(input).useDelimiter("\\A").next(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; try { Map json = (Map) parser.parse(content, containerFactory); Iterator iter = json.entrySet().iterator(); data = new HashMap<String, String>(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); data.put(entry.getKey().toString(), entry.getValue().toString()); } } catch (ParseException pe) { } } catch (java.util.NoSuchElementException e) { this.content = "{\"Error\": \"NO CONTENT\"}"; } } catch (MalformedURLException e) { } } catch (IOException e) { } }
public void run() { InputStream inputstream = null; try { inputstream = c.getInputStream(); } catch (IOException ioexception) { b = ioexception; } a = inputstream; synchronized (event) { event.notifyAll(); } }
public void end() throws Exception { FunMessage.Builder fm = FunMessage.newBuilder().setGameId(gameId).setFunScore(rate()); URL url = new URL("http://localhost:5000/gameFinish"); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(urlCon.getOutputStream()); wr.write("rating="); wr.flush(); fm.build().writeTo(urlCon.getOutputStream()); urlCon.getOutputStream().close(); // No network I/O happens until you ask for feedback apparently urlCon.getInputStream(); }
private TrackerInfo doRequest( String announce, String infoHash, String peerID, long uploaded, long downloaded, long left, String event) throws IOException { String s = announce + "?info_hash=" + infoHash + "&peer_id=" + peerID + "&port=" + port + "&uploaded=" + uploaded + "&downloaded=" + downloaded + "&left=" + left + ((event != NO_EVENT) ? ("&event=" + event) : ""); URL u = new URL(s); if (Snark.debug >= Snark.INFO) Snark.debug("Sending TrackerClient request: " + u, Snark.INFO); URLConnection c = u.openConnection(); c.connect(); InputStream in = c.getInputStream(); if (c instanceof HttpURLConnection) { // Check whether the page exists int code = ((HttpURLConnection) c).getResponseCode(); if (code / 100 != 2) // We can only handle 200 OK responses throw new IOException( "Loading '" + s + "' gave error code " + code + ", it probably doesn't exists"); } TrackerInfo info = new TrackerInfo(in, coordinator.getID(), coordinator.getMetaInfo()); if (Snark.debug >= Snark.INFO) Snark.debug("TrackerClient response: " + info, Snark.INFO); lastRequestTime = System.currentTimeMillis(); String failure = info.getFailureReason(); if (failure != null) throw new IOException(failure); interval = info.getInterval() * 1000; return info; }
/** * Get the last modification date of a URL. * * @return last modified timestamp "as is" */ public static long getLastModified(URL url) throws IOException { if ("file".equals(url.getProtocol())) { // Optimize file: access. Also, this prevents throwing an exception if the file doesn't exist // as we try to close the stream below. return new File(URLDecoder.decode(url.getFile(), STANDARD_PARAMETER_ENCODING)).lastModified(); } else { // Use URLConnection final URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) ((HttpURLConnection) urlConnection).setRequestMethod("HEAD"); try { return getLastModified(urlConnection); } finally { final InputStream is = urlConnection.getInputStream(); if (is != null) is.close(); } } }
public static byte[] download(String urlString, String name) { int maxLength = 52428800; // 50MB URL url = null; boolean unknownLength = false; byte[] data = null; ; int n = 0; try { url = new URL(urlString); if (IJ.debugMode) IJ.log("PluginInstaller: " + urlString + " " + url); if (url == null) return null; URLConnection uc = url.openConnection(); int len = uc.getContentLength(); unknownLength = len < 0; if (unknownLength) len = maxLength; if (name != null) IJ.showStatus("Downloading " + url.getFile()); InputStream in = uc.getInputStream(); data = new byte[len]; int lenk = len / 1024; while (n < len) { int count = in.read(data, n, len - n); if (count < 0) break; n += count; if (name != null) IJ.showStatus("Downloading " + name + " (" + (n / 1024) + "/" + lenk + "k)"); IJ.showProgress(n, len); } in.close(); } catch (Exception e) { String msg = "" + e; if (!msg.contains("://")) msg += "\n " + urlString; IJ.error("Plugin Installer", msg); return null; } finally { IJ.showProgress(1.0); } if (name != null) IJ.showStatus(""); if (unknownLength) { byte[] data2 = data; data = new byte[n]; for (int i = 0; i < n; i++) data[i] = data2[i]; } return data; }
/** * Decides if the given source is newer than a class. * * @param source the source we may want to compile * @param cls the former class * @return true if the source is newer, false else * @throws IOException if it is not possible to open an connection for the given source * @see #getTimeStamp(Class) */ protected boolean isSourceNewer(URL source, Class cls) throws IOException { long lastMod; // Special handling for file:// protocol, as getLastModified() often reports // incorrect results (-1) if (isFile(source)) { // Coerce the file URL to a File // See ClassNodeResolver.isSourceNewer for another method that replaces '|' with ':'. // WTF: Why is this done and where is it documented? String path = source.getPath().replace('/', File.separatorChar).replace('|', ':'); File file = new File(path); lastMod = file.lastModified(); } else { URLConnection conn = source.openConnection(); lastMod = conn.getLastModified(); conn.getInputStream().close(); } long classTime = getTimeStamp(cls); return classTime + config.getMinimumRecompilationInterval() < lastMod; }
/** * Makes a POST request and returns the server response. * * @param urlString the URL to post to * @param nameValuePairs a map of name/value pairs to supply in the request. * @return the server reply (either from the input stream or the error stream) */ public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey(); String value = pair.getValue(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, "UTF-8")); } out.close(); Scanner in; StringBuilder response = new StringBuilder(); try { in = new Scanner(connection.getInputStream()); } catch (IOException e) { if (!(connection instanceof HttpURLConnection)) throw e; InputStream err = ((HttpURLConnection) connection).getErrorStream(); if (err == null) throw e; in = new Scanner(err); } while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } in.close(); return response.toString(); }
public void run() { try { fireConnecting(); URLConnection connection = fileURL.openConnection(); int max = connection.getContentLength(); InputStream in = connection.getInputStream(); OutputStream out = new FileOutputStream(fileDest); fireStarted(); fireProgressChange(0, max); { int count = 0; int b = 0; int readCount = 0; byte[] buffer = new byte[1024 * 10]; b = in.read(); while (!canceling && b >= 0) { out.write(b); count += 1; readCount = in.read(buffer, 0, buffer.length); out.write(buffer, 0, readCount); count += readCount; fireProgressChange(count, max); b = in.read(); } } in.close(); out.close(); if (!canceling) { fireDone(fileDest); } else { // fireCancel(fileDest); } } catch (Exception ex) { fireException(ex); ex.printStackTrace(); } }
public static String doPost(String urlString, Map<Object, Object> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setDoOutput(true); String encoding = connection.getContentEncoding(); if (encoding == null) encoding = "ISO-8859-1"; try (PrintWriter out = new PrintWriter(connection.getOutputStream())) { boolean first = true; for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey().toString(); String value = pair.getValue().toString(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, encoding)); } } StringBuilder response = new StringBuilder(); try (Scanner in = new Scanner(connection.getInputStream(), encoding)) { while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } } catch (IOException e) { if (!(connection instanceof HttpURLConnection)) throw e; InputStream err = ((HttpURLConnection) connection).getErrorStream(); if (err == null) throw e; Scanner in = new Scanner(err); response.append(in.nextLine()); response.append("\n"); } return response.toString(); }
public static String sendPost(String url, String params) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setDoOutput(true); conn.setDoInput(true); out = new PrintWriter(conn.getOutputStream()); out.print(params); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
byte[] getJar(String address) { byte[] data; boolean gte133 = version().compareTo("1.33u") >= 0; try { URL url = new URL(address); URLConnection uc = url.openConnection(); int len = uc.getContentLength(); String name = address.endsWith("ij/ij.jar") ? "daily build" : "ij.jar"; IJ.showStatus("Downloading ij.jar (" + IJ.d2s((double) len / 1048576, 1) + "MB)"); InputStream in = uc.getInputStream(); data = new byte[len]; int n = 0; while (n < len) { int count = in.read(data, n, len - n); if (count < 0) throw new EOFException(); n += count; if (gte133) IJ.showProgress(n, len); } in.close(); } catch (IOException e) { return null; } return data; }
public String urlReader(URL crowdFlower) { String jsonInput = ""; try { URLConnection yc = crowdFlower.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { jsonInput = jsonInput + inputLine; } in.close(); trapException(jsonInput); } catch (IOException e) { e.printStackTrace(); } catch (CrowdFlowerException e) { e.printStackTrace(); } return jsonInput; }
/** Unpacks a resource to a temp. file */ public static File unpackInstaller(String resourceName) { // Array to hold all results (this code is slightly more // generally that it needs to be) File[] results = new File[1]; URL[] urls = new URL[1]; // Determine size of download ClassLoader cl = Main.class.getClassLoader(); urls[0] = cl.getResource(Config.getInstallerResource()); if (urls[0] == null) { Config.trace("Could not find resource: " + Config.getInstallerResource()); return null; } int totalSize = 0; int totalRead = 0; for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { try { URLConnection connection = urls[i].openConnection(); totalSize += connection.getContentLength(); } catch (IOException ioe) { Config.trace("Got exception: " + ioe); return null; } } } // Unpack each file for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { // Create temp. file to store unpacked file in InputStream in = null; OutputStream out = null; try { // Use extension from URL (important for dll files) String extension = new File(urls[i].getFile()).getName(); int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1; if (lastdotidx == -1) { extension = ".dat"; } else { extension = extension.substring(lastdotidx); } // Create output stream results[i] = File.createTempFile("jre", extension); results[i].deleteOnExit(); out = new FileOutputStream(results[i]); // Create inputstream URLConnection connection = urls[i].openConnection(); in = connection.getInputStream(); int read = 0; byte[] buf = new byte[BUFFER_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); // Notify delegate totalRead += read; if (totalRead > totalSize && totalSize != 0) totalSize = totalRead; // Update UI if (totalSize != 0) { int percent = (100 * totalRead) / totalSize; setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent)); } } } catch (IOException ie) { Config.trace("Got exception while downloading resource: " + ie); for (int j = 0; j < results.length; j++) { if (results[j] != null) results[j].delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException io) { /* ignore */ } } } } setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK)); return results[0]; }
public static boolean showLicensing() { if (Config.getLicenseResource() == null) return true; ClassLoader cl = Main.class.getClassLoader(); URL url = cl.getResource(Config.getLicenseResource()); if (url == null) return true; String license = null; try { URLConnection con = url.openConnection(); int size = con.getContentLength(); byte[] content = new byte[size]; InputStream in = new BufferedInputStream(con.getInputStream()); in.read(content); license = new String(content); } catch (IOException ioe) { Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe); return false; } // Build dialog JTextArea ta = new JTextArea(license); ta.setEditable(false); final JDialog jd = new JDialog(_installerFrame, true); Container comp = jd.getContentPane(); jd.setTitle(Config.getLicenseDialogTitle()); comp.setLayout(new BorderLayout(10, 10)); comp.add(new JScrollPane(ta), "Center"); Box box = new Box(BoxLayout.X_AXIS); box.add(box.createHorizontalStrut(10)); box.add(new JLabel(Config.getLicenseDialogQuestionString())); box.add(box.createHorizontalGlue()); JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString()); JButton exitButton = new JButton(Config.getLicenseDialogExitString()); box.add(acceptButton); box.add(box.createHorizontalStrut(10)); box.add(exitButton); box.add(box.createHorizontalStrut(10)); jd.getRootPane().setDefaultButton(acceptButton); Box box2 = new Box(BoxLayout.Y_AXIS); box2.add(box); box2.add(box2.createVerticalStrut(5)); comp.add(box2, "South"); jd.pack(); final boolean accept[] = new boolean[1]; acceptButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = true; jd.hide(); jd.dispose(); } }); exitButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = false; jd.hide(); jd.dispose(); } }); // Apply any defaults the user may have, constraining to the size // of the screen, and default (packed) size. Rectangle size = new Rectangle(0, 0, 500, 300); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); size.width = Math.min(screenSize.width, size.width); size.height = Math.min(screenSize.height, size.height); // Center the window jd.setBounds( (screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2, size.width, size.height); // Show dialog jd.show(); return accept[0]; }
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { InputSource inputSource = null; if (options.entityResolver != null) { inputSource = options.entityResolver.resolveEntity(null, systemId); } if (inputSource == null) { inputSource = new InputSource(systemId); InputStream is = null; int redirects = 0; boolean redirect; URL url = JAXWSUtils.getFileOrURL(inputSource.getSystemId()); URLConnection conn = url.openConnection(); do { if (conn instanceof HttpsURLConnection) { if (options.disableSSLHostnameVerification) { ((HttpsURLConnection) conn).setHostnameVerifier(new HttpClientVerifier()); } } redirect = false; if (conn instanceof HttpURLConnection) { ((HttpURLConnection) conn).setInstanceFollowRedirects(false); } if (conn instanceof JarURLConnection) { if (conn.getUseCaches()) { doReset = true; conn.setDefaultUseCaches(false); c = conn; } } try { is = conn.getInputStream(); // is = sun.net.www.protocol.http.HttpURLConnection.openConnectionCheckRedirects(conn); } catch (IOException e) { if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = ((HttpURLConnection) conn); int code = httpConn.getResponseCode(); if (code == 401) { errorReceiver.error( new SAXParseException( WscompileMessages.WSIMPORT_AUTH_INFO_NEEDED( e.getMessage(), systemId, WsimportOptions.defaultAuthfile), null, e)); throw new AbortException(); } // FOR other code we will retry with MEX } throw e; } // handle 302 or 303, JDK does not seem to handle 302 very well. // Need to redesign this a bit as we need to throw better error message for IOException in // this case if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = ((HttpURLConnection) conn); int code = httpConn.getResponseCode(); if (code == 302 || code == 303) { // retry with the value in Location header List<String> seeOther = httpConn.getHeaderFields().get("Location"); if (seeOther != null && seeOther.size() > 0) { URL newurl = new URL(url, seeOther.get(0)); if (!newurl.equals(url)) { errorReceiver.info( new SAXParseException( WscompileMessages.WSIMPORT_HTTP_REDIRECT(code, seeOther.get(0)), null)); url = newurl; httpConn.disconnect(); if (redirects >= 5) { errorReceiver.error( new SAXParseException( WscompileMessages.WSIMPORT_MAX_REDIRECT_ATTEMPT(), null)); throw new AbortException(); } conn = url.openConnection(); inputSource.setSystemId(url.toExternalForm()); redirects++; redirect = true; } } } } } while (redirect); inputSource.setByteStream(is); } return inputSource; }
/** Receives an RPC response and converts to an object */ protected Object readResp() throws Exception { InputStream is = huc.getInputStream(); MessagePackObject mpo = MessagePack.unpack(is); return unMsg(mpo); }
/** Submits POST command to the server, and reads the reply. */ public boolean post( String url, String fileName, String cryptToken, String type, String path, String content, String comment) throws IOException { String sep = "89692781418184"; while (content.indexOf(sep) != -1) sep += "x"; String message = makeMimeForm(fileName, cryptToken, type, path, content, comment, sep); // for test // URL server = new URL("http", "localhost", 80, savePath); URL server = new URL(getCodeBase().getProtocol(), getCodeBase().getHost(), getCodeBase().getPort(), url); URLConnection connection = server.openConnection(); connection.setAllowUserInteraction(false); connection.setDoOutput(true); // connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + sep); connection.setRequestProperty("Content-length", Integer.toString(message.length())); // System.out.println(url); String replyString = null; try { DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(message); out.close(); // System.out.println("Wrote " + message.length() + // " bytes to\n" + connection); try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String reply = null; while ((reply = in.readLine()) != null) { if (reply.startsWith("ERROR ")) { replyString = reply.substring("ERROR ".length()); } } in.close(); } catch (IOException ioe) { replyString = ioe.toString(); } } catch (UnknownServiceException use) { replyString = use.getMessage(); System.out.println(message); } if (replyString != null) { // System.out.println("---- Reply " + replyString); if (replyString.startsWith("URL ")) { URL eurl = getURL(replyString.substring("URL ".length())); getAppletContext().showDocument(eurl); } else if (replyString.startsWith("java.io.FileNotFoundException")) { // debug; when run from appletviewer, the http connection // is not available so write the file content if (path.endsWith(".draw") || path.endsWith(".map")) System.out.println(content); } else showStatus(replyString); return false; } else { showStatus(url + " saved"); return true; } }
public void actionPerformed(ActionEvent e) { SpinnerNumberModel m = ((SpinnerNumberModel) daysnr.getModel()); int days = m.getNumber().intValue(); String location = ((JTextField) loc).getText(); java.util.List<PointOfInterest> points = parent.textFieldPoints(location); if (!points.isEmpty()) { double latitude = points.get(0).getLatlon().latitude.getDegrees(), longitude = points.get(0).getLatlon().longitude.getDegrees(); // we want only the firs two decimals latitude = ((double) ((long) (latitude * 100))) / 100; longitude = ((double) ((long) (latitude * 100))) / 100; String APIKey = "65ea00ff33143650113112"; String address = "http://free.worldweatheronline.com/feed/weather.ashx?" + "key=" + APIKey + "&num_of_days=" + days + "&q=" + latitude + "," + longitude + "&format=json&cc=no"; try { URL link = new URL(address); URLConnection yc = link.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); Vector<WeatherElements> elem = new Vector<WeatherElements>(); String jsonFile = in.readLine(); int i1 = 0, i2 = 0; for (int i = 0; i < days; i++) { i1 = jsonFile.indexOf("\"date\"", i2) + 9; i2 = jsonFile.indexOf("\"", i1); String date = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"precipMM\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String rain = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"tempMaxC\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String tempMax = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"tempMinC\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String tempMin = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"value\"", i2) + 10; i2 = jsonFile.indexOf("\"", i1); String weatherStatus = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"value\"", i2) + 10; i2 = jsonFile.indexOf("\"", i1); String imgLink = jsonFile.substring(i1, i2); imgLink = imgLink.replace("\\", ""); i2++; i1 = jsonFile.indexOf("\"winddirDegree\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windDirDegree = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"winddirection\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windDir = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"windspeedKmph\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windSpeed = jsonFile.substring(i1, i2); i2++; WeatherElements o = new WeatherElements( date, rain, tempMax, tempMin, weatherStatus, imgLink, windDirDegree, windDir, windSpeed); elem.add(o); } weatherIcon.setVisible(true); dateout.setText(elem.elementAt(0).date); weatherIcon.setText("<html><img src=\"" + elem.elementAt(0).imgLink + "\" /></html>"); weatherstatus.setText("<html><h1>" + elem.elementAt(0).weatherStatus + "</h1></html>"); temperature.setText( "<html>Temperatures:<br />Temp min: " + elem.elementAt(0).tempMin + "°C<br />Temp max: " + elem.elementAt(0).tempMax + "°C</html>"); rain.setText("Rain: " + elem.elementAt(0).rain + " mm"); wind.setText( "<html>Wind: <br />" + "<img src=\"http://www.worldweatheronline.com" + "/App_Themes/Default/images/wind/" + elem.elementAt(0).windDir + ".png\" /><br />" + "Wind speed: " + elem.elementAt(0).windSpeed + "Km/h<br />" + elem.elementAt(0).windDir + "(" + elem.elementAt(0).windDirDegree + "°)</html>"); buttons.removeAll(); pageNum.removeAll(); buttons.updateUI(); pageNum.updateUI(); JButton previous = new JButton("Previous"); previous.setEnabled(false); previous.setName("prev"); JButton next = new JButton("Next"); next.setName("next"); if (days == 1) { next.setEnabled(false); } JTextField current = new JTextField("1", 3); current.setEditable(false); JTextField maxNum = new JTextField("" + elem.size(), 3); maxNum.setEditable(false); pageNum.add(current); pageNum.add(maxNum); previous.addActionListener( new WeatherButtonsActionListener( previous, next, weatherIcon, dateout, weatherstatus, temperature, rain, wind, elem, current)); next.addActionListener( new WeatherButtonsActionListener( previous, next, weatherIcon, dateout, weatherstatus, temperature, rain, wind, elem, current)); buttons.add(next); buttons.add(previous); JButton genHTML = new JButton("Generate HTML"); genHTML.addActionListener(new genHTMLWeatherReport(parent, elem)); buttons.add(genHTML); } catch (Exception ex) { parent.standardDialogBox("Fetching data error", "Somethnig goes wrong with the connection"); } } else { parent.standardDialogBox("Incorrect input", "Input is incorrect!"); } }