List of usage examples for java.net URL toExternalForm
public String toExternalForm()
From source file:it.geosolutions.httpproxy.callback.RequestTypeChecker.java
public void onRequest(HttpServletRequest request, HttpServletResponse response, URL url) throws IOException { loadPatterns();/*from www.ja va 2 s . c om*/ // ////////////////////////////////////// // Check off the request type // provided vs. permitted request types // ////////////////////////////////////// String urlExtForm = url.toExternalForm(); boolean check = false; for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(urlExtForm); if (matcher.matches()) { check = true; break; } } if (!check) throw new HttpErrorException(403, "Request Type" + " is not among the ones allowed for this proxy"); }
From source file:com.boundlessgeo.geoserver.api.controllers.IO.java
private static String source(URL url, GeoServerDataDirectory dataDir) { File baseDirectory = dataDir.getResourceLoader().getBaseDirectory(); if (url.getProtocol().equals("file")) { File file = Files.url(baseDirectory, url.toExternalForm()); if (file != null && !file.isAbsolute()) { return Paths.convert(baseDirectory, file); }/*from w w w . j av a 2 s . co m*/ } return url.toExternalForm(); }
From source file:com.opera.core.systems.OperaPaths.java
/** * Tries to load the launcher executable from the jar file A copy of the * launcher is put into user directory and on each call is compared to the * content in jar file/* w w w. j av a2 s . c o m*/ * * @return path to launcher executable */ public String getOperaLauncherPath() { String launcherName = getLauncherNameForOS(); String executablePath = null; // Get the launcher path URL res = OperaDriver.class.getClassLoader().getResource("launcher/" + launcherName); if (res != null) { String url = res.toExternalForm(); // If the launcher is inside the jar we will need to copy it out if ((url.startsWith("jar:")) || (url.startsWith("wsjar:"))) { executablePath = FileUtils.getUserDirectoryPath() + File.separatorChar + ".launcher" + File.separatorChar + launcherName; File cur_launcher = new File(executablePath); // Whether we need to copy a new launcher across, either because // it doesn't currently exist, or because its hash differs from // our launcher boolean copy = false; if (!cur_launcher.exists()) { copy = true; } else { try { // Copy if launchers don't match copy = !Arrays.equals(md5(executablePath), md5(res.openStream())); } catch (Exception e) { copy = true; } } if (copy == true) { try { if (!cur_launcher.exists()) FileUtils.touch(cur_launcher); InputStream is = res.openStream(); OutputStream os = new FileOutputStream(cur_launcher); IOUtils.copy(is, os); is.close(); os.close(); cur_launcher.setLastModified(cur_launcher.lastModified()); } catch (IOException e) { throw new WebDriverException("Cant write file to disk : " + e.getMessage()); } logger.fine("New launcher copied"); } // If launcher is not inside jar we can run it from it's current // location } else if (url.startsWith("file:")) { File f; try { f = new File(res.toURI()); } catch (URISyntaxException e) { f = new File(res.getPath()); } executablePath = f.getAbsolutePath(); } } if (executablePath != null) makeLauncherExecutable(executablePath); return executablePath; }
From source file:io.selendroid.standalone.server.grid.SelfRegisteringRemote.java
public void performRegistration() throws Exception { String tmp = config.getRegistrationUrl(); HttpClient client = HttpClientUtil.getHttpClient(); URL registration = new URL(tmp); if (log.isLoggable(Level.INFO)) { log.info("Registering selendroid node to Selenium Grid hub :" + registration); }//from w w w . j a v a2 s . c o m BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm()); JSONObject nodeConfig = getNodeConfig(); String nodeConfigString = nodeConfig.toString(); if (log.isLoggable(Level.INFO)) { log.info("Registering selendroid node with following config:\n" + nodeConfigString); } r.setEntity(new StringEntity(nodeConfigString)); HttpHost host = new HttpHost(registration.getHost(), registration.getPort()); HttpResponse response = client.execute(host, r); if (response.getStatusLine().getStatusCode() != 200) { throw new SelendroidException("Error sending the registration request."); } }
From source file:net.sf.jasperreports.engine.xml.BaseSaxParserFactory.java
protected String getResourceURI(String resource) { URL location = JRLoader.getResource(resource); if (location == null) { throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_RESOURCE_NOT_FOUND, new Object[] { resource }); }//from w w w.j a va 2 s . com return location.toExternalForm(); }
From source file:fr.jayasoft.ivy.url.HttpClientHandler.java
private GetMethod doGet(URL url) throws IOException, HttpException { HttpClient client = getClient(url);// w ww.java 2 s . c o m GetMethod get = new GetMethod(url.toExternalForm()); get.setDoAuthentication(useAuthentication(url) || useProxyAuthentication()); client.executeMethod(get); return get; }
From source file:com.digitalpebble.stormcrawler.tika.ParserBolt.java
private List<Outlink> toOutlinks(String parentURL, List<Link> links, Metadata parentMetadata) { Map<String, Outlink> outlinks = new HashMap<String, Outlink>(); URL url_;// w w w . ja v a 2 s . co m try { url_ = new URL(parentURL); } catch (MalformedURLException e1) { // we would have known by now as previous // components check whether the URL is valid LOG.error("MalformedURLException on {}", parentURL); eventCounter.scope("error_invalid_source_url").incrBy(1); return new LinkedList<Outlink>(); } for (Link l : links) { if (StringUtils.isBlank(l.getUri())) { continue; } String urlOL; // build an absolute URL try { URL tmpURL = URLUtil.resolveURL(url_, l.getUri()); urlOL = tmpURL.toExternalForm(); } catch (MalformedURLException e) { LOG.debug("MalformedURLException on {}", l.getUri()); eventCounter.scope("error_outlink_parsing_" + e.getClass().getSimpleName()).incrBy(1); continue; } // applies the URL filters if (urlFilters != null) { urlOL = urlFilters.filter(url_, parentMetadata, urlOL); if (urlOL == null) { eventCounter.scope("outlink_filtered").incrBy(1); continue; } } eventCounter.scope("outlink_kept").incrBy(1); Outlink ol = new Outlink(urlOL); // add the anchor ol.setAnchor(l.getText()); // get the metadata for the outlink from the parent ones ol.setMetadata(metadataTransfer.getMetaForOutlink(urlOL, parentURL, parentMetadata)); // keep only one instance of outlink per URL Outlink ol2 = outlinks.get(urlOL); if (ol2 == null) { outlinks.put(urlOL, ol); } } return new ArrayList<Outlink>(outlinks.values()); }
From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java
/** * uses the hub API to get some of its configuration. * @param parameters list of the parameter to be retrieved from the hub * @return// w w w. ja v a2s . c o m * @throws Exception */ private JSONObject getHubConfiguration(String... parameters) throws Exception { String hubApi = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/hub"; HttpClient client = httpClientFactory.getHttpClient(); URL api = new URL(hubApi); HttpHost host = new HttpHost(api.getHost(), api.getPort()); String url = api.toExternalForm(); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url); JSONObject j = new JSONObject(); JSONArray keys = new JSONArray(); j.put("configuration", keys); r.setEntity(new StringEntity(j.toString())); HttpResponse response = client.execute(host, r); return extractObject(response); }
From source file:com.brienwheeler.apps.tomcat.TomcatBean.java
private void extractWarFile() { if (webAppBase != null && webAppBase.length() > 0) { ProtectionDomain protectionDomain = this.getClass().getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); log.info("detected run JAR at " + location); if (!location.toExternalForm().startsWith("file:") || !location.toExternalForm().endsWith(".jar")) throw new IllegalArgumentException("invalid code location: " + location); try {// w w w. j av a2s.co m ZipFile zipFile = new ZipFile(new File(location.toURI())); Enumeration<? extends ZipEntry> entryEnum = zipFile.entries(); ZipEntry warEntry = null; while (entryEnum.hasMoreElements()) { ZipEntry entry = entryEnum.nextElement(); String entryName = entry.getName(); if (entryName.startsWith(webAppBase) && entryName.endsWith(".war")) { warEntry = entry; break; } } if (warEntry == null) throw new RuntimeException("can't find JAR entry for " + webAppBase + "*.war"); log.info("extracting WAR file " + warEntry.getName()); // extract web app WAR to current directory InputStream inputStream = zipFile.getInputStream(warEntry); OutputStream outputStream = new FileOutputStream(new File(warEntry.getName())); byte buf[] = new byte[1024]; int nread; while ((nread = inputStream.read(buf, 0, 1024)) > 0) { outputStream.write(buf, 0, nread); } outputStream.close(); inputStream.close(); zipFile.close(); String launchContextRoot = contextRoot != null ? contextRoot : webAppBase; if (!launchContextRoot.startsWith("/")) launchContextRoot = "/" + launchContextRoot; log.info("launching WAR file " + warEntry.getName() + " at context root " + launchContextRoot); // add web app to Tomcat Context context = tomcat.addWebapp(launchContextRoot, warEntry.getName()); if (context instanceof StandardContext) ((StandardContext) context).setUnpackWAR(false); } catch (Exception e) { throw new RuntimeException("error extracting WAR file", e); } } }
From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPDigestUnitTestCase.java
@Test public void testDigestAuth() throws Exception { URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try {/*from w w w . ja va2 s.co m*/ String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); Header header = headers[0]; String value = header.getValue(); value = value.substring(7).trim(); String[] tokens = HTTPDigestUtil.quoteTokenize(value); DigestHolder digestHolder = HTTPDigestUtil.digest(tokens); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("algorithm", "MD5"); digestAuth.overrideParamter("realm", digestHolder.getRealm()); digestAuth.overrideParamter("nonce", digestHolder.getNonce()); digestAuth.overrideParamter("qop", "auth"); digestAuth.overrideParamter("nc", "0001"); digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce()); digestAuth.overrideParamter("opaque", digestHolder.getOpaque()); httpget = new HttpGet(url.toExternalForm()); Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget); System.out.println(auth.getName()); System.out.println(auth.getValue()); httpget.setHeader(auth); System.out.println("executing request" + httpget.getRequestLine()); response = httpclient.execute(httpget); entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }