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:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

/**
 * Writes the master password in the file
 * @param url/*from  w  w w .  ja  v a 2 s.  c  o  m*/
 * @param configDir
 * @return
 * @throws IOException
 */
static OutputStream output(URL url, File configDir) throws IOException {
    //check for file URL
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }
        if (!f.isAbsolute()) {
            //make relative to config dir
            f = new File(configDir, f.getPath());
        }
        return new FileOutputStream(f);
    } else {
        URLConnection cx = url.openConnection();
        cx.setDoOutput(true);
        return cx.getOutputStream();
    }
}

From source file:it.marcoberri.mbmeteo.action.Commons.java

/**
 *
 * @param fileName/*from ww w  .  j av  a  2s.co m*/
 * @param log
 * @return
 */
protected static String getJsFromFile(String fileName, Logger log) {
    try {
        final URL main = log.getClass().getProtectionDomain().getCodeSource().getLocation();
        final String path = URLDecoder.decode(main.getPath(), "utf-8");
        final String webInfFolderPosition = new File(path).getPath();
        final String webInfFolder = webInfFolderPosition.substring(0, webInfFolderPosition.indexOf("classes"));
        return FileUtils.readFileToString(new File(webInfFolder + File.separator + fileName));
    } catch (IOException ex) {
        log.error(ex);
    }
    return null;
}

From source file:de.pdark.dsmp.RequestHandler.java

public static File getCacheFile(URL url, File root) {
    root = new File(root, url.getHost());
    if (url.getPort() != -1 && url.getPort() != 80)
        root = new File(root, String.valueOf(url.getPort()));
    File f = new File(root, url.getPath());
    return f;/*  w  ww  .  ja  v  a  2 s.c  o m*/
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

/**
 * Get the path of the file in the resources folder 
 * //from  w ww.j  a  va 2  s  . c o  m
 * @param fileName
 * @return String path
 */
public static String getFilePathFromResources(String fileName) {
    String path = null;
    try {
        URL url = DocumentProcessorUtil.class.getClassLoader().getResource(fileName);
        path = url.getPath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return path;
}

From source file:org.lightcouch.CouchDbUtil.java

/**
 * List directory contents for a resource folder. Not recursive. This is
 * basically a brute-force implementation. Works for regular files and also
 * JARs./*from   w w w  . j a  v  a 2s . co m*/
 * 
 * @author Greg Briggs
 * @param clazz
 *            Any java class that lives in the same place as the resources
 *            you want.
 * @param path
 *            Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 */
public static List<String> listResources(String path) {
    String fileURL = null;
    try {
        URL entry = Platform.getBundle("org.lightcouch").getEntry(path);
        File file = null;
        if (entry != null) {
            fileURL = FileLocator.toFileURL(entry).getPath();
            // remove leading slash from absolute path when on windows
            if (OSValidator.isWindows())
                fileURL = fileURL.substring(1, fileURL.length());
            file = new File(fileURL);
        }
        URL dirURL = file.toPath().toUri().toURL();

        if (dirURL != null && dirURL.getProtocol().equals("file")) {
            return Arrays.asList(new File(dirURL.toURI()).list());
        }
        if (dirURL != null && dirURL.getProtocol().equals("jar")) {
            String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
            JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
            Enumeration<JarEntry> entries = jar.entries();
            Set<String> result = new HashSet<String>();
            while (entries.hasMoreElements()) {
                String name = entries.nextElement().getName();
                if (name.startsWith(path)) {
                    String entry1 = name.substring(path.length());
                    int checkSubdir = entry1.indexOf("/");
                    if (checkSubdir >= 0) {
                        entry1 = entry1.substring(0, checkSubdir);
                    }
                    if (entry1.length() > 0) {
                        result.add(entry1);
                    }
                }
            }
            return new ArrayList<String>(result);
        }
        return null;
    } catch (Exception e) {
        throw new CouchDbException("fileURL: " + fileURL, e);
    }
}

From source file:com.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java

private static String unpackJar(URL resource) {
    String file = resource.getPath();
    if (file.contains(".jar!/")) {
        s_logger.info("Unpacking zip file located within a jar file: {}", resource);
        String jarFileName = StringUtils.substringBefore(file, "!/");
        if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(5);
            if (SystemUtils.IS_OS_WINDOWS) {
                jarFileName = StringUtils.stripStart(jarFileName, "/");
            }//w  w w  . ja va2  s. c o m
        } else if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(6);
        }
        jarFileName = StringUtils.replace(jarFileName, "%20", " ");
        String innerFileName = StringUtils.substringAfter(file, "!/");
        innerFileName = StringUtils.replace(innerFileName, "%20", " ");
        s_logger.info("Unpacking zip file found jar file: {}", jarFileName);
        s_logger.info("Unpacking zip file found zip file: {}", innerFileName);
        try {
            JarFile jar = new JarFile(jarFileName);
            JarEntry jarEntry = jar.getJarEntry(innerFileName);
            try (InputStream in = jar.getInputStream(jarEntry)) {
                File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip");
                tempFile.deleteOnExit();
                try (OutputStream out = new FileOutputStream(tempFile)) {
                    IOUtils.copy(in, out);
                }
                file = tempFile.getCanonicalPath();
            }
        } catch (IOException ex) {
            throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex);
        }
        s_logger.debug("Unpacking zip file extracted to: {}", file);
    }
    return file;
}

From source file:co.cask.common.security.server.ExternalAuthenticationServerTestBase.java

/**
 * LDAP server and related handler configurations.
 *//*from  www .  ja  va 2 s.c o m*/
private static SecurityConfiguration getSecurityConfiguration(SecurityConfiguration cConf) {
    String configBase = Constants.AUTH_HANDLER_CONFIG_BASE;

    // Use random port for testing
    cConf.setInt(Constants.AUTH_SERVER_BIND_PORT, Networks.getRandomPort());
    cConf.setInt(Constants.AuthenticationServer.SSL_PORT, Networks.getRandomPort());

    cConf.set(Constants.AUTH_HANDLER_CLASS, LDAPAuthenticationHandler.class.getName());
    cConf.set(Constants.LOGIN_MODULE_CLASS_NAME, LDAPLoginModule.class.getName());
    cConf.set(configBase.concat("debug"), "true");
    cConf.set(configBase.concat("hostname"), "localhost");
    cConf.set(configBase.concat("port"), Integer.toString(ldapPort));
    cConf.set(configBase.concat("userBaseDn"), "dc=example,dc=com");
    cConf.set(configBase.concat("userRdnAttribute"), "cn");
    cConf.set(configBase.concat("userObjectClass"), "inetorgperson");

    URL keytabUrl = ExternalAuthenticationServerTestBase.class.getClassLoader().getResource("test.keytab");
    Assert.assertNotNull(keytabUrl);
    cConf.set(Constants.CFG_CDAP_MASTER_KRB_KEYTAB_PATH, keytabUrl.getPath());
    cConf.set(Constants.CFG_CDAP_MASTER_KRB_PRINCIPAL, "test_principal");
    return cConf;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * FUNKTIONIERT NICHT, HOST WIRD NICHT UEBERNOMMEN
 * Clones a http method and sets a new url
 * @param src/*from   w  w w  .  j  ava2s.  co  m*/
 * @param url
 * @return
 */
private static HttpMethod clone(HttpMethod src, URL url) {
    HttpMethod trg = HttpMethodCloner.clone(src);
    HostConfiguration trgConfig = trg.getHostConfiguration();
    trgConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());
    trg.setPath(url.getPath());
    trg.setQueryString(url.getQuery());

    return trg;
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * /*from  w  ww . j  av  a 2  s .  c o  m*/
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception// w ww  .j  av a 2  s  . c  om
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}