Example usage for java.net URL toExternalForm

List of usage examples for java.net URL toExternalForm

Introduction

In this page you can find the example usage for java.net URL toExternalForm.

Prototype

public String toExternalForm() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:ch.entwine.weblounge.common.impl.content.page.PageletRendererImpl.java

/**
 * Processes both renderer and editor url by replacing templates in their
 * paths with real values from the actual module.
 * /*from ww  w . ja va  2  s .com*/
 * @param environment
 *          the environment
 * 
 * @return <code>false</code> if the paths don't end up being real urls,
 *         <code>true</code> otherwise
 */
private boolean processURLTemplates(Environment environment) {
    if (module == null)
        throw new IllegalStateException("Module is null");
    if (module.getSite() == null)
        throw new IllegalArgumentException("Site is null");

    // Process the renderer URL
    for (Map.Entry<String, URL> entry : renderers.entrySet()) {
        URL renderer = entry.getValue();
        String rendererURL = ConfigurationUtils.processTemplate(renderer.toExternalForm(), module, environment);
        try {
            renderer = new URL(rendererURL);
            renderers.put(entry.getKey(), renderer);
        } catch (MalformedURLException e) {
            logger.warn("Renderer url {} of pagelet {} is malformed", rendererURL, this);
            return false;
        }
    }

    // Process the editor URL
    if (editor != null) {
        String editorURL = ConfigurationUtils.processTemplate(editor.toExternalForm(), module, environment);
        try {
            editor = new URL(editorURL);
        } catch (MalformedURLException e) {
            logger.warn("Editor url {} of pagelet {} is malformed", editorURL, this);
            return false;
        }
    }

    // Process the head elements (scripts and stylesheet includes)
    for (HTMLHeadElement headElement : headers) {
        headElement.setEnvironment(environment);
    }

    return true;
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

private void setCredentials(DefaultHttpClient client, URL url) {
    if (configService == null) {
        return;/* ww  w  .j  a v  a  2 s .c  om*/
    }

    DestinationsConfig config = configService.readConfiguration(DestinationsConfig.class);
    if (config == null) {
        return;
    }

    for (DestinationConfig destination : config.getDestinations()) {
        Pattern regex = Pattern.compile(destination.getPattern());
        Matcher matcher = regex.matcher(url.toExternalForm());
        if (matcher.matches()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("matched URL {0} with destination ''{1}''", url.toExternalForm(),
                        destination.getId()));
            }

            if (StringUtils.isNotBlank(destination.getUser())
                    && StringUtils.isNotBlank(destination.getPattern())) {
                String authenticationMethod = destination.getAuthenticationMethod();
                if ("basic".equalsIgnoreCase(authenticationMethod)) { //$NON-NLS-1$
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
                    client.setCredentialsProvider(credsProvider);
                } else if (StringUtils.isNotBlank(authenticationMethod)) {
                    LOG.warn(MessageFormat.format("Authentication method ''{1}'' is not supported",
                            authenticationMethod));
                }
            }
            break;
        }
    }
}

From source file:org.dawnsci.marketplace.services.MarketplaceDAO.java

private Marketplace loadCatalogs(URL url) {
    ResourceSet rs = new ResourceSetImpl();
    rs.getPackageRegistry().put(null, MarketplacePackage.eINSTANCE);
    try {//from  w  w w.jav a2s  .c  o m
        Resource resource = rs.createResource(URI.createURI(url.toExternalForm()));
        InputStream is = url.openStream();
        resource.load(is, rs.getLoadOptions());
        return (Marketplace) resource.getContents().get(0);
    } catch (UnknownHostException e) {
        // marketplace is unavailable flagging it as such
        catalogsUnavailable = true;
        logger.warn("Marketplace at " + url + " is unavailable");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.jboss.additional.testsuite.jdkall.present.domain.management.cli.DomainDeploymentOverlayTestCase.java

private String performHttpCall(String host, String server, String deployment) throws Exception {
    ModelNode op = new ModelNode();
    op.get(OP).set(READ_RESOURCE_OPERATION);
    op.get(OP_ADDR).add(HOST, host).add(SERVER, server).add(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME)
            .add(SOCKET_BINDING, "http");
    op.get(INCLUDE_RUNTIME).set(true);/*ww w . j av  a 2  s.com*/
    ModelNode socketBinding = validateResponse(client.execute(op));

    URL url = new URL("http",
            NetworkUtils.formatAddress(InetAddress.getByName(socketBinding.get("bound-address").asString())),
            socketBinding.get("bound-port").asInt(),
            "/" + deployment + "/SimpleServlet?env-entry=overlay-test");
    return HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS).trim();
}

From source file:com.jaeksoft.searchlib.crawler.web.database.PatternManager.java

final public boolean matchPattern(URL url) {
    rwl.r.lock();/*from  w ww . j  a  v a2s.co  m*/
    try {
        if (url == null)
            return false;
        List<PatternItem> patternList = patternMap.get(PatternItem.getTopDomainOrHost(url.getHost()));
        if (patternList == null)
            return false;
        String sUrl = url.toExternalForm();
        for (PatternItem patternItem : patternList)
            if (patternItem.match(sUrl))
                return true;
        return false;
    } finally {
        rwl.r.unlock();
    }
}

From source file:com.madrobot.net.client.XMLRPCClient.java

/**
 * Convenience XMLRPCClient constructor. Creates new instance based on server URL
 * /*from ww w .  j a  va2s  .  c  om*/
 * @param XMLRPC
 *            server URL
 */
public XMLRPCClient(URL url) {
    this(URI.create(url.toExternalForm()));
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private boolean isAlreadyRegistered(RegistrationRequest node) {

    HttpClient client = httpClientFactory.getHttpClient();
    try {/*w w w. j a  v a 2s  .  c  o  m*/
        String tmp = "http://" + node.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + node.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/proxy";
        URL api = new URL(tmp);
        HttpHost host = new HttpHost(api.getHost(), api.getPort());

        String id = (String) node.getConfiguration().get(RegistrationRequest.ID);
        if (id == null) {
            id = (String) node.getConfiguration().get(RegistrationRequest.REMOTE_HOST);
        }
        BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);

        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new GridException("Hub is down or not responding.");
        }
        JSONObject o = extractObject(response);
        return (Boolean) o.get("success");
    } catch (Exception e) {
        throw new GridException("Hub is down or not responding: " + e.getMessage());
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java

@Override
public AbstractStorageItem retrieveItem(final ProxyRepository repository, final ResourceStoreRequest request,
        final String baseUrl) throws ItemNotFoundException, RemoteStorageException {
    final URL remoteURL = appendQueryString(getAbsoluteUrlFromBase(baseUrl, request.getRequestPath()),
            repository);// w  w w.j  av a2 s  .c om

    final HttpGet method = new HttpGet(remoteURL.toExternalForm());

    final HttpResponse httpResponse = executeRequest(repository, request, method);

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        if (method.getURI().getPath().endsWith("/")) {
            // this is a collection and not a file!
            // httpClient will follow redirections, and the getPath()
            // _should_
            // give us URL with ending "/"
            release(httpResponse);
            throw new ItemNotFoundException(
                    "The remoteURL we got to looks like is a collection, and Nexus cannot fetch collections over plain HTTP (remoteUrl=\""
                            + remoteURL.toString() + "\")",
                    request, repository);
        }

        InputStream is;
        try {
            is = httpResponse.getEntity().getContent();

            String mimeType = EntityUtils.getContentMimeType(httpResponse.getEntity());
            if (mimeType == null) {
                mimeType = getMimeSupport().guessMimeTypeFromPath(repository.getMimeRulesSource(),
                        request.getRequestPath());
            }

            final DefaultStorageFileItem httpItem = new DefaultStorageFileItem(repository, request, CAN_READ,
                    CAN_WRITE, new PreparedContentLocator(is, mimeType));

            if (httpResponse.getEntity().getContentLength() != -1) {
                httpItem.setLength(httpResponse.getEntity().getContentLength());
            }
            httpItem.setRemoteUrl(remoteURL.toString());
            httpItem.setModified(makeDateFromHeader(httpResponse.getFirstHeader("last-modified")));
            httpItem.setCreated(httpItem.getModified());
            httpItem.getItemContext().putAll(request.getRequestContext());

            return httpItem;
        } catch (IOException ex) {
            release(httpResponse);
            throw new RemoteStorageException("IO Error during response stream handling [repositoryId=\""
                    + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\""
                    + remoteURL.toString() + "\"]!", ex);
        } catch (RuntimeException ex) {
            release(httpResponse);
            throw ex;
        }
    } else {
        release(httpResponse);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ItemNotFoundException(
                    "The remoteURL we requested does not exists on remote server (remoteUrl=\""
                            + remoteURL.toString() + "\")",
                    request, repository);
        } else {
            throw new RemoteStorageException(
                    "The method execution returned result code " + httpResponse.getStatusLine().getStatusCode()
                            + ". [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                            + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    }
}

From source file:de.betterform.agent.betty.Betty.java

/**
 * Init: Initializes an AppletAdapter./*from   w  w  w .java2s . com*/
 */
public void init() {
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Applet init start");
        }

        // set splash screen

        //            javascriptCall("setSplash", getSplashScreen(XFormsProcessorImpl.getAppInfo(), ""));

        // get code and document bases
        URL codeBaseUrl = getCodeBase();
        URL documentBaseUrl = getDocumentBase();
        LOGGER.debug("getDocumentBase: " + documentBaseUrl.toExternalForm());

        // extract document name
        String documentPath = documentBaseUrl.getPath();
        this.documentName = documentPath.substring(documentPath.lastIndexOf('/') + 1);

        // update splash screen
        //            javascriptCall("setSplash", getSplashScreen("configuring", this.documentName));

        // init logging
        URI log4jUrl = resolveParameter(codeBaseUrl, LOG4J_PARAMETER, LOG4J_DEFAULT);
        DOMConfigurator.configure(log4jUrl.toURL());

        LOGGER.info("init: code base '" + codeBaseUrl + "'");
        LOGGER.info("init: document base '" + documentBaseUrl + "'");
        LOGGER.info("init: document name '" + this.documentName + "'");

        // loading config
        URI configUrl = resolveParameter(codeBaseUrl, CONFIG_PARAMETER, CONFIG_DEFAULT);
        LOGGER.info("configURL '" + configUrl + "'");
        if (configUrl.toString().startsWith("file:")) {
            LOGGER.info("loading from file:");
            Config.getInstance(new FileInputStream(new File(configUrl)));
        } else {
            LOGGER.info("loading from http:");
            Config.getInstance(configUrl.toURL().openConnection().getInputStream());
        }

        // init adapter
        this.appletProcessor = initAdapter(documentBaseUrl);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        handleException(e);
        throw new RuntimeException(e);
    }
}

From source file:org.danann.cernunnos.runtime.web.CernunnosServlet.java

@SuppressWarnings("unchecked")
@Override//from www .j av a  2  s.  c om
public void init() throws ServletException {

    ServletConfig config = getServletConfig();

    // Load the context, if present...
    try {

        // Bootstrap the servlet Grammar instance...
        final Grammar root = XmlGrammar.getMainGrammar();
        final InputStream inpt = CernunnosServlet.class.getResourceAsStream("servlet.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.getServletName() + "-portlet.xml";
        URL defaultUrl = getServletConfig().getServletContext().getResource(defaultLoc);
        URL u = Settings.locateContextConfig(
                getServletConfig().getServletContext().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.isDebugEnabled()) {
            log.debug("Location 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 CernunnosServlet.init()";
        throw new ServletException(msg, t);
    }

}