Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified host.
 * @param u the URL on which to base the returned URL
 * @param newHost the new host to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified host
 * @throws MalformedURLException if there is a problem creating the new URL
 *///from   w  w  w . j  ava2 s .  c o  m
public static URL getUrlWithNewHost(final URL u, final String newHost) throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), newHost, u.getPort(), u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Adds parameter to a query string/*from w  w w. j  a  v a  2  s .c  o m*/
 *
 * @param url            url
 * @param parameterName  parameter name
 * @param parameterValue parameter value
 */
@SuppressWarnings("UnusedDeclaration")
public static String addParameter(String url, String parameterName, String parameterValue) {
    try {
        if (url == null) {
            return null;
        }

        StringBuilder targetUrl = new StringBuilder();
        targetUrl.append(url);

        URL testURL = new URL(url);
        if (testURL.getQuery() != null) {
            targetUrl.append("&");
        } else if ("".equals(testURL.getPath())) {
            targetUrl.append("/?");
        } else {
            targetUrl.append("?");
        }

        targetUrl.append(parameterName);
        targetUrl.append("=");
        targetUrl.append(parameterValue);

        return targetUrl.toString();
    } catch (MalformedURLException ex) {
        return url;
    }
}

From source file:com.aurel.track.lucene.LuceneUtil.java

/**
 * Gets the context path of the application
 * @return/*from w w w .  j  a v  a2  s .c  om*/
 */
public static String getContexPath() {
    URL url = null;
    File file;
    //get the application context path
    url = LuceneUtil.class.getResource("/../..");
    if (url == null) {
        return null;
    }
    if (url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(url.getPath());
        }
    }
    //see Bug ID:  4466485 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485) 
    URI uri = null;
    try {
        uri = new URI(url.toString());
    } catch (URISyntaxException e) {
        LOGGER.error("Getting the lucene index root URI from URL failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (uri == null) {
        return null;
    }
    //sometimes it is enough
    if (uri.getPath() != null) {
        file = new File(uri.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(uri.getPath());
        }
    }

    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
    }
    if (url != null && url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            return stripTrailingPathSeparator(url.getPath());
        }
    }
    return "";
}

From source file:com.tc.util.ProductInfo.java

static InputStream getData(String name) {
    CodeSource codeSource = ProductInfo.class.getProtectionDomain().getCodeSource();
    if (codeSource != null && codeSource.getLocation() != null) {
        URL source = codeSource.getLocation();

        if (source.getProtocol().equals("file") && source.toExternalForm().endsWith(".jar")) {
            URL res;//  w  ww  .ja  va 2  s  . co  m
            try {
                res = new URL("jar:" + source.toExternalForm() + "!" + name);
                InputStream in = res.openStream();
                if (in != null) {
                    return in;
                }
            } catch (MalformedURLException e) {
                throw new AssertionError(e);
            } catch (IOException e) {
                // must not be embedded in this jar -- resolve via loader path
            }
        } else if (source.getProtocol().equals("file") && (new File(source.getPath()).isDirectory())) {
            File local = new File(source.getPath(), name);

            if (local.isFile()) {
                try {
                    return new FileInputStream(local);
                } catch (FileNotFoundException e) {
                    throw new AssertionError(e);
                }
            }
        }
    }

    return ProductInfo.class.getResourceAsStream(name);
}

From source file:fr.gael.dhus.datastore.processing.ProcessingUtils.java

public static List<MetadataIndex> getIndexesFrom(URL url) {
    java.util.Collection<String> properties = null;
    DrbNode node = null;// ww  w.  ja  va2 s . com
    DrbCortexItemClass cl = null;

    // Prepare the index structure.
    List<MetadataIndex> indexes = new ArrayList<MetadataIndex>();

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        node = ProcessingUtils.getNodeFromPath(url.getPath());
        cl = ProcessingUtils.getClassFromNode(node);
        logger.info("Class \"" + cl.getLabel() + "\" for product " + node.getName());

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

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

    // Loop among retrieved property values
    for (String property : properties) {
        // Filter possible XML markup brackets that could have been encoded
        // in a CDATA section
        property = property.replaceAll("&lt;", "<");
        property = property.replaceAll("&gt;", ">");
        /*
         * property = property.replaceAll("\n", " "); // Replace eol by blank
         * space property = property.replaceAll(" +", " "); // Remove
         * contiguous blank spaces
         */

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

        // Evaluate the XQuery
        DrbSequence metadataSequence = metadataQuery.evaluate(node);

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

        // Loop among results
        for (int iitem = 0; iitem < metadataSequence.getLength(); iitem++) {
            // Get current metadata node
            DrbNode n = (DrbNode) metadataSequence.getItem(iitem);

            // Get name
            DrbAttribute name_att = n.getAttribute("name");
            Value name_v = null;
            if (name_att != null)
                name_v = name_att.getValue();
            String name = null;
            if (name_v != null)
                name = name_v.convertTo(Value.STRING_ID).toString();

            // get type
            DrbAttribute type_att = n.getAttribute("type");
            Value type_v = null;
            if (type_att != null)
                type_v = type_att.getValue();
            else
                type_v = new fr.gael.drb.value.String(MIME_PLAIN_TEXT);
            String type = type_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute cat_att = n.getAttribute("category");
            Value cat_v = null;
            if (cat_att != null)
                cat_v = cat_att.getValue();
            else
                cat_v = new fr.gael.drb.value.String("product");
            String category = cat_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute qry_att = n.getAttribute("queryable");
            String queryable = null;
            if (qry_att != null) {
                Value qry_v = qry_att.getValue();
                if (qry_v != null)
                    queryable = qry_v.convertTo(Value.STRING_ID).toString();
            }

            // Get value
            String value = null;
            if (MIME_APPLICATION_GML.equals(type) && n.hasChild()) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                XmlWriter.writeXML(n.getFirstChild(), out);
                value = out.toString();
                try {
                    out.close();
                } catch (IOException e) {
                    logger.warn("Cannot close stream !", e);
                }
            } else
            // Case of "text/plain"
            {
                Value value_v = n.getValue();
                if (value_v != null) {
                    value = value_v.convertTo(Value.STRING_ID).toString();
                    value = value.trim();
                }
            }

            if ((name != null) && (value != null)) {
                MetadataIndex index = new MetadataIndex();
                index.setName(name);
                try {
                    index.setType(new MimeType(type).toString());
                } catch (MimeTypeParseException e) {
                    logger.warn("Wrong metatdata extractor mime type in class \"" + cl.getLabel()
                            + "\" for metadata called \"" + name + "\".", e);
                }
                index.setCategory(category);
                index.setValue(value);
                index.setQueryable(queryable);
                indexes.add(index);
            } else {
                String field_name = "";
                if (name != null)
                    field_name = name;
                else if (queryable != null)
                    field_name = queryable;
                else if (category != null)
                    field_name = "of category " + category;

                logger.warn("Nothing extracted for field " + field_name);
            }
        }
    }
    return indexes;
}

From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java

/**
 * Creates and returns a new URL identical to the specified URL, except using the specified host.
 * @param u the URL on which to base the returned URL
 * @param newHost the new host to use in the returned URL
 * @param newPort the new port to use in the returned URL
 * @return a new URL identical to the specified URL, except using the specified host
 * @throws MalformedURLException if there is a problem creating the new URL
 *///w  w  w.  ja v a2 s.  c o  m
public static URL getUrlWithNewHostAndPort(final URL u, final String newHost, final int newPort)
        throws MalformedURLException {
    return createNewUrl(u.getProtocol(), u.getUserInfo(), newHost, newPort, u.getPath(), u.getRef(),
            u.getQuery());
}

From source file:com.streamsets.datacollector.cluster.ClusterProviderImpl.java

private static List<URL> findJars(String name, URLClassLoader cl, @Nullable String stageClazzName)
        throws IOException {
    Properties properties = readDataCollectorProperties(cl);
    List<String> blacklist = new ArrayList<>();
    for (Map.Entry entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        if (stageClazzName != null && key.equals(CLUSTER_MODE_JAR_BLACKLIST + stageClazzName)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        } else if (key.equals(CLUSTER_MODE_JAR_BLACKLIST + ALL_STAGES)) {
            String value = (String) entry.getValue();
            blacklist.addAll(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(value));
        }//from w  w w. ja v a  2s. c o m
    }
    if (IS_TRACE_ENABLED) {
        LOG.trace("Blacklist for '{}': '{}'", name, blacklist);
    }
    List<URL> urls = new ArrayList<>();
    for (URL url : cl.getURLs()) {
        if (blacklist.isEmpty()) {
            urls.add(url);
        } else {
            if (exclude(blacklist, FilenameUtils.getName(url.getPath()))) {
                LOG.trace("Skipping '{}' for '{}' due to '{}'", url, name, blacklist);
            } else {
                urls.add(url);
            }
        }
    }
    return urls;
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Gets a file with a given path relativ to classes directory from the WEB-INF
 * @param url//from  ww  w.  j  a  va 2  s .  c  om
 * @return
 */
public static File getFileFromURL(URL url) {
    File file;
    if (url == null) {
        return null;
    }
    if (url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            //valid url
            return file;
        }
    }

    //valid file through URI?
    //see Bug ID:  4466485 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485)
    URI uri = null;
    try {
        //get rid of spaces
        uri = new URI(url.toString());
    } catch (URISyntaxException e1) {
    }
    if (uri == null) {
        return null;
    }
    if (uri.getPath() != null) {
        file = new File(uri.getPath());
        if (file.exists()) {
            return file;
        }
    }
    //back to URL from URI
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
    }
    if (url != null && url.getPath() != null) {
        file = new File(url.getPath());
        if (file.exists()) {
            //valid url
            return file;
        }
    }
    return null;
}

From source file:io.fabric8.maven.generator.javaexec.FatJarDetectorTest.java

private String decodeUrl(URL testDirUrl) throws UnsupportedEncodingException {
    return URLDecoder.decode(testDirUrl.getPath(), "UTF-8");
}

From source file:com.centeractive.ws.legacy.SchemaUtils.java

private static void loadDefaultSchema(URL url) throws Exception {
    XmlObject xmlObject = XmlUtils.createXmlObject(url);
    if (!((Document) xmlObject.getDomNode()).getDocumentElement().getNamespaceURI().equals(Constants.XSD_NS)) {

        return;/*from   www .jav  a  2 s  .  c o m*/
    }

    String targetNamespace = getTargetNamespace(xmlObject);

    if (defaultSchemas.containsKey(targetNamespace)) {
        log.warn("Overriding schema for targetNamespace " + targetNamespace);
    }

    defaultSchemas.put(targetNamespace, xmlObject);

    log.debug("Added default schema from " + url.getPath() + " with targetNamespace " + targetNamespace);
}