/** * This method returns the entire result from the HTTP response. * * @param url The URL to fetch the HTTP response from. * @return The contents of the HTTP response, null if no response * @throws IOException Related to network and stream reading */ public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); String response = null; if (hasInput) { response = scanner.next(); } scanner.close(); return response; } finally { urlConnection.disconnect(); } }
public synchronized Image getImage(URL url) { Object o = imageCache.get(url); if (o != null) { return (Image)o; } try { o = url.getContent(); if (o == null) { return null; } if (o instanceof Image) { imageCache.put(url, o); return (Image) o; } // Otherwise it must be an ImageProducer. Image img = target.createImage((java.awt.image.ImageProducer)o); imageCache.put(url, img); return img; } catch (Exception ex) { return null; } }
@SmallTest @Feature({"Cronet"}) @CompareDefaultWithCronet public void testAddAndSetRequestPropertyWithSameKey() throws Exception { URL url = new URL(NativeTestServer.getEchoAllHeadersURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.addRequestProperty("header-name", "value1"); connection.setRequestProperty("Header-nAme", "value2"); // Before connection is made, check request headers are set. assertEquals("value2", connection.getRequestProperty("header-namE")); Map<String, List<String>> requestHeadersMap = connection.getRequestProperties(); assertEquals(1, requestHeadersMap.get("HeAder-name").size()); assertEquals("value2", requestHeadersMap.get("HeAder-name").get(0)); // Check the request headers echoed back by the server. assertEquals(200, connection.getResponseCode()); assertEquals("OK", connection.getResponseMessage()); String headers = TestUtil.getResponseAsString(connection); List<String> actualValues = getRequestHeaderValues(headers, "Header-nAme"); assertEquals(1, actualValues.size()); assertEquals("value2", actualValues.get(0)); connection.disconnect(); }
public TemplateLoader load() { try { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); urlConnection.setUseCaches(false); urlConnection.connect(); Files.copy(urlConnection.getInputStream(), Paths.get(dest)); ((HttpURLConnection)urlConnection).disconnect(); } catch (IOException e) { e.printStackTrace(); } return this; }
@NotNull @Override public List<URL> getRegisteredMavenRepositories() { if(registeredMavenRepositories == null || registeredMavenRepositories.get() == null) { registeredMavenRepositories = new SoftReference<>(Collections.unmodifiableList( orionCore.modMavenRepositories.stream().map(u -> { try { return u.toURL(); } catch (MalformedURLException e) { SneakyThrow.throwException(e); return null; } }) .collect(Collectors.toList()) )); } return Objects.requireNonNull(registeredMavenRepositories.get()); // Should not throw NPE }
/** * Retrieve the URL of the page that contains the login form */ private void fetchLoginUrl() { Log.d(TAG, "fetching login URL..."); mRequestFactory.get( "https://stackexchange.com/users/signin", true, new RequestListener() { @Override public void onSucceeded(URL url, String data) { mListener.authProgress(20); mLoginUrl = data; fetchNetworkFkey(); } } ); }
static Business businessFrom(JSONObject information) { try { return new Business( information.getDouble("rating"), information.has("price") ? PricingLevel.fromSymbol(information.getString("price")) : PricingLevel.NONE, information.getString("phone"), information.getString("id"), information.getBoolean("is_closed"), buildCategories(information.getJSONArray("categories")), information.getInt("review_count"), information.getString("name"), new URL(information.getString("url")), CoordinatesParser.from(information.getJSONObject("coordinates")), !information.getString("image_url").trim().isEmpty() ? new URL(information.getString("image_url")) : null, LocationParser.from(information.getJSONObject("location")), !information.isNull("distance") ? Distance.inMeters(information.getDouble("distance")) : null, buildTransactions(information.getJSONArray("transactions")) ); } catch (JSONException | MalformedURLException exception) { throw ParsingFailure.producedBy(information, exception); } }
@Override protected EpubPublication doInBackground(String... urls) { String strUrl = urls[0]; try { URL url = new URL(strUrl); URLConnection urlConnection = url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString()); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class); } catch (IOException e) { Log.e(TAG, "SpineListTask error " + e); } return null; }
/** * <b>LISTSTATUS</b> * * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS" * * @param path * @return * @throws MalformedURLException * @throws IOException * @throws AuthenticationException */ public String listStatus(String path) throws MalformedURLException, IOException, AuthenticationException { ensureValidToken(); System.out.println("Token = "+token.isSet()); HttpURLConnection conn = authenticatedURL.openConnection( new URL(new URL(httpfsUrl), MessageFormat.format( "/webhdfs/v1/{0}?op=LISTSTATUS", URLUtil.encodePath(path))), token); conn.setRequestMethod("GET"); conn.connect(); String resp = result(conn, true); conn.disconnect(); return resp; }
protected void scanJar(URL jarUrl, Map<String, ResourceInfo> resInfos) throws IOException { JarInputStream jarInput = new JarInputStream(jarUrl.openStream(), false); JarEntry entry = null; while((entry = jarInput.getNextJarEntry()) != null) { String entryName = entry.getName(); if(entryName != null && entryName.endsWith(".class")) { final String className = entryName.substring(0, entryName.length() - 6).replace('/', '.'); if(!resInfos.containsKey(className)) { ClassReader classReader = new ClassReader(jarInput); ResourceInfo resInfo = new ResourceInfo(null, className, null); ResourceInfoVisitor visitor = new ResourceInfoVisitor(resInfo); classReader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); if(visitor.isCreoleResource()) { resInfos.put(className, resInfo); } } } } jarInput.close(); }
private Document getLargestImagePageDocument(URL url) throws IOException { // Get current page Document doc = Http.url(url).get(); // Look for larger image page String largestImagePage = this.url.toExternalForm(); for (Element olSize : doc.select("ol.sizes-list > li > ol > li")) { Elements ola = olSize.select("a"); if (ola.size() == 0) { largestImagePage = this.url.toExternalForm(); } else { String candImage = ola.get(0).attr("href"); if (candImage.startsWith("/")) { candImage = "http://www.flickr.com" + candImage; } largestImagePage = candImage; } } if (!largestImagePage.equals(this.url.toExternalForm())) { // Found larger image page, get it. doc = Http.url(largestImagePage).get(); } return doc; }
/** * Download the most recent fsimage from the name node, and save it to a local * file in the given directory. * * @param argv * List of of command line parameters. * @param idx * The index of the command that is being processed. * @return an exit code indicating success or failure. * @throws IOException */ public int fetchImage(final String[] argv, final int idx) throws IOException { Configuration conf = getConf(); final URL infoServer = DFSUtil.getInfoServer( HAUtil.getAddressOfActive(getDFS()), conf, DFSUtil.getHttpClientScheme(conf)).toURL(); SecurityUtil.doAsCurrentUser(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { TransferFsImage.downloadMostRecentImageToDirectory(infoServer, new File(argv[idx])); return null; } }); return 0; }
private String getDocEncoding(URL root) { assert root != null && root.toString().endsWith("/") : root; InputStream is = URLUtils.open(root, "index-all.html", "index-files/index-1.html"); if (is != null) { try { try { ParserDelegator pd = new ParserDelegator(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); EncodingCallback ecb = new EncodingCallback(in); pd.parse(in, ecb, true); return ecb.getEncoding(); } finally { is.close(); } } catch (IOException x) { LOG.log(Level.FINE, "Getting encoding from " + root, x); } } return null; }
@Test public void proxyWithConnectionClose() throws IOException { server.useHttps(sslClient.socketFactory, true); server.enqueue( new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("this response comes via a proxy")); urlFactory.setClient(urlFactory.client().newBuilder() .proxy(server.toProxyAddress()) .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager) .hostnameVerifier(new RecordingHostnameVerifier()) .build()); URL url = new URL("https://android.com/foo"); connection = urlFactory.open(url); connection.setRequestProperty("Connection", "close"); assertContent("this response comes via a proxy", connection); }
@Override protected Void doInBackground(Integer... params) { for (Integer cur : params) { remote = cur; try { URLConnection connection = new URL(Utils.BASE_URL_PHP + "updateViewTracker.php?remote=" + remote) .openConnection(); connection.getInputStream(); Utils.getController().getPreferences() .edit() .putString("pref_key_cache_vieweditems", getNewCacheString()) .apply(); } catch (IOException e) { Utils.logError(e); } } return null; }
private void process(String resource, String charset) throws Exception { Console.out.println("Processing " + resource + "..."); URL rurl = getClass().getResource("/charsets/" + resource); String file = rurl.getPath(); long before = System.currentTimeMillis(); ASTClassList parsed = parseClasses(file, charset); TCClassList classes = ClassMapper.getInstance(TCNode.MAPPINGS).init().convert(parsed); long after = System.currentTimeMillis(); Console.out.println("Parsed " + classes.size() + " classes in " + (double)(after-before)/1000 + " secs. "); before = System.currentTimeMillis(); TypeChecker typeChecker = new ClassTypeChecker(classes); typeChecker.typeCheck(); after = System.currentTimeMillis(); Console.out.println("Type checked in " + (double)(after-before)/1000 + " secs. "); Console.out.println("There were " + TypeChecker.getWarningCount() + " warnings"); assertEquals("Type check errors", 0, TypeChecker.getErrorCount()); }
public List<URL> getURLs() { if( _loader instanceof URLClassLoader ) { URL[] urls = ((URLClassLoader)_loader).getURLs(); return urls == null ? Collections.emptyList() : Arrays.asList( urls ); } List<URL> allUrls = new ArrayList<>( getClasspathUrls() ); if( JreUtil.isJava9Modular_runtime() ) { allUrls.addAll( getModularUrls() ); } return Collections.unmodifiableList( allUrls ); }
@Override public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException { final URL foUrl = fo.toUri().toURL(); for (Set<Location> s : listLocationsForModules(location)) { for (Location l : s) { ModuleLocation ml = ModuleLocation.cast(l); for (URL root : ml.getModuleRoots()) { if (FileObjects.isParentOf(root, foUrl)) { return l; } } } } return null; }
private Bitmap getBitmapFromUrl(String url) { Bitmap bitmap = null; try { URLConnection conn = new URL(url).openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent()); } catch (Exception e) { e.printStackTrace(); } return bitmap; }
/** * Sends the data to the bStats server. * * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(JSONObject data) throws Exception { if (data == null) { throw new IllegalArgumentException("Data cannot be null!"); } if (Bukkit.isPrimaryThread()) { throw new IllegalAccessException("This method must not be called from the main thread!"); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response - Just send our data :) }
/** * Check the protocol used in the systemId against allowed protocols * * @param systemId the Id of the URI * @param allowedProtocols a list of allowed protocols separated by comma * @param accessAny keyword to indicate allowing any protocol * @return the name of the protocol if rejected, null otherwise */ public static String checkAccess(String systemId, String allowedProtocols, String accessAny) throws IOException { if (systemId == null || (allowedProtocols != null && allowedProtocols.equalsIgnoreCase(accessAny))) { return null; } String protocol; if (systemId.indexOf(":")==-1) { protocol = "file"; } else { URL url = new URL(systemId); protocol = url.getProtocol(); if (protocol.equalsIgnoreCase("jar")) { String path = url.getPath(); protocol = path.substring(0, path.indexOf(":")); } else if (protocol.equalsIgnoreCase("jrt")) { // if the systemId is "jrt" then allow access if "file" allowed protocol = "file"; } } if (isProtocolAllowed(protocol, allowedProtocols)) { //access allowed return null; } else { return protocol; } }
private static InputStream openInputStream(String resName, ClassLoader loader, boolean reload) throws IOException { if (reload) { URL url = loader.getResource(resName); if (url != null) { URLConnection urlCx = url.openConnection(); urlCx.setUseCaches(false); return urlCx.getInputStream(); } return null; } return loader.getResourceAsStream(resName); }
private void maybeUpdateDefaultJavadoc() { if (javadocRoots.length == 0) { URL[] defaults = getDefaultJavadocRoots(); if (defaults != null) { javadocRoots = defaults; pcs.firePropertyChange(JavadocRootsProvider.PROP_JAVADOC_ROOTS, null, null); } } }
public static URL fileAsUrl(File file) { try { return file.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
@DetourCall public static URLConnection openConnection(URL url) throws IOException { URLConnection conn = url.openConnection(); if (conn instanceof HttpsURLConnection) { return new HttpsURLConnectionWrapper((HttpsURLConnection) conn); } if (conn instanceof HttpURLConnection) { return new HttpURLConnectionWrapper((HttpURLConnection) conn); } return conn; }
private boolean urlExists(String url) { try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); if (connection.getResponseCode() != 200) { throw new IOException("Couldn't find full-size image at " + url); } return true; } catch (IOException e) { return false; } }
/** make sure if a plugin is compiled against the same ES version, it works */ public void testGoodESVersionInJar() throws Exception { Path dir = createTempDir(); Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0"); attributes.put(new Attributes.Name("X-Compile-Elasticsearch-Version"), Version.CURRENT.toString()); URL[] jars = {makeJar(dir, "foo.jar", manifest, "Foo.class")}; JarHell.checkJarHell(jars); }
static URL qualifyHost(URL url) { try { InetAddress a = InetAddress.getByName(url.getHost()); String qualHost = a.getCanonicalHostName(); URL q = new URL(url.getProtocol(), qualHost, url.getPort(), url.getFile()); return q; } catch (IOException io) { return url; } }
/** * Get the pathname to the webapps files. * @param appName eg "secondary" or "datanode" * @return the pathname as a URL * @throws FileNotFoundException if 'webapps' directory cannot be found on CLASSPATH. */ protected String getWebAppsPath(String appName) throws FileNotFoundException { URL url = getClass().getClassLoader().getResource("webapps/" + appName); if (url == null) throw new FileNotFoundException("webapps/" + appName + " not found in CLASSPATH"); String urlString = url.toString(); return urlString.substring(0, urlString.lastIndexOf('/')); }
@Override @Nullable public URL getBasePageUrl() { ContentViewCore baseContentViewCore = getBaseContentView(); if (baseContentViewCore == null) return null; try { return new URL(baseContentViewCore.getWebContents().getUrl()); } catch (MalformedURLException e) { return null; } }
public EfectosSonido(){ URL url = getClass().getResource("laser.WAV"); clipShoot = Applet.newAudioClip(url); url = getClass().getResource("explosion.wav"); clipExplosion = Applet.newAudioClip(url); url = getClass().getResource("Beep.WAV"); clipClick = Applet.newAudioClip(url); }
/** * Tjek for om vi er på et netværk der kræver login eller lignende. * Se 'Handling Network Sign-On' i http://developer.android.com/reference/java/net/HttpHttpURLConnection.html */ private static void tjekOmdirigering(URL u, HttpURLConnection urlConnection) throws IOException { URL u2 = urlConnection.getURL(); if (!u.getHost().equals(u2.getHost())) { // Vi blev omdirigeret Log.d("tjekOmdirigering " + u); Log.d("tjekOmdirigering " + u2); //Log.rapporterFejl(omdirigeringsfejl); throw new UnknownHostException("Der blev omdirigeret fra " + u.getHost() + " til " + u2.getHost()); } }
protected void retrieveRemoteImage(final TextureTile tile, String mimeType, int timeout) throws Exception { // TODO: apply retriever-factory pattern for remote retrieval case. final URL resourceURL = tile.getResourceURL(mimeType); if (resourceURL == null) return; Retriever retriever; String protocol = resourceURL.getProtocol(); if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) { retriever = new HTTPRetriever(resourceURL, new CompositionRetrievalPostProcessor(tile)); retriever.setValue(URLRetriever.EXTRACT_ZIP_ENTRY, "true"); // supports legacy layers } else { String message = Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL); throw new RuntimeException(message); } Logging.logger().log(java.util.logging.Level.FINE, "Retrieving " + resourceURL.toString()); retriever.setConnectTimeout(10000); retriever.setReadTimeout(timeout); retriever.call(); }
@Override public void initialize(URL location, ResourceBundle resources) { configuringFileChooser(fileChooser); initTable(); initRightClick(); initDragDrop(); initDefaultChk(); }
private File extractNativeLibraries(final File nativesDirectory, final String libraryPath) { final URL libraryUrl = Thread.currentThread().getContextClassLoader().getResource(libraryPath); if (libraryUrl == null) { throw new IllegalArgumentException( String.format("Unable to find native binary %s for library %s", libraryPath, key)); } final String libraryName; libraryName = FilenameUtils.getName(libraryPath); final File libraryFile = new File(nativesDirectory, libraryName); libraryFile.getParentFile().mkdirs(); try { final URLConnection urlConnection = libraryUrl.openConnection(); try (final InputStream inputStream = urlConnection.getInputStream()) { try (final OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(libraryFile))) { IOUtils.copy(inputStream, outputStream); } } } catch (final Exception exception) { throw new RuntimeException(exception); } if (deleteOnExit) { libraryFile.deleteOnExit(); } // TODO make accessible for linux and mac return libraryFile; }
public static void main(String[] args) throws Exception { String serverName = "example.com"; String userName = "hoge"; String password = "fuga"; String url = "https://" + serverName + "/sdk"; ManagedObjectReference siRef; VimServiceLocator locator; VimPortType service; ServiceContent siContent; System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); siRef = new ManagedObjectReference(); siRef.setType("ServiceInstance"); siRef.set_value("ServiceInstance"); locator = new VimServiceLocator(); locator.setMaintainSession(true); service = locator.getVimPort(new URL(url)); siContent = service.retrieveServiceContent(siRef); if (siContent.getSessionManager() != null) { service.login(siContent.getSessionManager(), userName, password, null); } refresh(service, siContent); collectProperties(service, siContent); service.logout(siContent.getSessionManager()); service = null; siContent = null; }
@Before public void setup() throws Exception { URL sourceUrl = this.getClass().getResource("/"); rootPath = new File(sourceUrl.getFile()); if (!rootPath.exists()) { throw new Exception("Cannot find base path for test!"); } outputPath = folder.newFolder("output"); config = ConfigUtil.load(rootPath); }
public void test168923c() throws Exception { // #168923 - [Move] refactoring a package doesn't update star imports [68cat] writeFilesAndWaitForScan(src, new File("t/package-info.java", "package t;"), new File("A.java", "import u.*; import u.B; public class A { public void foo() { int d = B.c; } }"), new File("u/B.java", "package u; public class B { public static int c = 5; }")); performMoveClass(Lookups.singleton(src.getFileObject("u/B.java")), new URL(src.getURL(), "t/")); verifyContent(src, new File("t/package-info.java", "package t;"), new File("A.java", "import t.B; public class A { public void foo() { int d = B.c; } }"), new File("t/B.java", "package t; public class B { public static int c = 5; }")); }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
public static String checkForRedirect(String url) { try { HttpURLConnection con = (HttpURLConnection) new URL( url ).openConnection(); if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) { url = con.getHeaderField("Location"); } } catch(IOException e) { e.printStackTrace(); } return url; }