List of usage examples for java.net URL toExternalForm
public String toExternalForm()
From source file:org.openqa.grid.internal.TestSession.java
/** * Sends a DELETE/testComplete (webdriver/selenium) session command to the remote, following web * driver protocol.//from w ww.j av a 2 s . c om * * @return true is the remote replied successfully to the request. */ public boolean sendDeleteSessionRequest() { URL remoteURL = slot.getRemoteURL(); HttpRequest request; switch (slot.getProtocol()) { case Selenium: request = new BasicHttpRequest("POST", remoteURL.toExternalForm() + "/?cmd=testComplete&sessionId=" + getExternalKey().getKey()); break; case WebDriver: String uri = remoteURL.toString() + "/session/" + externalKey; request = new BasicHttpRequest("DELETE", uri); break; default: throw new GridException("Error, protocol not implemented."); } HttpHost host = new HttpHost(remoteURL.getHost(), remoteURL.getPort()); boolean ok; try { HttpClient client = getClient(); HttpResponse response = client.execute(host, request); int code = response.getStatusLine().getStatusCode(); ok = (code >= 200) && (code <= 299); } catch (Throwable e) { ok = false; // corrupted or the something else already sent the DELETE. log.severe("Error releasing. Server corrupted ?"); } return ok; }
From source file:ch.entwine.weblounge.preview.phantomjs.PhantomJsPagePreviewGenerator.java
/** * {@inheritDoc}/*from ww w . ja v a 2 s. c om*/ * * @see ch.entwine.weblounge.common.content.PreviewGenerator#createPreview(ch.entwine.weblounge.common.content.Resource, * ch.entwine.weblounge.common.site.Environment, * ch.entwine.weblounge.common.language.Language, * ch.entwine.weblounge.common.content.image.ImageStyle, String, * java.io.InputStream, java.io.OutputStream) */ public void createPreview(Resource<?> resource, Environment environment, Language language, ImageStyle style, String format, InputStream is, OutputStream os) throws IOException { // We don't need the input stream IOUtils.closeQuietly(is); // Find a suitable image preview generator for scaling ImagePreviewGenerator imagePreviewGenerator = null; synchronized (previewGenerators) { for (ImagePreviewGenerator generator : previewGenerators) { if (generator.supports(format)) { imagePreviewGenerator = generator; break; } } if (imagePreviewGenerator == null) { logger.debug("Unable to generate page previews since no image renderer is available"); return; } } // Find the relevant metadata to start the request ResourceURI uri = resource.getURI(); long version = resource.getVersion(); Site site = uri.getSite(); // Create the url URL pageURL = new URL(UrlUtils.concat(site.getHostname(environment).toExternalForm(), PAGE_HANDLER_PREFIX, uri.getIdentifier())); if (version == Resource.WORK) { pageURL = new URL( UrlUtils.concat(pageURL.toExternalForm(), "work_" + language.getIdentifier() + ".html")); } else { pageURL = new URL( UrlUtils.concat(pageURL.toExternalForm(), "index_" + language.getIdentifier() + ".html")); } // Create a temporary file final File rendererdFile = File.createTempFile("phantomjs-", "." + format, phantomTmpDir); final URL finalPageURL = pageURL; final AtomicBoolean success = new AtomicBoolean(); // Call PhantomJS to render the page try { final PhantomJsProcessExecutor phantomjs = new PhantomJsProcessExecutor(scriptFile.getAbsolutePath(), pageURL.toExternalForm(), rendererdFile.getAbsolutePath()) { @Override protected void onProcessFinished(int exitCode) throws IOException { super.onProcessFinished(exitCode); switch (exitCode) { case 0: if (rendererdFile.length() > 0) { success.set(true); logger.debug("Page preview of {} created at {}", finalPageURL, rendererdFile.getAbsolutePath()); } else { logger.warn("Error creating page preview of {}", finalPageURL); success.set(false); FileUtils.deleteQuietly(rendererdFile); } break; default: success.set(false); logger.warn("Error creating page preview of {}", finalPageURL); FileUtils.deleteQuietly(rendererdFile); } } }; // Finally have PhantomJS create the preview logger.debug("Creating preview of {}", finalPageURL); phantomjs.execute(); } catch (ProcessExcecutorException e) { logger.warn("Error creating page preview of {}: {}", pageURL, e.getMessage()); throw new IOException(e); } finally { // If page preview rendering failed, there is no point in scaling the // images if (!success.get()) { logger.debug("Skipping scaling of failed preview rendering {}", pageURL); FileUtils.deleteQuietly(rendererdFile); return; } } FileInputStream imageIs = null; // Scale the image to the correct size try { imageIs = new FileInputStream(rendererdFile); imagePreviewGenerator.createPreview(resource, environment, language, style, PREVIEW_FORMAT, imageIs, os); } catch (IOException e) { logger.error("Error reading original page preview from " + rendererdFile, e); throw e; } catch (Throwable t) { logger.warn("Error scaling page preview at " + uri + ": " + t.getMessage(), t); throw new IOException(t); } finally { IOUtils.closeQuietly(imageIs); FileUtils.deleteQuietly(rendererdFile); } }
From source file:com.aurel.track.dbase.HandleHome.java
/** * Gets the PropertiesConfiguration for a property file from servlet context * @param propFile/*ww w . ja v a 2s. com*/ * @param servletContext * @return * @throws ServletException */ public static PropertiesConfiguration loadServletContextPropFile(String propFile, ServletContext servletContext) throws ServletException { PropertiesConfiguration pc = null; InputStream in = null; URL propFileURL = null; try { if (pc == null && servletContext != null) { propFileURL = servletContext.getResource("/WEB-INF/" + propFile); in = propFileURL.openStream(); pc = new PropertiesConfiguration(); pc.load(in); in.close(); } } catch (Exception e) { LOGGER.error("Could not read " + propFile + " from servlet context " + propFileURL == null ? "" : propFileURL.toExternalForm() + ". Exiting. " + e.getMessage()); throw new ServletException(e); } return pc; }
From source file:VrmlPickingTest.java
protected BranchGroup createSceneBranchGroup() { BranchGroup objRoot = super.createSceneBranchGroup(); Bounds lightBounds = getApplicationBounds(); AmbientLight ambLight = new AmbientLight(true, new Color3f(1.0f, 1.0f, 1.0f)); ambLight.setInfluencingBounds(lightBounds); objRoot.addChild(ambLight);// ww w .j a v a 2s . co m DirectionalLight headLight = new DirectionalLight(); headLight.setInfluencingBounds(lightBounds); objRoot.addChild(headLight); TransformGroup mouseGroup = createMouseBehaviorsGroup(); String vrmlFile = null; try { URL codebase = getWorkingDirectory(); vrmlFile = codebase.toExternalForm() + "BoxConeSphere.wrl"; } catch (Exception e) { e.printStackTrace(); } if (m_szCommandLineArray != null) { switch (m_szCommandLineArray.length) { case 0: break; case 1: vrmlFile = m_szCommandLineArray[0]; break; default: System.err.println("Usage: VrmlPickingTest [pathname|URL]"); System.exit(-1); } } BranchGroup sceneRoot = loadVrmlFile(vrmlFile); if (sceneRoot != null) mouseGroup.addChild(sceneRoot); objRoot.addChild(mouseGroup); return objRoot; }
From source file:com.googlecode.fightinglayoutbugs.DetectInvalidImageUrls.java
private void checkCssResourceAsync(final String pathToCssResource, String url, URL baseUrl, final String fallBackCharset) { try {//from w w w . jav a 2s .c o m final URL cssUrl = getCompleteUrlFor(baseUrl, url); if (_checkedCssUrls.add(cssUrl.toExternalForm())) { _mockBrowser.downloadAsync(cssUrl, new DownloadCallback() { @Override public void onSuccess(GetMethod getMethod) { final Css css = getCssFrom(getMethod, cssUrl, fallBackCharset); if (css.text != null) { for (String importUrl : getImportUrlsFrom(css.text)) { checkCssResourceAsync(importUrl + " (imported from " + pathToCssResource + ")", importUrl, cssUrl, css.charset); } for (String url : extractUrlsFrom(css.text)) { try { checkImageUrl(cssUrl, url, "Detected invalid image URL \"" + url + "\" in " + pathToCssResource); } catch (MalformedURLException e) { addLayoutBugIfNotPresent( "Detected invalid image URL \"" + url + "\" in " + pathToCssResource); } } } } @Override public void onFailure(IOException e) { LOG.error("Could not get CSS from " + pathToCssResource + ".", e); } }); } } catch (MalformedURLException e) { LOG.error("Could not get CSS from " + pathToCssResource + ".", e); } }
From source file:com.gargoylesoftware.htmlunit.MockWebConnection.java
/** * Sets the response that will be returned when the specified URL is requested. * @param url the URL that will return the given response * @param content the content to return/*from www. java2 s . c o m*/ * @param statusCode the status code to return * @param statusMessage the status message to return * @param contentType the content type to return * @param headers the response headers to return */ public void setResponse(final URL url, final byte[] content, final int statusCode, final String statusMessage, final String contentType, final List<NameValuePair> headers) { final RawResponseData responseEntry = buildRawResponseData(content, statusCode, statusMessage, contentType, headers); responseMap_.put(url.toExternalForm(), responseEntry); }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.realm.AggregateRealmTestCase.java
private URL prepareRolesPrintingURL(URL webAppURL) throws MalformedURLException { return new URL( webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + QUERY_ROLES); }
From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java
private void checkState() { // first of all, check if the resource is idle for too long. Regain it then. if (resource.getState() == ResourceState.IN_USE && resource.getIdleTime() > maxIdleTime) { // try to safely shutdown Selenium session LOG.info("Detected IDLE IN_USE resource (" + resource.getOriginalUrl() + "), trying to regain it."); resource.tryKillSession();// w w w .ja va 2 s.com resource.stopUsing(); return; } // check state via our very own proxy - to get custom timeouts and direct feedback for lost connections. InputStream in = null; HttpGet request = null; CloseableHttpResponse response = null; try { URL uurl = new URL(accessUrl); URL checkUrl = new URL("http://127.0.0.1:" + uurl.getPort() + uurl.getPath() + "/wd/hub/status"); LOG.debug("Checking health state for " + resource.getOriginalUrl() + " using " + checkUrl.toExternalForm()); request = new HttpGet(checkUrl.toURI()); response = healthCheckClient.execute(request); if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() == HttpServletResponse.SC_GATEWAY_TIMEOUT) { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (proxy timeout)"); resource.setState(ResourceState.DISCONNECTED); } else if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid HTTP status code " + response.getStatusLine().getStatusCode() + ")"); resource.setState(ResourceState.DISCONNECTED); } else if (response.getEntity() != null) { in = response.getEntity().getContent(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); IOUtils.copy(in, buf); String statusStr = new String(buf.toByteArray(), "UTF-8"); if (statusStr.contains("\"status\":0")) { if (resource.getState() == ResourceState.DISCONNECTED || resource.getState() == ResourceState.CONNECTED) { resource.setState(ResourceState.READY); LOG.debug(resource.getOriginalUrl() + " is READY"); } } else { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid response content: " + statusStr + ")"); resource.setState(ResourceState.DISCONNECTED); } } else { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid or no HTTP response)"); resource.setState(ResourceState.DISCONNECTED); } } catch (IOException e) { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to IOException: " + e.getMessage()); resource.setState(ResourceState.DISCONNECTED); } catch (URISyntaxException e) { LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to URISyntaxException: " + e.getMessage()); resource.setState(ResourceState.DISCONNECTED); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(response); } }
From source file:org.danann.cernunnos.runtime.web.CernunnosPortlet.java
@SuppressWarnings("unchecked") @Override/*w w w .j a v a2 s . c o m*/ public void init() throws PortletException { PortletConfig config = getPortletConfig(); // Load the context, if present... try { // Bootstrap the portlet Grammar instance... final Grammar root = XmlGrammar.getMainGrammar(); final InputStream inpt = CernunnosPortlet.class.getResourceAsStream("portlet.grammar"); // Can't rely on classpath:// protocol handler... final Document doc = new SAXReader().read(inpt); final Task k = new ScriptRunner(root).compileTask(doc.getRootElement()); final RuntimeRequestResponse req = new RuntimeRequestResponse(); final ReturnValueImpl rslt = new ReturnValueImpl(); req.setAttribute(Attributes.RETURN_VALUE, rslt); k.perform(req, new RuntimeRequestResponse()); Grammar g = (Grammar) rslt.getValue(); runner = new ScriptRunner(g); // Choose a context location & load it if it exists... String defaultLoc = "/WEB-INF/" + config.getPortletName() + "-portlet.xml"; URL defaultUrl = getPortletConfig().getPortletContext().getResource(defaultLoc); URL u = Settings.locateContextConfig( getPortletConfig().getPortletContext().getResource("/").toExternalForm(), config.getInitParameter(CONFIG_LOCATION_PARAM), defaultUrl); if (u != null) { // There *is* a resource mapped to this path name... spring_context = new FileSystemXmlApplicationContext(u.toExternalForm()); } if (log.isTraceEnabled()) { log.trace("Loaction of spring context (null means none): " + u); } // Load the Settings... Map<String, String> settingsMap = new HashMap<String, String>(); // default... if (spring_context != null && spring_context.containsBean("settings")) { settingsMap = (Map<String, String>) spring_context.getBean("settings"); } settings = Settings.load(settingsMap); } catch (Throwable t) { String msg = "Failure in CernunnosPortlet.init()"; throw new PortletException(msg, t); } }
From source file:com.sun.socialsite.web.rest.opensocial.ConsumerContext.java
/** * Adds an element to this object's context chain. If the specified * element has a "delegate" attribute, this method will retrieve the * delegation element and recursively add it also. * * @param element the ChainElement to be added to the context chain. */// www.ja v a2 s. co m private void appendToChain(URL source, boolean loadedDirectly, JSONObject contents) throws SocialSiteException { try { ChainElement element = null; if (contents.has("attributes")) { element = new LegacyChainElement(source, loadedDirectly, contents); } else { element = new ChainElement(source, loadedDirectly, contents); } elements.add(element); if (element.contents.has("delegate")) { JSONObject delegate = element.contents.getJSONObject("delegate"); URL url = null; if (element.source != null) { url = new URL(element.source, delegate.getString("url")); } else { url = new URL(delegate.getString("url")); } HttpClient httpClient = new HttpClient(); HttpMethod method = null; if ("GET".equalsIgnoreCase(delegate.getString("method"))) { method = new GetMethod(url.toExternalForm()); } if (delegate.has("headers")) { JSONObject headers = delegate.getJSONObject("headers"); for (Iterator<?> iterator = headers.keys(); iterator.hasNext();) { String name = iterator.next().toString(); String value = headers.get(name).toString(); method.addRequestHeader(name, value); } } if (element.source != null) { method.setRequestHeader("Referer", element.source.toString()); } int responseCode = httpClient.executeMethod(method); if (responseCode == 200) { String responseBody = method.getResponseBodyAsString(); appendToChain(url, true, new JSONObject(responseBody)); if (log.isDebugEnabled()) { String msg = String.format("%s %s returned %d: %s", method.getName(), url, responseCode, responseBody); log.debug(msg); } } else { String msg = String.format("%s %s returned %d", method.getName(), url, responseCode); throw new SocialSiteException(msg); } } } catch (SocialSiteException e) { throw e; } catch (Exception e) { throw new SocialSiteException(e); } }