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:pl.softech.learning.gwtp.simple.server.spring.RemoteLoggingHandler.java

@Override
public void setServletContext(final ServletContext servletContext) {
    this.servletContext = servletContext;

    final String path = servletContext.getInitParameter("symbolMapsPath");
    if (path != null) {
        URL url = RemoteLoggingHandler.class.getResource("/");
        LOGGER.debug("Current path is {}", url.getFile());
        String rootPath = "/../../";
        URL rootPathUrl = RemoteLoggingHandler.class.getResource(rootPath);
        if (rootPathUrl != null) {
            LOGGER.debug("Root app path is {}", rootPathUrl.getFile());
        }/*from   ww  w  . j a  v  a2s . co  m*/
        URL symbolMapsUrl = RemoteLoggingHandler.class.getResource(String.format("%s%s", rootPath, path));
        if (symbolMapsUrl != null) {
            String symbolMapsDir = symbolMapsUrl.getPath();
            LOGGER.debug("SymbolMaps absolute path is {}", symbolMapsDir);
            deobfuscator = new StackTraceDeobfuscator(symbolMapsDir);
            LOGGER.debug("Created deobfuscator with symbolMaps located {}", path);
        }
    }
}

From source file:crawler.RobotstxtServer.java

/** Please note that in the case of a bad URL, TRUE will be returned */
public boolean allows(WebURL webURL) {
    if (!config.isEnabled()) {
        return true;
    }/*w w  w  .  ja  v a2 s. c  o  m*/
    try {
        URL url = new URL(webURL.getURL());
        String host = getHost(url);
        String path = url.getPath();

        HostDirectives directives = host2directivesCache.get(host);

        if (directives != null && directives.needsRefetch()) {
            synchronized (host2directivesCache) {
                host2directivesCache.remove(host);
                directives = null;
            }
        }
        if (directives == null) {
            directives = fetchDirectives(url);
        }
        return directives.allows(path);
    } catch (MalformedURLException e) {
        logger.error("Bad URL in Robots.txt: " + webURL.getURL(), e);
    }

    logger.warn("RobotstxtServer: default: allow", webURL.getURL());
    return true;
}

From source file:com.jaspersoft.jasperserver.war.xmla.XmlaServletImpl.java

public void init(ServletConfig config) throws ServletException {
    ServletContext servletContext = config.getServletContext();

    // TODO it is meaningless to generate URLs here, but the XMLServlet requires it
    // Looks like XML/A clients ignore the URL
    try {/*from w w w  .  j a  v a  2 s.  c o  m*/
        InetAddress local = InetAddress.getLocalHost();

        // We can override the default protocol and port with servlet init parameters

        String defaultProtocol = servletContext.getInitParameter("defaultProtocol");
        if (defaultProtocol == null || defaultProtocol.trim().length() == 0) {
            defaultProtocol = "http";
        }

        String defaultPort = servletContext.getInitParameter("defaultPort");
        if (defaultPort == null || defaultPort.trim().length() == 0) {
            defaultPort = "-1";
        }
        int port = Integer.parseInt(defaultPort);

        URL root = servletContext.getResource("/");
        // Looks like the path will be /localhost/webapp

        int pastHost = root.getPath().indexOf("/", 1);
        String path = root.getPath().substring(pastHost, root.getPath().length());

        SERVER_URL = (new URL(defaultProtocol, local.getCanonicalHostName(), port, path)).toString() + "xmla";
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    super.init(config);
}

From source file:com.chinamobile.bcbsp.util.BSPJob.java

/**
 * Find the BC-BSP application jar of the job.
 * @param myClass/*from   w  ww.jav  a 2  s. com*/
 *        The BC-BSP application jarFileClass of the job.
 * @return The name of the jar.
 */
private static String findContainingJar(Class<?> myClass) {
    ClassLoader loader = myClass.getClassLoader();
    String classFile = myClass.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        LOG.error("[findContainingJar]", e);
        throw new RuntimeException(e);
    }
    return null;
}

From source file:com.googlecode.l10nmavenplugin.validators.property.UrlValidator.java

/**
 * ERROR if URL does not match regexp./*from  ww  w . j  a v  a  2 s .c om*/
 * 
 * ERROR if URL does not support https context and is an HTML import.
 * 
 * Performs a MessageFormat if needed.
 * 
 * @note the {@link org.apache.commons.validator.UrlValidator} from Apache does not seem to support scheme relative URLs.
 * 
 * @param key
 * @param message
 * @param propertyName
 * @return Number of errors
 */
public int validate(Property property, List<L10nReportItem> reportItems) {
    int nbErrors = 0;
    String formattedMessage = property.getMessage();

    try {
        if (formattingParametersExtractor.isParametric(formattedMessage)) {
            formattedMessage = formattingParametersExtractor.defaultFormat(property.getMessage());
        }
        // Unescape HTML in case URL is used in HTML context (ex: &amp; -> &)
        String url = StringEscapeUtils.unescapeHtml(formattedMessage);
        Matcher m = URL_VALIDATION_PATTERN.matcher(url);

        if (!m.matches()) {
            nbErrors++;
            L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION, "Invalid URL syntax.", property,
                    formattedMessage);
            reportItems.add(reportItem);
            logger.log(reportItem);

        } else {
            // If URL path extension is an HTML include (.js, .css, .jpg, ...) check that URL inherits https protocol
            // Context is mandatory for scheme relative URLs
            URL context = new URL("https://");
            URL resultingURL = new URL(context, url);

            String extension = FilenameUtils.getExtension(resultingURL.getPath());
            if (HTML_URL_INCLUDE_EXTESIONS.contains(extension) && !"https".equals(resultingURL.getProtocol())) {
                nbErrors++;
                L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION,
                        "URL for external HTML import [." + extension
                                + "] must be scheme relative to avoid mixed content in HTTPS context.",
                        property, formattedMessage);
                reportItems.add(reportItem);
                logger.log(reportItem);
            }
        }

    } catch (IllegalArgumentException e) {
        // Catch MessageFormat errors in case of malformed message
        nbErrors++;
        L10nReportItem reportItem = new L10nReportItem(Type.MALFORMED_PARAMETER,
                "URL contains malformed parameters: " + e.getMessage(), property, formattedMessage);
        reportItems.add(reportItem);
        logger.log(reportItem);
    } catch (MalformedURLException e) {
        nbErrors++;
        L10nReportItem reportItem = new L10nReportItem(Type.URL_VALIDATION, "Malformed URL: " + e.getMessage(),
                property, formattedMessage);
        reportItems.add(reportItem);
        logger.log(reportItem);
    }

    return nbErrors;
}

From source file:es.tid.fiware.rss.common.test.DatabaseLoader.java

/**
 * Clean insert.//from ww  w .  ja  v  a 2s.c o  m
 * 
 * @param resource
 *            the resource
 * @param commit
 *            the commit
 * @throws Exception
 *             the exception
 */
public void cleanInsert(String resource, boolean commit) throws Exception {
    DatabaseLoader.logger.debug("cleanInsert: " + resource);
    URL url = this.getClass().getClassLoader().getResource(resource);
    DatabaseLoader.logger.debug("Resource url: " + url.getPath());
    IDataSet ds = loader.build(url);
    DatabaseOperation.CLEAN_INSERT.execute(dbConn, ds);

    if (commit) {
        dbConn.getConnection().commit();
    }

}

From source file:com.mgmtp.perfload.core.console.meta.LtMetaInfoHandler.java

/**
 * Dumps the specified meta information to specified writer.
 * /*from   ww  w . j a  v  a  2 s  .c om*/
 * @param metaInfo
 *            the meta information object
 * @param writer
 *            the writer
 */
public void dumpMetaInfo(final LtMetaInfo metaInfo, final Writer writer) {
    PrintWriter pr = new PrintWriter(writer);

    URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
    if (url.getPath().endsWith(".jar")) {
        try {
            JarFile jarFile = new JarFile(toFile(url));
            Manifest mf = jarFile.getManifest();
            Attributes attr = mf.getMainAttributes();
            pr.printf("perfload.implementation.version=%s", attr.getValue("Implementation-Version"));
            pr.println();
            pr.printf("perfload.implementation.date=%s", attr.getValue("Implementation-Date"));
            pr.println();
            pr.printf("perfload.implementation.revision=%s", attr.getValue("Implementation-Revision"));
            pr.println();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    pr.printf("test.file=%s", metaInfo.getTestplanFileName());
    pr.println();

    pr.printf("test.start=%s", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(metaInfo.getStartTimestamp()));
    pr.println();
    pr.printf("test.finish=%s", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(metaInfo.getFinishTimestamp()));
    pr.println();

    List<Daemon> daemonList = metaInfo.getDaemons();
    Collections.sort(daemonList);

    for (Daemon daemon : daemonList) {
        pr.printf("daemon.%d=%s:%d", daemon.getId(), daemon.getHost(), daemon.getPort());
        pr.println();
    }

    List<String> lpTargets = metaInfo.getLpTargets();
    if (!lpTargets.isEmpty()) {
        Collections.sort(lpTargets);
        pr.printf("targets=%s", on(',').join(lpTargets));
        pr.println();
    }

    List<String> lpOperations = metaInfo.getLpOperations();
    if (!lpOperations.isEmpty()) {
        Collections.sort(lpOperations);
        pr.printf("operations=%s", on(',').join(lpOperations));
        pr.println();
    }

    List<Executions> executionsList = metaInfo.getExecutionsList();
    Collections.sort(executionsList);
    for (Executions executions : executionsList) {
        pr.printf("executions.%s.%s=%d", executions.operation, executions.target, executions.executions);
        pr.println();
    }
}

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

/**
 * Gets a file (or directory) with a specific name from the root of the web application
 * @param servletContext//from  ww  w  .j av  a 2 s.  c  om
 * @param fileName
 * @return
 */
public static File getResourceFileFromWebAppRoot(ServletContext servletContext, String fileName) {
    URL urlDest;
    File file = null;
    //first try to get the template dir through class.getResource(path)
    urlDest = PluginUtils.class.getResource("/../../" + fileName);
    urlDest = createValidFileURL(urlDest);
    if (urlDest != null) {
        file = new File(urlDest.getPath());
    }
    //second try to get the template dir through servletContext.getResource(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        try {
            urlDest = servletContext.getResource("/" + fileName);
            urlDest = createValidFileURL(urlDest);
            if (urlDest != null) {
                file = new File(urlDest.getPath());
            }
        } catch (MalformedURLException e) {
            LOGGER.error("Getting the URL through getServletContext().getResource(path) failed with "
                    + e.getMessage());
        }
    }
    //third try to get the template dir through servletContext.getRealPath(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        String path;
        //does not work for unexpanded .war
        path = servletContext.getRealPath(File.separator) + fileName;
        file = new File(path);
    }
    return file;
}

From source file:com.marklogic.entityservices.tests.TestSetup.java

@SuppressWarnings("unchecked")
Collection<File> getTestResources(String dirName) {
    URL filesUrl = _client.getClass().getResource(dirName);

    return FileUtils.listFiles(new File(filesUrl.getPath()), FileFilterUtils.trueFileFilter(),
            FileFilterUtils.trueFileFilter());
}

From source file:cn.austin.crawle.Parser.java

@Override
public void run() {
    List<Book> reservedBooks = new ArrayList<>();
    while (true) {
        try {//from w  ww  . j  a  v  a2s .  c o  m
            URL resource = Parser.class.getClassLoader().getResource("result.txt");
            try (FileWriter writer = new FileWriter(new File(resource.getPath()))) {
                reservedBooks = reservedBooks.stream().filter(x -> x != null).collect(toList());
                for (Book x : reservedBooks) {
                    writer.write(x.toString());
                }
                writer.flush();
            }
            List<Book> parsedBooks = parsing(messageQueue.take());
            reservedBooks = filterAndSort(reservedBooks, parsedBooks);
        } catch (Exception ex) {
            Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}