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:org.eclipse.ebr.maven.AboutFilesUtil.java

private void appendIssueTrackingInfo(final StrBuilder text, final Artifact artifact, final Model artifactPom) {
    final String url = artifactPom.getIssueManagement().getUrl();
    if (isPotentialWebUrl(url)) {
        try {/*from   w  w w. java  2  s .  com*/
            final URL issueTrackingUrl = toUrl(url); // parse as URL to avoid surprises
            text.append("Bugs or feature requests can be made in the project issue tracking system at ");
            text.append("<a href=\"").append(issueTrackingUrl.toExternalForm()).append("\" target=\"_blank\">");
            text.append(escapeHtml4(removeWebProtocols(url)));
            text.append("</a>.");
        } catch (final MalformedURLException e) {
            getLog().debug(e);
            getLog().warn(format("Invalide project issue tracking url '%s' in artifact pom '%s'.", url,
                    artifact.getFile()));
        }
    } else if (StringUtils.isNotBlank(url)) {
        text.append("Bugs or feature requests can be made in the project issue tracking system at ");
        text.append(escapeHtml4(url)).append('.');
    }
}

From source file:org.eclipse.skalli.model.ext.maven.internal.HttpMavenPomResolverBase.java

/**
 * @param logResponse = true will return an default empty MavenPom  and log the content read from the
 * url with level Error to LOG; if set to false the method parse is called.
 *//*  w  w  w.  j  a va2s  . c  o m*/
private MavenPom parse(URL url, String relativePath, boolean logResponse)
        throws IOException, HttpException, ValidationException {
    HttpClient client = Destinations.getClient(url);
    if (client == null) {
        return null;
    }
    HttpParams params = client.getParams();
    HttpClientParams.setRedirecting(params, false); // we want to find 301 MOVED PERMANTENTLY
    HttpResponse response = null;
    try {
        LOG.info("GET " + url); //$NON-NLS-1$
        HttpGet method = new HttpGet(url.toExternalForm());
        response = client.execute(method);
        int status = response.getStatusLine().getStatusCode();
        LOG.info(status + " " + response.getStatusLine().getReasonPhrase()); //$NON-NLS-1$
        if (status == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            if (!logResponse) {
                return parse(asPomInputStream(entity, relativePath));
            } else {
                logResponse(url, entity);
                return new MavenPom();
            }
        } else {
            String statusText = response.getStatusLine().getReasonPhrase();
            switch (status) {
            case SC_NOT_FOUND:
                throw new HttpException(MessageFormat.format("{0} not found", url));
            case SC_UNAUTHORIZED:
                throw new HttpException(MessageFormat.format("{0} found but authentication required: {1} {2}",
                        url, status, statusText));
            case SC_INTERNAL_SERVER_ERROR:
            case SC_SERVICE_UNAVAILABLE:
            case SC_GATEWAY_TIMEOUT:
            case SC_INSUFFICIENT_STORAGE:
                throw new HttpException(MessageFormat.format(
                        "{0} not found. Host reports a temporary problem: {1} {2}", url, status, statusText));
            case SC_MOVED_PERMANENTLY:
                throw new HttpException(
                        MessageFormat.format("{0} not found. Resource has been moved permanently to {1}", url,
                                response.getFirstHeader("Location")));
            default:
                throw new HttpException(MessageFormat.format("{0} not found. Host responded with {1} {2}", url,
                        status, statusText));
            }
        }
    } finally {
        HttpUtils.consumeQuietly(response);
    }
}

From source file:org.apache.jena.sparql.engine.http.HttpQuery.java

private InputStream execPost() throws QueryExceptionHTTP {
    URL target = null;
    try {/*from   www.  ja v  a  2s .c  o m*/
        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 {
        // Select the appropriate HttpClient to use
        this.selectClient();

        // 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) {
        throw rewrap(httpEx);
    }
}

From source file:net.sf.ehcache.config.Configurator.java

/**
 * Configures a bean from an XML file in the classpath.
 *//* ww  w.  j  a  v  a  2  s .  c o  m*/
public void configure(final Object bean) throws Exception {
    final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    final BeanHandler handler = new BeanHandler(bean);
    URL url = getClass().getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
    if (url != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Configuring ehcache from ehcache.xml found in the classpath: " + url);
        }
    } else {
        url = getClass().getResource(FAILSAFE_CLASSPATH_CONFIGURATION_FILE);
        if (LOG.isWarnEnabled()) {
            LOG.warn("No configuration found. Configuring ehcache from ehcache-failsafe.xml"
                    + " found in the classpath: " + url);
        }
    }
    parser.parse(url.toExternalForm(), handler);
}

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

/**
 * Convenience XMLRPCClient constructor. Creates new instance based on server URL
 * //from www . j a  v a2  s  .  c o  m
 * @param XMLRPC
 *            server URL
 * @param HttpClient
 *            to use
 */
public XMLRPCClient(URL url, HttpClient client) {
    this(URI.create(url.toExternalForm()), client);
}

From source file:com.redhat.ewittman.MultiReferencePropertyJoinTest.java

@Test
public void test() throws Exception {
    Repository repository = null;/*from   w w  w.  jav a 2  s.c  om*/
    AnonymousCredentials credentials = new AnonymousCredentials();
    Session session = null;
    Node rootNode = null;

    // Get the ModeShape repo
    Map<String, String> parameters = new HashMap<String, String>();
    URL configUrl = getClass().getResource("inmemory-config.json");
    RepositoryConfiguration config = RepositoryConfiguration.read(configUrl);
    Problems problems = config.validate();
    if (problems.hasErrors()) {
        throw new RepositoryException(problems.toString());
    }
    parameters.put("org.modeshape.jcr.URL", configUrl.toExternalForm());
    for (RepositoryFactory factory : ServiceLoader.load(RepositoryFactory.class)) {
        repository = factory.getRepository(parameters);
        if (repository != null)
            break;
    }
    if (repository == null) {
        throw new RepositoryException("ServiceLoader could not instantiate JCR Repository");
    }

    // Configure it with our CND
    InputStream is = null;
    session = repository.login(credentials, "default");

    // Register some namespaces.
    NamespaceRegistry namespaceRegistry = session.getWorkspace().getNamespaceRegistry();
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP, JCRConstants.SRAMP_NS);
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP_PROPERTIES, JCRConstants.SRAMP_PROPERTIES_NS);
    namespaceRegistry.registerNamespace(JCRConstants.SRAMP_RELATIONSHIPS, JCRConstants.SRAMP_RELATIONSHIPS_NS);

    NodeTypeManager manager = (NodeTypeManager) session.getWorkspace().getNodeTypeManager();

    // Register the ModeShape S-RAMP node types ...
    is = getClass().getResourceAsStream("multiref-property-join.cnd");
    manager.registerNodeTypes(is, true);
    IOUtils.closeQuietly(is);
    session.logout();

    ////////////////////////////////////////////////
    // Add some artifact nodes.
    ////////////////////////////////////////////////
    session = repository.login(credentials, "default");
    rootNode = session.getRootNode();
    String jcrNodeType = JCRConstants.SRAMP_ + "artifact";
    // Node - Artifact A
    /////////////////////////
    Node artifactA = rootNode.addNode("artifact-a", jcrNodeType);
    artifactA.setProperty("sramp:uuid", "1");
    artifactA.setProperty("sramp:name", "A");
    artifactA.setProperty("sramp:model", "core");
    artifactA.setProperty("sramp:type", "Document");
    // Node - Artifact B
    /////////////////////////
    Node artifactB = rootNode.addNode("artifact-b", jcrNodeType);
    artifactB.setProperty("sramp:uuid", "2");
    artifactB.setProperty("sramp:name", "B");
    artifactB.setProperty("sramp:model", "core");
    artifactB.setProperty("sramp:type", "Document");
    // Node - Artifact C
    /////////////////////////
    Node artifactC = rootNode.addNode("artifact-c", jcrNodeType);
    artifactC.setProperty("sramp:uuid", "3");
    artifactC.setProperty("sramp:name", "C");
    artifactC.setProperty("sramp:model", "core");
    artifactC.setProperty("sramp:type", "Document");
    session.save();

    //////////////////////////////////////////////////////////////////////
    // Add the relationship nodes.  Here's what
    // I'm going for here:
    //    A has relationships to both B and C of type 'relatesTo'
    //    A has a relationship to C of type 'isDocumentedBy'
    //    B has a single relationship to C of type 'covets'
    //    C has no relationships
    //////////////////////////////////////////////////////////////////////
    Node relA_relatesTo = artifactA.addNode("relatesTo", "sramp:relationship");
    relA_relatesTo.setProperty("sramp:type", "relatesTo");
    Value[] targets = new Value[2];
    targets[0] = session.getValueFactory().createValue(artifactB, false);
    targets[1] = session.getValueFactory().createValue(artifactC, false);
    relA_relatesTo.setProperty("sramp:target", targets);

    Node relA_isDocumentedBy = artifactA.addNode("isDocumentedBy", "sramp:relationship");
    relA_isDocumentedBy.setProperty("sramp:type", "isDocumentedBy");
    relA_isDocumentedBy.setProperty("sramp:target", session.getValueFactory().createValue(artifactC, false));

    Node relB_covets = artifactB.addNode("relationship-b-1", "sramp:relationship");
    relB_covets.setProperty("sramp:type", "covets");
    relB_covets.setProperty("sramp:target", session.getValueFactory().createValue(artifactC, false));

    session.save();
    session.logout();

    //////////////////////////////////////////////////////////////////////
    // Now it's time to do some querying.
    //////////////////////////////////////////////////////////////////////
    session = repository.login(credentials, "default");
    // Show that we have the 'relatesTo' relationship set up for Artifact A (with two targets)
    String query = "SELECT relationship.[sramp:target] AS target_jcr_uuid\r\n"
            + "    FROM [sramp:artifact] AS artifact \r\n"
            + "    JOIN [sramp:relationship] AS relationship ON ISCHILDNODE(relationship, artifact) \r\n"
            + "   WHERE artifact.[sramp:name] = 'A'\r\n"
            + "     AND relationship.[sramp:type] = 'relatesTo'\r\n" + "";
    QueryManager jcrQueryManager = session.getWorkspace().getQueryManager();
    javax.jcr.query.Query jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    QueryResult jcrQueryResult = jcrQuery.execute();
    System.out.println("Result 1:");
    System.out.println(jcrQueryResult.toString());
    NodeIterator jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected one (1) node to come back (with two values).", 1, jcrNodes.getSize());
    Node n = jcrNodes.nextNode();
    Set<String> jcr_uuids = new HashSet<String>();
    for (Value value : n.getProperty("sramp:target").getValues()) {
        System.out.println("  Found JCR UUID: " + value.getString());
        jcr_uuids.add(value.getString());
    }

    // Now show that the UUIDs found above match the jcr:uuid for Artifact B and Artifact C
    query = "SELECT artifact.[jcr:uuid]\r\n" + "  FROM [sramp:artifact] AS artifact \r\n"
            + " WHERE artifact.[sramp:name] = 'B' OR artifact.[sramp:name] = 'C'\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 2:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes to come back.", 2, jcrNodes.getSize());
    Node n1 = jcrNodes.nextNode();
    Node n2 = jcrNodes.nextNode();
    Assert.assertTrue("Expected to find the JCR UUID in jcr_uuids",
            jcr_uuids.contains(n1.getProperty("jcr:uuid").getString()));
    Assert.assertTrue("Expected to find the JCR UUID in jcr_uuids",
            jcr_uuids.contains(n2.getProperty("jcr:uuid").getString()));
    System.out.println("Confirmed: the [jcr:uuid] for both Artifact B and Artifact C were found!");

    // OK - so far so good.  Now put it all together in a single query!  Here
    // we are trying to select Artifact B and Artifact C by selecting all Artifacts
    // that Artifatc A has a 'relatesTo' relationship on
    query = "SELECT artifact2.*\r\n" + "   FROM [sramp:artifact] AS artifact1\r\n"
            + "   JOIN [sramp:relationship] AS relationship1 ON ISCHILDNODE(relationship1, artifact1)\r\n"
            + "   JOIN [sramp:artifact] AS artifact2 ON relationship1.[sramp:target] = artifact2.[jcr:uuid]\r\n"
            + "   WHERE artifact1.[sramp:name] = 'A'\r\n"
            + "    AND relationship1.[sramp:type] = 'relatesTo')\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 3:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes (Artifact B and Artifact C) to come back!", 2,
            jcrNodes.getSize());

    // We made it past that.  Cool.  Let's try the same query but with a DISTINCT on it.  We'll
    // need this in case multiple artifacts have the same relationship to the same other artifact.  We
    // don't want that other artifact showing up in the result set multiple times.
    query = "SELECT DISTINCT artifact2.*\r\n" + "   FROM [sramp:artifact] AS artifact1\r\n"
            + "   JOIN [sramp:relationship] AS relationship1 ON ISCHILDNODE(relationship1, artifact1)\r\n"
            + "   JOIN [sramp:artifact] AS artifact2 ON relationship1.[sramp:target] = artifact2.[jcr:uuid]\r\n"
            + "   WHERE artifact1.[sramp:name] = 'A'\r\n"
            + "    AND relationship1.[sramp:type] = 'relatesTo')\r\n" + "";
    jcrQueryManager = session.getWorkspace().getQueryManager();
    jcrQuery = jcrQueryManager.createQuery(query, JCRConstants.JCR_SQL2);
    jcrQueryResult = jcrQuery.execute();
    System.out.println("\n\nResult 3:");
    System.out.println(jcrQueryResult.toString());
    jcrNodes = jcrQueryResult.getNodes();
    Assert.assertEquals("Expected two (2) nodes (Artifact B and Artifact C) to come back!", 2,
            jcrNodes.getSize());

    session.logout();

}

From source file:net.sourceforge.dita4publishers.impl.dita.InMemoryDitaLinkManagementService.java

/**
 * @param keyAccessOptions Options that control access to resources.
 * @param resUrl Absolute URL of the target resource.
 * @return Root element of the target resource (topic or map).
 *///  w ww . ja  v  a 2s  .c o  m
private Element resolveUriToElement(KeyAccessOptions keyAccessOptions, URL resUrl) throws DitaApiException {
    Element result = null;
    Document doc = null;
    String urlString = resUrl.toExternalForm();
    String resUrlString = null;
    if (urlString.contains("#")) {
        resUrlString = urlString.substring(0, urlString.indexOf("#"));
    } else {
        resUrlString = urlString;
    }

    try {
        InputSource src = new InputSource(resUrl.openStream());
        src.setSystemId(resUrlString);
        doc = DomUtil.getDomForSource(src, bosOptions, false);
    } catch (Exception e) {
        throw new DitaApiException("Exception contructing DOM from URL " + resUrl + ": " + e.getMessage(), e);
    }

    if (urlString.contains("#")) {
        String fragId = urlString.split("#")[1];
        result = DitaUtil.resolveDitaFragmentId(doc, fragId);
    } else {
        result = DitaUtil.getImplicitElementFromDoc(doc);
    }

    return result;
}

From source file:com.scoopit.weedfs.client.WeedFSClientImpl.java

@Override
public MasterStatus getMasterStatus() throws IOException {
    URL url = new URL(masterURL, "/dir/status");

    HttpGet get = new HttpGet(url.toString());

    try {//from  www.  j a v  a2s .c  o  m
        HttpResponse response = httpClient.execute(get);
        StatusLine line = response.getStatusLine();

        if (line.getStatusCode() != 200) {
            throw new IOException("Not 200 status recieved for master status url: " + url.toExternalForm());
        }

        String content = getContentOrNull(response);
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(content, MasterStatus.class);

        } catch (JsonMappingException | JsonParseException e) {
            throw new WeedFSException("Unable to parse JSON from weed-fs from: " + content, e);
        }
    } finally {
        get.abort();
    }
}

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

@Override
public void run(final Product product) {
    if (ImageIO.getUseCache())
        ImageIO.setUseCache(false);

    DrbNode node = null;//from w w  w. ja v a  2s. c  om
    URL url = product.getPath();

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

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

    } catch (Exception e) {
        logger.error("Exception raised while processing Quicklook", e);
        return;
    }

    if (!ImageFactory.isImage(node)) {
        logger.debug("No Image.");
        return;
    }

    RenderedImageList input_list = null;
    RenderedImage input_image = null;
    try {
        input_list = ImageFactory.createImage(node);
        input_image = RenderingFactory.createDefaultRendering(input_list);
    } catch (Exception e) {
        logger.debug("Cannot retrieve default rendering");
        if (logger.isDebugEnabled()) {
            logger.debug("Error occurs during rendered image reader", e);
        }

        if (input_list == null)
            return;
        input_image = input_list;
    }

    int quicklook_width = cfgManager.getProductConfiguration().getQuicklookConfiguration().getWidth();
    int quicklook_height = cfgManager.getProductConfiguration().getQuicklookConfiguration().getHeight();
    boolean quicklook_cutting = cfgManager.getProductConfiguration().getQuicklookConfiguration().isCutting();

    logger.info("Generating Quicklook " + quicklook_width + "x" + quicklook_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight());

    RenderedImage image = ProcessingUtils.ResizeImage(input_image, quicklook_width, quicklook_height, 10f,
            quicklook_cutting);

    String product_id = product.getIdentifier();
    if (product_id == null)
        product_id = "unknown";

    // Manages the quicklook output
    File image_directory = incomingManager.getNewIncomingPath();

    LockFactory lf = new NativeFSLockFactory(image_directory);
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    File file = new File(image_directory, product_id + "-ql.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setQuicklookPath(file.getPath());
        product.setQuicklookSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save quicklook.", e);
    }

    // Thumbnail
    int thumbnail_width = cfgManager.getProductConfiguration().getThumbnailConfiguration().getWidth();
    int thumbnail_height = cfgManager.getProductConfiguration().getThumbnailConfiguration().getHeight();
    boolean thumbnail_cutting = cfgManager.getProductConfiguration().getThumbnailConfiguration().isCutting();

    logger.info("Generating Thumbnail " + thumbnail_width + "x" + thumbnail_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight() + " image.");

    image = ProcessingUtils.ResizeImage(input_image, thumbnail_width, thumbnail_height, 10f, thumbnail_cutting);

    // Manages the quicklook output
    file = new File(image_directory, product_id + "-th.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setThumbnailPath(file.getPath());
        product.setThumbnailSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save thumbnail.", e);
    }
    SdiImageFactory.close(input_list);
    try {
        lock.close();
    } catch (IOException e) {
    }
}

From source file:com.hp.hpl.jena.sparql.engine.http.HttpQuery.java

private InputStream execPost() throws QueryExceptionHTTP {
    URL target = null;
    try {/*from w ww .  jav a2 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 {
        httpConnection = (HttpURLConnection) target.openConnection();
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Accept", contentTypeResult);
        httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        basicAuthentication(httpConnection);
        applyTimeouts(httpConnection);
        applyEncodings(httpConnection);
        httpConnection.setDoOutput(true);

        boolean first = true;
        OutputStream out = httpConnection.getOutputStream();
        for (Iterator<Pair> iter = pairs().listIterator(); iter.hasNext();) {
            if (!first)
                out.write('&');
            first = false;
            Pair p = iter.next();
            out.write(p.getName().getBytes());
            out.write('=');
            String x = p.getValue();
            x = Convert.encWWWForm(x);
            out.write(x.getBytes());
            ARQ.getHttpRequestLogger().trace("Param: " + x);
        }
        out.flush();
        httpConnection.connect();
        return execCommon();
    } catch (java.net.ConnectException connEx) {
        throw new QueryExceptionHTTP(-1, "Failed to connect to remote server");
    } catch (SocketTimeoutException timeoutEx) {
        throw new QueryExceptionHTTP(-1, "Failed to connect to remove server within specified timeout");
    } catch (IOException ioEx) {
        throw new QueryExceptionHTTP(ioEx);
    }
}