Example usage for java.net URL getFile

List of usage examples for java.net URL getFile

Introduction

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

Prototype

public String getFile() 

Source Link

Document

Gets the file name of this URL .

Usage

From source file:com.yahoo.gondola.container.ZookeeperRegistryClientTest.java

private void readConfig() {
    URL resource = ZookeeperRegistryClientTest.class.getClassLoader().getResource("gondola.conf");
    if (resource == null) {
        throw new IllegalStateException("cannot find gondola config");
    }/*  w  ww.ja  va 2  s .c  om*/
    config = new Config(new File(resource.getFile()));
}

From source file:azkaban.restli.ProjectManagerResource.java

@Action(name = "deploy")
public String deploy(@ActionParam("sessionId") String sessionId, @ActionParam("projectName") String projectName,
        @ActionParam("packageUrl") String packageUrl)
        throws ProjectManagerException, UserManagerException, ServletException, IOException {
    logger.info("Deploy called. {sessionId: " + sessionId + ", projectName: " + projectName + ", packageUrl:"
            + packageUrl + "}");

    String ip = (String) this.getContext().getRawRequestContext().getLocalAttr("REMOTE_ADDR");
    User user = ResourceUtils.getUserFromSessionId(sessionId, ip);
    ProjectManager projectManager = getAzkaban().getProjectManager();
    Project project = projectManager.getProject(projectName);
    if (project == null) {
        throw new ProjectManagerException("Project '" + projectName + "' not found.");
    }// w w w  .  j ava 2s  . c  o m

    if (!ResourceUtils.hasPermission(project, user, Permission.Type.WRITE)) {
        String errorMsg = "User " + user.getUserId() + " has no permission to write to project "
                + project.getName();
        logger.error(errorMsg);
        throw new ProjectManagerException(errorMsg);
    }

    logger.info("Target package URL is " + packageUrl);
    URL url = null;
    try {
        url = new URL(packageUrl);
    } catch (MalformedURLException e) {
        String errorMsg = "URL " + packageUrl + " is malformed.";
        logger.error(errorMsg, e);
        throw new ProjectManagerException(errorMsg, e);
    }

    String filename = getFileName(url.getFile());
    File tempDir = Utils.createTempDir();
    File archiveFile = new File(tempDir, filename);
    try {
        // Since zip files can be large, don't specify an explicit read or
        // connection
        // timeout. This will cause the call to block until the download is
        // complete.
        logger.info("Downloading package from " + packageUrl);
        FileUtils.copyURLToFile(url, archiveFile);
        Props props = new Props();

        logger.info("Downloaded to " + archiveFile.toString());
        projectManager.uploadProject(project, archiveFile, "zip", user, props);
    } catch (IOException e) {
        String errorMsg = "Download of URL " + packageUrl + " to " + archiveFile.toString() + " failed";
        logger.error(errorMsg, e);
        throw new ProjectManagerException(errorMsg, e);
    } finally {
        if (tempDir.exists()) {
            FileUtils.deleteDirectory(tempDir);
        }
    }
    return Integer.toString(project.getVersion());
}

From source file:com.alibaba.antx.expand.Expander.java

private ExpanderHandler getExpanderHandler(URL url) {
    String name = url.getFile();

    name = name.substring(name.lastIndexOf("/") + 1);

    if (name.endsWith(".war")) {
        return new WarExpanderHandler();
    } else {//from  ww  w.j  ava  2 s  .  com
        return new EarExpanderHandler(url);
    }
}

From source file:com.vmware.qe.framework.datadriven.config.DDComponentsConfig.java

private DDComponentsConfig() throws DDException {
    log.info("Initializing Components...");
    final XMLConfiguration ddconfig;
    try {//from ww w .  j a  v  a2 s  .c o m
        log.info("Config file '{}'", DD_COMPONENT_CONFIG_FILE_NAME);
        URL cfgFile = this.getClass().getResource(DD_COMPONENT_CONFIG_FILE_NAME);
        log.info("Loading Components from: {}", cfgFile);
        ddconfig = new XMLConfiguration(cfgFile.getFile());
    } catch (Exception e) {
        throw new DDException("Error loading File: " + DD_COMPONENT_CONFIG_FILE_NAME, e);
    }
    List<HierarchicalConfiguration> suppliers = ddconfig.configurationsAt(TAG_DATA_SUPPLIER);
    for (HierarchicalConfiguration supplier : suppliers) {
        String name = supplier.getString(TAG_NAME);
        String className = supplier.getString(TAG_CLASS);
        Class<?> clazz = registerClass(className);
        DataSupplier dataSupplier;
        try {
            dataSupplier = (DataSupplier) clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DDException("Error in creating supplier instance", e);
        }
        dataSupplierMap.put(name, dataSupplier);
        if (supplier.getBoolean(TAG_DEFAULT_ATTR, false)) {
            if (dataSupplierMap.containsKey(KEY_DEFAULT)) {
                throw new DDException("multiple default supplier configuration found!!!");
            } else {
                dataSupplierMap.put(KEY_DEFAULT, dataSupplier);
            }
        }
    }
    log.info("Data Suppliers: {}", dataSupplierMap.keySet());
    List<HierarchicalConfiguration> generators = ddconfig.configurationsAt(TAG_DATA_GENERATOR);
    for (HierarchicalConfiguration generator : generators) {
        String name = generator.getString(TAG_NAME);
        String className = generator.getString(TAG_CLASS);
        Class<?> clazz = registerClass(className);
        DataGenerator dataGenerator;
        try {
            dataGenerator = (DataGenerator) clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DDException("Error in creating generator instance", e);
        }
        dataGeneratorMap.put(name, dataGenerator);
        if (generator.getBoolean(TAG_DEFAULT_ATTR, false)) {
            if (dataGeneratorMap.containsKey(KEY_DEFAULT)) {
                throw new DDException("multiple default supplier configuration found!!!");
            } else {
                dataGeneratorMap.put(KEY_DEFAULT, dataGenerator);
            }
        }
    }
    log.info("Data Generators: {}", dataGeneratorMap.keySet());
    List<HierarchicalConfiguration> filters = ddconfig.configurationsAt(TAG_DATA_FILTER);
    for (HierarchicalConfiguration filter : filters) {
        String name = filter.getString(TAG_NAME);
        String className = filter.getString(TAG_CLASS);
        Class<?> clazz = registerClass(className);
        DataFilter dataFilter;
        try {
            dataFilter = (DataFilter) clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DDException("Error in creating filter instance", e);
        }
        dataFilterMap.put(name, dataFilter);
    }
    log.info("Data Filters {}", dataFilterMap.keySet());
    // No default for filters, all will be applied...
    List<HierarchicalConfiguration> instanceCreators = ddconfig.configurationsAt(TAG_INSTANCE_CREATOR);
    for (HierarchicalConfiguration instanceCreator : instanceCreators) {
        String name = instanceCreator.getString(TAG_NAME);
        String className = instanceCreator.getString(TAG_CLASS);
        Class<?> clazz = registerClass(className);
        TestInstanceCreator testInstanceCreator;
        try {
            testInstanceCreator = (TestInstanceCreator) clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DDException("Error in creating testInstanceCreator instance", e);
        }
        instanceCreatorMap.put(name, testInstanceCreator);
        if (instanceCreator.getBoolean(TAG_DEFAULT_ATTR, false)) {
            instanceCreatorMap.put(KEY_DEFAULT, testInstanceCreator);
        }
    }
    log.info("Instance Creators: {}", instanceCreatorMap.keySet());
    List<HierarchicalConfiguration> dataInjectors = ddconfig.configurationsAt(TAG_DATA_INJECTOR);
    for (HierarchicalConfiguration dataInjector : dataInjectors) {
        String name = dataInjector.getString(TAG_NAME);
        String className = dataInjector.getString(TAG_CLASS);
        Class<?> clazz = registerClass(className);
        DataInjector dataInjectorObj;
        try {
            dataInjectorObj = (DataInjector) clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new DDException("Error in creating DataInjector instance", e);
        }
        dataInjectorMap.put(name, dataInjectorObj);
        if (dataInjector.getBoolean(TAG_DEFAULT_ATTR, false)) {
            dataInjectorMap.put(KEY_DEFAULT, dataInjectorObj);
        }
    }
    log.info("Data Injectors  : {}", dataInjectorMap.keySet());
}

From source file:edu.du.penrose.systems.fedoraApp.batchIngest.data.BatchIngestURLhandlerImpl.java

/**
 * Currently only works for File: protocol URLs 
 * /*from w  w w. j  a v a2s  .c om*/
 * @param properityURL
 * @throws FatalException
 */
void checkURLlocationExists(URL properityURL) throws FatalException {

    String dirName = properityURL.getFile().replace('/', File.separatorChar);
    File directory = new File(dirName);

    if (!directory.exists()) {

        throw new FatalException(
                "Fatal Error: check applications properties file, directory does not exist: " + dirName);
    }

}

From source file:net.mojodna.sprout.SproutAutoLoaderPlugIn.java

public void autoloadClasses(final WebApplicationContext wac) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    if (loader instanceof URLClassLoader) {
        URL[] cp = ((URLClassLoader) loader).getURLs();

        for (int i = 0; i < cp.length; i++) {
            URL url = cp[i];

            if (url.getProtocol().equals("file")) {
                String pathname = url.getFile();
                File file = new File(pathname);

                if (file.isDirectory()) {
                    autoloadFromDirectory(loader, pathname.length(), file);
                }//ww w  . j  av a2  s .co  m
            }
        }
    }
}

From source file:dsd.controller.ParserControler.java

private String ReturnRootPath() {
    // URL returned
    URL r = this.getClass().getResource("/");

    // path decoded
    String decoded = null;//from  ww  w . j  av  a2  s  . c o m
    try {
        decoded = URLDecoder.decode(r.getFile(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (decoded.startsWith("/"))
        decoded = decoded.replaceFirst("/", "");
    return decoded.replaceAll("WEB-INF/classes/", "");
}

From source file:info.magnolia.cms.beans.config.ModuleRegistration.java

/**
 * @param xmlUrl// www  .ja v  a 2  s . c  o  m
 * @return
 */
protected File getModuleRoot(URL xmlUrl) {
    String xmlString = xmlUrl.getFile();
    String protocol = xmlUrl.getProtocol();

    File moduleRoot = null;

    if ("jar".equals(protocol)) {
        xmlString = StringUtils.substringBefore(xmlString, ".jar!") + ".jar";
        try {
            moduleRoot = new File(new URI(xmlString));
        } catch (URISyntaxException e) {
            // should never happen
            log.error(e.getMessage(), e);
        }
    } else {
        try {
            File xmlFile = new File(new URI(xmlUrl.toString()));
            moduleRoot = xmlFile.getParentFile().getParentFile().getParentFile();
        } catch (URISyntaxException e) {
            // should never happen
            log.error(e.getMessage(), e);
        }
    }
    return moduleRoot;
}

From source file:com.alfaariss.oa.OAContextListener.java

/**
 * Starts the engine before all servlets are initialized.
 * /*  w w w .  j  a  v  a2 s  .  c om*/
 * Searches for the properties needed for the configuration in:
 * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code>
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent oServletContextEvent) {
    Properties pConfig = new Properties();
    try {
        _logger.info("Starting Asimba");

        Package pCurrent = OAContextListener.class.getPackage();

        String sSpecVersion = pCurrent.getSpecificationVersion();
        if (sSpecVersion != null)
            _logger.info("Specification-Version: " + sSpecVersion);

        String sImplVersion = pCurrent.getImplementationVersion();
        if (sImplVersion != null)
            _logger.info("Implementation-Version: " + sImplVersion);

        ServletContext oServletContext = oServletContextEvent.getServletContext();

        Enumeration enumContextAttribs = oServletContext.getInitParameterNames();
        while (enumContextAttribs.hasMoreElements()) {
            String sName = (String) enumContextAttribs.nextElement();
            pConfig.put(sName, oServletContext.getInitParameter(sName));
        }

        if (pConfig.size() > 0) {
            _logger.info("Using configuration items found in servlet context: " + pConfig);
        }

        // Add MountingPoint to PathTranslator
        PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath(""));

        // Try to see whether there is a system property with the location of the properties file:
        String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY);
        if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) {
            File fConfig = new File(sPropertiesFilename);
            if (fConfig.exists()) {
                _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath());
                pConfig.putAll(getProperties(fConfig));
            }
        }

        String sWebInf = oServletContext.getRealPath("WEB-INF");
        if (sWebInf != null) {
            _logger.info("Cannot find path in ServletContext for WEB-INF");
            StringBuffer sbConfigFile = new StringBuffer(sWebInf);
            if (!sbConfigFile.toString().endsWith(File.separator))
                sbConfigFile.append(File.separator);
            sbConfigFile.append(PROPERTIES_FILENAME);

            File fConfig = new File(sbConfigFile.toString());
            if (fConfig.exists()) {
                _logger.info("Updating configuration items with the items in file: " + fConfig.toString());
                pConfig.putAll(getProperties(fConfig));
            } else {
                _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME
                        + ") file found at: " + fConfig.toString());
            }
        }
        //Search for PROPERTIES_FILENAME file in servlet context classloader classpath 
        //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME]
        //if previous location didn't contain PROPERTIES_FILENAME then checking: 
        //./tomcat/common/classes/PROPERTIES_FILENAME
        URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME);
        if (urlProperties != null) {
            String sProperties = urlProperties.getFile();
            _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties);
            File fProperties = new File(sProperties);
            if (fProperties != null && fProperties.exists()) {
                _logger.info("Updating configuration items with the items in file: "
                        + fProperties.getAbsolutePath());
                pConfig.putAll(getProperties(fProperties));
            } else
                _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
        } else
            _logger.info("No optional '" + PROPERTIES_FILENAME
                    + "' configuration file found in servlet context classpath");

        if (!pConfig.containsKey("configuration.handler.filename")) {
            StringBuffer sbOAConfigFile = new StringBuffer(sWebInf);
            if (!sbOAConfigFile.toString().endsWith(File.separator))
                sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("conf");
            sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("asimba.xml");
            File fOAConfig = new File(sbOAConfigFile.toString());
            if (fOAConfig.exists()) {
                pConfig.put("configuration.handler.filename", sbOAConfigFile.toString());
                _logger.info(
                        "Setting 'configuration.handler.filename' configuration property with configuration file found at: "
                                + fOAConfig.toString());
            }
        }

        _oEngineLauncher.start(pConfig);

        _logger.info("Started Engine with OAContextListener");
    } catch (Exception e) {
        _logger.error("Can't start Engine with OAContextListener", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();
    }

}

From source file:URLUtils.java

/**
 * normalize an URL,//from www.  ja  va  2 s. co m
 * 
 * @param u,
 *          the URL to normalize
 * @return a new URL, the normalized version of the parameter, or the u URL,
 *         if something failed in the process
 */
public static URL normalize(URL u) {
    String proto = u.getProtocol().toLowerCase();
    String host = u.getHost().toLowerCase();
    int port = u.getPort();

    if (port != -1) {
        if (url_defport != null) {
            try {
                int udp;
                udp = ((Integer) url_defport.invoke(u, (Object[]) null)).intValue();
                // we have the default, skip the port part
                if (udp == port) {
                    port = -1;
                }
            } catch (InvocationTargetException ex) {
            } catch (IllegalAccessException iex) {
            }
        } else {
            switch (port) {
            case 21:
                if (proto.equals("ftp")) {
                    port = -1;
                }
                break;
            case 80:
                if (proto.equals("http")) {
                    port = -1;
                }
                break;
            case 443:
                if (proto.equals("https")) {
                    port = -1;
                }
                break;
            }
        }
    }
    try {
        URL _nu;
        if (port == -1) {
            _nu = new URL(proto, host, u.getFile());
        } else {
            _nu = new URL(proto, host, port, u.getFile());
        }
        return _nu;
    } catch (MalformedURLException ex) {
    }
    return u;
}