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:com.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws java.io.IOException if the checking failed
 *///from   w  ww.  ja v  a 2 s . co m
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    // check META-INF folder
    String urlToString = originalURL.toExternalForm();
    if (!urlToString.contains(META_INF)) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }
    if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
        if (logger.isInfoEnabled()) {
            logger.info(resource.getFilename()
                    + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                    + resource);
        }
        return null;
    }

    String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
    if (persistenceUnitRoot.endsWith("/")) {
        persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
    }
    return new URL(persistenceUnitRoot);
}

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

/**
 * Convenience implementation for JSP renderer. The <code>renderer</code> url
 * is first looked up using the available language information from request
 * and site. Then it is included in the response.
 * /*  www . j a v  a2 s.  c om*/
 * @param request
 *          the request
 * @param response
 *          the response
 * @param renderer
 *          the renderer
 * @throws RenderException
 *           if an error occurs while rendering
 */
protected void includeJSP(WebloungeRequest request, WebloungeResponse response, URL renderer)
        throws RenderException {

    Site site = request.getSite();
    Language language = request.getLanguage();
    File jsp = null;

    try {
        if ("file".equals(renderer.getProtocol())) {
            // Find the best match for the template
            String[] filePaths = LanguageUtils.getLanguageVariants(renderer.toExternalForm(), language,
                    site.getDefaultLanguage());
            for (String path : filePaths) {
                logger.trace("Looking for jsp {}", path);
                File f = new File(path);
                if (f.exists()) {
                    logger.debug("Found jsp at {}", path);
                    jsp = f;
                    break;
                }
            }

            // Did we find a suitable JSP?
            if (jsp == null) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                throw new RenderException(this, "No suitable java server page found for " + renderer
                        + " and language '" + language.getIdentifier() + "'");
            }

            // Check readability
            if (!jsp.canRead()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                throw new RenderException(this, "Java server page at " + jsp + " cannot be read");
            }

            // No directory listings allowed
            if (!jsp.isFile()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                throw new RenderException(this, "Java server page at " + jsp + " is not a file");
            }

            renderer = jsp.toURI().toURL();
        }

        // Prepare a request to site resources
        String servletPath = "/weblounge-sites/" + site.getIdentifier();
        String requestPath = renderer.getPath();
        requestPath = requestPath.substring(servletPath.length());
        requestPath = UrlUtils.concat(Site.BUNDLE_PATH, requestPath);
        SiteRequestWrapper siteRequest = new SiteRequestWrapper(request, requestPath, false);

        RequestDispatcher dispatcher = request.getRequestDispatcher(servletPath);
        if (dispatcher == null)
            throw new IllegalStateException("No dispatcher found for site '" + site + "'");

        // Finally serve the JSP
        logger.debug("Including jsp {}", renderer);
        dispatcher.include(siteRequest, response);

        response.getWriter().flush();
    } catch (IOException e) {
        logger.error("Exception while including jsp {}", renderer, e);
    } catch (Throwable t) {
        throw new RenderException(this, t);
    }
}

From source file:org.graphity.core.util.jena.HttpQuery.java

private InputStream execPost() throws QueryExceptionHTTP {
    URL target = null;
    try {//  w  ww . j ava2 s.c  om
        target = new URL(serviceURL);
    } catch (MalformedURLException malEx) {
        throw new QueryExceptionHTTP(0, "Malformed URL: " + malEx);
    }
    log.trace("POST " + target.toExternalForm());

    ARQ.getHttpRequestLogger().trace(target.toExternalForm());

    try {
        this.client = new SystemDefaultHttpClient();

        // Always apply a 10 second timeout to obtaining a connection lease from HTTP Client
        // This prevents a potential lock up
        this.client.getParams().setLongParameter(ConnManagerPNames.TIMEOUT, TimeUnit.SECONDS.toMillis(10));

        // If user has specified time outs apply them now
        if (this.connectTimeout > 0)
            this.client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                    this.connectTimeout);
        if (this.readTimeout > 0)
            this.client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, this.readTimeout);

        // Enable compression support appropriately
        HttpContext context = new BasicHttpContext();
        if (allowGZip || allowDeflate) {
            // Apply auth early as the decompressing client we're about
            // to add will block this being applied later
            HttpOp.applyAuthentication((AbstractHttpClient) client, serviceURL, context, authenticator);
            this.client = new DecompressingHttpClient(client);
        }

        // Get the actual response stream
        TypedInputStream stream = HttpOp.execHttpPostFormStream(serviceURL, this, contentTypeResult, client,
                context, authenticator);
        if (stream == null)
            throw new QueryExceptionHTTP(404);
        return execCommon(stream);
    } catch (HttpException httpEx) {
        // Unwrap and re-wrap the HTTP Exception
        responseCode = httpEx.getResponseCode();
        throw new QueryExceptionHTTP(responseCode, "Error making the query, see cause for details",
                httpEx.getCause());
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductIdentifier.java

private String process(URL url) {
    Collection<String> properties = null;
    DrbNode node = null;// ww  w. jav a 2  s. c  o  m
    DrbCortexItemClass cl = null;

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        DrbCortexModel model = DrbCortexModel.getDefaultModel();
        node = ProcessingUtils.getNodeFromPath(url.getPath());

        if (node == null) {
            throw new IOException("Cannot Instantiate Drb with URI \"" + url.toExternalForm() + "\".");
        }

        cl = model.getClassOf(node);

        if (cl == null) {
            throw new UnsupportedOperationException("Unknown DRB class for product \"" + url.getPath() + "\".");
        }

        logger.info("Recognized class \"" + cl.getLabel() + "\".");

        // Get all values of the metadata properties attached to the item
        // class or any of its super-classes
        properties = cl.listPropertyStrings(METADATA_NAMESPACE + PROPERTY, false);

        // Return immediately if no property value were found
        if (properties == null) {
            logger.warn("Item \"" + cl.getLabel() + "\" has no identifier defined.");
            return null;
        }
    } catch (IOException e) {
        throw new UnsupportedOperationException("Error While decoding drb node", e);
    }

    // retrieve the first extractor
    String property = properties.iterator().next();

    // Filter possible XML markup brackets that could have been encoded
    // in a CDATA section
    property = property.replaceAll("&lt;", "<");
    property = property.replaceAll("&gt;", ">");

    // Create a query for the current metadata extractor
    Query query = new Query(property);

    // Evaluate the XQuery
    DrbSequence sequence = query.evaluate(node);

    // Check that something results from the evaluation: jump to next
    // value otherwise
    if ((sequence == null) || (sequence.getLength() < 1)) {
        return null;
    }

    String identifier = sequence.getItem(0).toString();
    return identifier;

}

From source file:de.nava.informa.impl.hibernate.Channel.java

public Channel(String title, URL location) {
    this(null, title, location.toExternalForm());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.Stylesheet.java

/**
 * Returns the URL of the stylesheet.//from  w  ww .j a  v  a 2s  .  c om
 * @return the URL of the stylesheet
 */
public String jsxGet_href() {
    final BrowserVersion version = getBrowserVersion();

    if (ownerNode_ != null) {
        final DomNode node = ownerNode_.getDomNodeOrDie();
        if (node instanceof HtmlLink) {
            // <link rel="stylesheet" type="text/css" href="..." />
            final HtmlLink link = (HtmlLink) node;
            final HtmlPage page = (HtmlPage) link.getPage();
            final String href = link.getHrefAttribute();
            if (!version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_EXPANDURL)) {
                // Don't expand relative URLs.
                return href;
            }
            // Expand relative URLs.
            try {
                final URL url = page.getFullyQualifiedUrl(href);
                return url.toExternalForm();
            } catch (final MalformedURLException e) {
                // Log the error and fall through to the return values below.
                LOG.warn(e.getMessage(), e);
            }
        }
    }

    // <style type="text/css"> ... </style>
    if (version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_STYLE_EMPTY)) {
        return "";
    } else if (version.hasFeature(BrowserVersionFeatures.STYLESHEET_HREF_STYLE_NULL)) {
        return null;
    } else {
        final DomNode node = ownerNode_.getDomNodeOrDie();
        final HtmlPage page = (HtmlPage) node.getPage();
        final URL url = page.getWebResponse().getRequestSettings().getUrl();
        return url.toExternalForm();
    }
}

From source file:com.quartercode.quarterbukkit.api.query.ServerModsAPIQuery.java

/**
 * Executes the stored query and returns the result as a {@link JSONArray}.
 * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}.
 * The GET response of that {@link URL} is then parsed to a {@link JSONArray}.
 * /* ww  w . j av  a 2  s . c  o m*/
 * @return The response of the server mods api.
 * @throws QueryException Something goes wrong while querying the server mods api.
 */
public JSONArray execute() throws QueryException {

    // Build request url using the query
    URL requestUrl = null;
    try {
        requestUrl = new URL(HOST + query);
    } catch (MalformedURLException e) {
        throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e);
    }

    // Open connection to request url
    URLConnection request = null;
    try {
        request = requestUrl.openConnection();
    } catch (IOException e) {
        throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(),
                e);
    }

    // Set connection timeout
    request.setConnectTimeout(CONNECTION_TIMEOUT);

    // Set user agent
    request.addRequestProperty("User-Agent", USER_AGENT);

    // Set api key (if provided)
    String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key");
    if (apiKey != null && !apiKey.isEmpty()) {
        request.addRequestProperty("X-API-Key", apiKey);
    }

    // We want to read the results
    request.setDoOutput(true);

    // Read first line from the response
    BufferedReader reader = null;
    String response = null;
    try {
        reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        response = reader.readLine();
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e);
        } else {
            throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(),
                    e);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this,
                        requestUrl.toExternalForm(), e);
            }
        }
    }

    // Parse the response
    Object jsonResponse = JSONValue.parse(response);

    if (jsonResponse instanceof JSONArray) {
        return (JSONArray) jsonResponse;
    } else {
        throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm());
    }
}

From source file:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java

/**
 * Test roles for jduke user.//from   w  w w  . ja  v a2  s  .c o  m
 *
 * @throws Exception
 */
@Test
@OperateOnDeployment(SERVICE_PROVIDER_NAME)
public void testJDukeRoles(@ArquillianResource URL webAppURL,
        @ArquillianResource @OperateOnDeployment(IDENTITY_PROVIDER_NAME) URL idpURL) throws Exception {
    final URI rolesPrintingURL = new URI(
            webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1)
                    + "?test=testDeploymentViaKerberos&" + KerberosServerSetupTask.QUERY_ROLES);

    String responseBody = makeCallWithKerberosAuthn(rolesPrintingURL, idpURL.toURI(), "jduke", DUKE_PASSWORD);

    final List<String> assignedRolesList = Arrays.asList("TheDuke", "Echo", "Admin");
    for (String role : KerberosServerSetupTask.ROLE_NAMES) {
        if (assignedRolesList.contains(role)) {
            assertThat("Missing role assignment", responseBody, containsString("," + role + ","));
        } else {
            assertThat("Unexpected role assignment", responseBody, not(containsString("," + role + ",")));
        }
    }
}

From source file:net.sf.jasperreports.engine.xml.JRXmlDigester.java

private void addEntityResource(String systemId, String resource) {
    URL resourceURL = JRLoader.getResource(resource);
    if (resourceURL == null) {
        log.warn("Could not find entity resource " + resource);
        return;// w  ww . j  a  va 2 s. com
    }

    if (log.isDebugEnabled()) {
        log.debug("Entity " + systemId + " resolved to " + resourceURL);
    }

    if (systemId != null) {
        internalEntityResources.put(systemId, resourceURL);
    }
    entityURLs.add(resourceURL.toExternalForm());
}

From source file:com.mothsoft.alexis.engine.retrieval.RssRetrievalTaskImpl.java

private void handleEntry(final RssFeed rssFeed, final SyndEntry entry) {
    logger.info("Entry: " + entry.getLink());

    URL url = null;

    if (entry.getLink() != null) {

        try {//from  w w  w.j  av  a 2  s .  co  m
            url = new URL(entry.getLink());
        } catch (MalformedURLException e1) {
            logger.error("    Bad link: " + entry.getLink() + ", skipping");
            return;
        }

        Document document = this.documentDao.findByUrl(url.toExternalForm());

        if (document == null) {
            final String title = readTitle(entry);
            final String description = readDescription(entry);
            document = new Document(DocumentType.W, url, title, description);
            document.setCreationDate(
                    this.firstNotNull(entry.getPublishedDate(), entry.getUpdatedDate(), new Date()));

            this.documentDao.add(document);

        } else {
            logger.info("Document already exists, will not queue again.");
        }

        // FIXME - optimize, perhaps with an intelligent query
        for (final RssSource ithRssSource : rssFeed.getRssSources()) {
            final Long userId = ithRssSource.getUserId();
            final User user = this.userDao.get(userId);
            final DocumentUser documentUser = new DocumentUser(document, user);

            if (!document.getDocumentUsers().contains(documentUser)) {
                document.getDocumentUsers().add(documentUser);
            }
            this.documentDao.update(document);
        }

    }
}