List of usage examples for java.net URL toExternalForm
public String toExternalForm()
From source file:de.highbyte_le.weberknecht.ControllerCore.java
private void doRedirect(HttpServletRequest request, HttpServletResponse response, String redirectDestination) throws MalformedURLException { URL reqURL = new URL(request.getRequestURL().toString()); URL dest = new URL(reqURL, redirectDestination); response.setHeader("Location", dest.toExternalForm()); response.setStatus(303); //303 - "see other" (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) }
From source file:net.sourceforge.eclipsetrader.yahoo.FrenchNewsProvider.java
private void update(URL feedUrl, Security security) { System.out.println("Fetching " + feedUrl.toExternalForm()); //$NON-NLS-1$ boolean subscribersOnly = YahooPlugin.getDefault().getPreferenceStore() .getBoolean(YahooPlugin.PREFS_SHOW_SUBSCRIBERS_ONLY); try {/* w w w . j a va 2 s .co m*/ HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext(); ServiceReference reference = context.getServiceReference(IProxyService.class.getName()); if (reference != null) { IProxyService proxy = (IProxyService) context.getService(reference); IProxyData data = proxy.getProxyDataForHost(feedUrl.getHost(), IProxyData.HTTP_PROXY_TYPE); if (data != null) { if (data.getHost() != null) client.getHostConfiguration().setProxy(data.getHost(), data.getPort()); if (data.isRequiresAuthentication()) client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(data.getUserId(), data.getPassword())); } } SyndFeed feed = fetcher.retrieveFeed(feedUrl, client); for (Iterator iter = feed.getEntries().iterator(); iter.hasNext();) { SyndEntry entry = (SyndEntry) iter.next(); if (!subscribersOnly && entry.getTitle().indexOf("[$$]") != -1) //$NON-NLS-1$ continue; NewsItem news = new NewsItem(); news.setRecent(true); Date entryDate = entry.getPublishedDate(); if (entry.getUpdatedDate() != null) entryDate = entry.getUpdatedDate(); if (entryDate != null) { Calendar date = Calendar.getInstance(); date.setTime(entryDate); date.set(Calendar.SECOND, 0); news.setDate(date.getTime()); } String title = entry.getTitle(); if (title.endsWith(")")) //$NON-NLS-1$ { int s = title.lastIndexOf('('); if (s != -1) { news.setSource(title.substring(s + 1, title.length() - 1)); title = title.substring(0, s - 1).trim(); } } news.setTitle(title); news.setUrl(entry.getLink()); if (security != null) news.addSecurity(security); // System.out.println("** News found:"); // System.out.println(news.getTitle()); // System.out.println(news.getSource()); // System.out.println(news.getUrl()); // System.out.println("--"); CorePlugin.getRepository().save(news); } } catch (Exception e) { CorePlugin.logException(e); } }
From source file:io.selendroid.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 ww .j a va 2s . c o m BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm()); JSONObject nodeConfig = getNodeConfig(); r.setEntity(new StringEntity(nodeConfig.toString())); 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:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java
/** * This testcase tests that a regular non-json payload is returned without any encryption * * @throws Exception/* ww w. j a v a2 s. c o m*/ */ @Test public void testPlainText() throws Exception { String urlStr = "http://localhost:11080/rest/bookstore/books"; URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); httpget.setHeader(JWEInterceptor.CLIENT_ID, "1234"); System.out.println("executing request:" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity 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()); } InputStream is = entity.getContent(); String contentString = getContentAsString(is); System.out.println("Plain Text=" + contentString); assertNotNull(contentString); assertEquals("books=Les Miserables", contentString); 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(); } }
From source file:com.intuit.tank.standalone.agent.StandaloneAgentStartup.java
public void startTest(final StandaloneAgentRequest request) { Thread t = new Thread(new Runnable() { public void run() { try { currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.DELEGATING); sendAvailability();/*from www . ja va 2 s. c o m*/ LOG.info("Starting up: ControllerBaseUrl=" + controllerBase); URL url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SETTINGS); LOG.info("Starting up: making call to tank service url to get settings.xml " + url.toExternalForm()); InputStream settingsStream = url.openStream(); try { String settings = IOUtils.toString(settingsStream); FileUtils.writeStringToFile(new File("settings.xml"), settings); LOG.info("got settings file..."); } finally { IOUtils.closeQuietly(settingsStream); } url = new URL(controllerBase + SERVICE_RELATIVE_PATH + METHOD_SUPPORT); LOG.info("Making call to tank service url to get support files " + url.toExternalForm()); ZipInputStream zip = new ZipInputStream(url.openStream()); try { ZipEntry entry = zip.getNextEntry(); while (entry != null) { String name = entry.getName(); LOG.info("Got file from controller: " + name); File f = new File(name); FileOutputStream fout = FileUtils.openOutputStream(f); try { IOUtils.copy(zip, fout); } finally { IOUtils.closeQuietly(fout); } entry = zip.getNextEntry(); } } finally { IOUtils.closeQuietly(zip); } // now start the harness String cmd = API_HARNESS_COMMAND + " -http=" + controllerBase + " -jobId=" + request.getJobId() + " -stopBehavior=" + request.getStopBehavior(); LOG.info("Starting apiharness with command: " + cmd); currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.RUNNING_JOB); sendAvailability(); Process exec = Runtime.getRuntime().exec(cmd); exec.waitFor(); currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.AVAILABLE); sendAvailability(); // } catch (Exception e) { LOG.error("Error in AgentStartup " + e, e); currentAvailability.setAvailabilityStatus(AgentAvailabilityStatus.AVAILABLE); sendAvailability(); } } }); t.start(); }
From source file:javarestart.WebClassLoader.java
private String resourceName(URL url) { String burl = baseURL.toExternalForm(); String eurl = url.toExternalForm(); int length = burl.endsWith("/") ? burl.length() : burl.length() + 1; return eurl.length() <= length ? "" : eurl.substring(length); }
From source file:org.kalypso.ogc.sensor.timeseries.TimeseriesUtils.java
/** * Lazy loading of the properties/* www.j a v a2 s .c om*/ * * @return config of the timeseries package */ private static synchronized Properties getProperties() { if (CONFIG == null) { CONFIG = new Properties(); final Properties defaultConfig = new Properties(); CONFIG = new Properties(defaultConfig); // The config file in the sources is used as defaults PropertiesUtilities.loadI18nProperties(defaultConfig, CONFIG_BASE_URL, BASENAME); // TODO: also load configured properties via i18n mechanism InputStream configIs = null; try { // If we have a configured config file, use it as standard final URL configUrl = Platform.isRunning() ? Platform.getConfigurationLocation().getURL() : null; final String timeseriesConfigLocation = System.getProperty(PROP_TIMESERIES_CONFIG); final URL timeseriesConfigUrl = timeseriesConfigLocation == null ? null : new URL(configUrl, timeseriesConfigLocation); // TODO: load time series ini from local config: ni order to support debugging correctly, sue this pattern: // final URL proxyConfigLocation = HwvProductSachsenAnhalt.findConfigLocation( CONFIG_PROXY_PATH ); try { if (timeseriesConfigUrl != null) configIs = timeseriesConfigUrl.openStream(); } catch (final Throwable t) { // ignore: there is no config file; we are using standard instead final IStatus status = StatusUtilities.createStatus(IStatus.WARNING, "Specified timeseries config file at " + timeseriesConfigUrl.toExternalForm() //$NON-NLS-1$ + " does not exist. Using default settings.", //$NON-NLS-1$ null); KalypsoCorePlugin.getDefault().getLog().log(status); t.printStackTrace(); } if (configIs != null) { CONFIG.load(configIs); configIs.close(); } } catch (final IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(configIs); } } return CONFIG; }
From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java
public Collection<RepositoryItem> getOntologies() { final Collection<RepositoryItem> items = new ArrayList<RepositoryItem>(); URL url = null; try {/*from w w w .jav a 2s.com*/ url = new URL( BioPortalRepository.ONTOLOGY_LIST + "?format=json&apikey=" + BioPortalRepository.readAPIKey()); logger.debug("Contacting BioPortal REST API at: " + url.toExternalForm()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(CONNECT_TIMEOUT); int responseCode = connection.getResponseCode(); logger.info("BioPortal http response: " + responseCode); if (responseCode == 400 || responseCode == 403) { throw new BioPortalAccessDeniedException(); } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(connection.getInputStream()); for (final JsonNode item : node) { String name = item.get("name").asText(); String id = item.get("acronym").asText(); BioPortalRepositoryItem repositoryItem = new BioPortalRepositoryItem(id, name, this); if (repositoryItem.isCompatible()) { items.add(repositoryItem); } } if (SAVE_PROPERTIES_CACHE) { BioPortalCache.getInstance().dumpStoredProperties(); } } catch (UnknownHostException e) { ErrorHandler.getErrorHandler().handleError(e); } catch (MalformedURLException e) { logger.error("Error with URL for BioPortal rest API", e); } catch (SocketTimeoutException e) { logger.error("Timeout connecting to BioPortal", e); ErrorHandler.getErrorHandler().handleError(e); } catch (IOException e) { logger.error("Error communiciating with BioPortal rest API", e); } catch (BioPortalAccessDeniedException e) { ErrorHandler.getErrorHandler().handleError(e); } return items; }
From source file:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java
/** * This test case tests the encryption of JSON payload * * @throws Exception//from w ww .j a v a 2s. c o m */ @Test public void testJAXRS_jsonEncryption() throws Exception { PrivateKey privateKey = getPrivateKey(); String urlStr = "http://localhost:11080/rest/bookstore/"; URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); httpget.setHeader(JWEInterceptor.CLIENT_ID, "1234"); System.out.println("executing request:" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity 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()); } InputStream is = entity.getContent(); String contentString = getContentAsString(is); JSONWebToken jwt = new JSONWebToken(); jwt.setPrivateKey(privateKey); jwt.decode(contentString); JSONObject jsonObject = jwt.getData(); assertNotNull(jsonObject); assertEquals("Harry Potter", jsonObject.getString("name")); System.out.println(jsonObject.toString()); 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(); } }
From source file:net.sourceforge.subsonic.backend.controller.RedirectionManagementController.java
public void register(HttpServletRequest request, HttpServletResponse response) throws Exception { String redirectFrom = StringUtils .lowerCase(ServletRequestUtils.getRequiredStringParameter(request, "redirectFrom")); String licenseHolder = ServletRequestUtils.getStringParameter(request, "licenseHolder"); String serverId = ServletRequestUtils.getRequiredStringParameter(request, "serverId"); int port = ServletRequestUtils.getRequiredIntParameter(request, "port"); Integer localPort = ServletRequestUtils.getIntParameter(request, "localPort"); String localIp = ServletRequestUtils.getStringParameter(request, "localIp"); String contextPath = ServletRequestUtils.getRequiredStringParameter(request, "contextPath"); boolean trial = ServletRequestUtils.getBooleanParameter(request, "trial", false); Date now = new Date(); Date trialExpires = null;/*from ww w . ja va 2 s .c o m*/ if (trial) { trialExpires = new Date(ServletRequestUtils.getRequiredLongParameter(request, "trialExpires")); } if (RESERVED_REDIRECTS.containsKey(redirectFrom)) { sendError(response, "\"" + redirectFrom + "\" is a reserved address. Please select another."); return; } if (!redirectFrom.matches("(\\w|\\-)+")) { sendError(response, "Illegal characters present in \"" + redirectFrom + "\". Please select another."); return; } String host = request.getRemoteAddr(); URL url = new URL("http", host, port, "/" + contextPath); String redirectTo = url.toExternalForm(); String localRedirectTo = null; if (localIp != null && localPort != null) { URL localUrl = new URL("http", localIp, localPort, "/" + contextPath); localRedirectTo = localUrl.toExternalForm(); } Redirection redirection = redirectionDao.getRedirection(redirectFrom); if (redirection == null) { // Delete other redirects for same server ID. redirectionDao.deleteRedirectionsByServerId(serverId); redirection = new Redirection(0, licenseHolder, serverId, redirectFrom, redirectTo, localRedirectTo, trial, trialExpires, now, null, 0); redirectionDao.createRedirection(redirection); LOG.info("Created " + redirection); } else { boolean sameServerId = serverId.equals(redirection.getServerId()); boolean sameLicenseHolder = licenseHolder != null && licenseHolder.equals(redirection.getLicenseHolder()); // Note: A licensed user can take over any expired trial domain. boolean existingTrialExpired = redirection.getTrialExpires() != null && redirection.getTrialExpires().before(now); if (sameServerId || sameLicenseHolder || (existingTrialExpired && !trial)) { redirection.setLicenseHolder(licenseHolder); redirection.setServerId(serverId); redirection.setRedirectFrom(redirectFrom); redirection.setRedirectTo(redirectTo); redirection.setLocalRedirectTo(localRedirectTo); redirection.setTrial(trial); redirection.setTrialExpires(trialExpires); redirection.setLastUpdated(now); redirectionDao.updateRedirection(redirection); LOG.info("Updated " + redirection); } else { sendError(response, "The web address \"" + redirectFrom + "\" is already in use. Please select another."); } } }