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.thoughtworks.go.server.web.UrlRewriterIntegrationTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    ServletHelper.init();//ww  w . j  a  va 2s  .  c om
    httpUtil = new HttpTestUtil(new HttpTestUtil.ContextCustomizer() {
        public void customize(WebAppContext ctx) throws Exception {
            wac = mock(WebApplicationContext.class);
            ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

            URL resource = getClass().getClassLoader().getResource("WEB-INF/urlrewrite.xml");
            if (resource == null) {
                throw new RuntimeException("Cannot load WEB-INF/urlrewrite.xml");
            }

            ctx.setBaseResource(Resource.newResource(new File(resource.getFile()).getParent()));
            ctx.addFilter(UrlRewriteFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST))
                    .setInitParameter("confPath", "/urlrewrite.xml");
            ctx.addServlet(HttpTestUtil.EchoServlet.class, "/*");
        }
    });
    httpUtil.httpConnector(HTTP);
    httpUtil.httpsConnector(HTTPS);
    when(wac.getBean("serverConfigService")).thenReturn(new BaseUrlProvider() {
        public boolean hasAnyUrlConfigured() {
            return useConfiguredUrls;
        }

        public String siteUrlFor(String url, boolean forceSsl) throws URISyntaxException {
            ServerSiteUrlConfig siteUrl = forceSsl ? new ServerSiteUrlConfig(HTTPS_SITE_URL)
                    : new ServerSiteUrlConfig(HTTP_SITE_URL);
            return siteUrl.siteUrlFor(url);
        }
    });

    httpUtil.start();
    originalSslPort = System.getProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT);
    System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, String.valueOf(HTTPS));

    FeatureToggleService featureToggleService = mock(FeatureToggleService.class);
    when(featureToggleService.isToggleOn(anyString())).thenReturn(true);
    Toggles.initializeWith(featureToggleService);
}

From source file:org.jboss.as.test.integration.security.loginmodules.usersroles.UsersRolesLoginModuleTestCase8.java

protected static void createSecurityDomains() throws Exception {

    final ModelControllerClient client = ModelControllerClient.Factory
            .create(InetAddress.getByName("localhost"), 9999);
    List<ModelNode> updates = new ArrayList<ModelNode>();

    ModelNode op1 = new ModelNode();

    op1.get(OP).set(ADD);/*from w w  w .ja va2s .  com*/
    op1.get(OP_ADDR).add(SUBSYSTEM, "security");
    op1.get(OP_ADDR).add(SECURITY_DOMAIN, "prepare-login-module");
    updates.add(op1);

    op1 = new ModelNode();
    op1.get(OP).set(ADD);
    op1.get(OP_ADDR).add(SUBSYSTEM, "security");
    op1.get(OP_ADDR).add(SECURITY_DOMAIN, "prepare-login-module");
    op1.get(OP_ADDR).add(Constants.AUTHENTICATION, Constants.CLASSIC);

    ModelNode loginModule = op1.get(Constants.LOGIN_MODULES).add();
    loginModule.get(ModelDescriptionConstants.CODE).set(UsersRolesLoginModule.class.getName());
    loginModule.get(FLAG).set("optional");
    op1.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);

    updates.add(op1);

    String securityDomain = "users-roles-login-module";
    ModelNode op2 = new ModelNode();
    op2.get(OP).set(ADD);
    op2.get(OP_ADDR).add(SUBSYSTEM, "security");
    op2.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    updates.add(op2);

    op2 = new ModelNode();
    op2.get(OP).set(ADD);
    op2.get(OP_ADDR).add(SUBSYSTEM, "security");
    op2.get(OP_ADDR).add(SECURITY_DOMAIN, securityDomain);
    op2.get(OP_ADDR).add(Constants.AUTHENTICATION, Constants.CLASSIC);

    loginModule = op2.get(Constants.LOGIN_MODULES).add();
    loginModule.get(ModelDescriptionConstants.CODE).set(UsersRolesLoginModule.class.getName());
    loginModule.get(FLAG).set("required");
    op2.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);

    URL usersProp = Utils.getResource("users-roles-login-module.war/users.properties");
    URL rolesProp = Utils.getResource("users-roles-login-module.war/roles.properties");
    ModelNode moduleOptions = loginModule.get("module-options");

    Map<String, String> moduleOptionsMap = classModuleOptionsMap.get(UsersRolesLoginModuleTestCase8.class);

    moduleOptions.get("usersProperties").set(usersProp.getFile());
    moduleOptions.get("rolesProperties").set(rolesProp.getFile());
    for (Map.Entry<String, String> entry : moduleOptionsMap.entrySet()) {
        moduleOptions.get(entry.getKey()).set(entry.getValue());
    }

    updates.add(op2);

    applyUpdates(updates, client);

}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

public static OutputStream downloadFile(String url, String downloadFolder) {
    InputStream input = null;/*from   w ww  . ja  v a 2  s. c  om*/
    OutputStream output = null;
    try {
        URL urlFile = new URL(url);
        String filename = urlFile.getFile();
        if (filename != null) {
            int pos = filename.lastIndexOf('/');
            if (pos != -1) {
                filename = filename.substring(pos + 1);
            }
        } else {
            int pos = url.lastIndexOf('/');
            if (pos != -1) {
                filename = url.substring(pos + 1);
            }
        }
        input = urlFile.openStream();
        byte[] bytes = IOUtils.toByteArray(input);
        output = new FileOutputStream(new File(downloadFolder + "/" + filename)); //$NON-NLS-1$
        IOUtils.write(bytes, output);
        return output;
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return null;
}

From source file:com.zimbra.cs.servlet.util.AuthUtil.java

public static String getRedirectURL(HttpServletRequest req, Server server, boolean isAdminRequest,
        boolean relative) throws ServiceException, MalformedURLException {
    String redirectUrl;//from  ww w.  ja  v a 2  s.c  o m
    if (isAdminRequest) {
        redirectUrl = getAdminURL(server, relative);
    } else {
        redirectUrl = getMailURL(server, relative);
    }
    if (!relative) {
        URL url = new URL(redirectUrl);

        // replace host of the URL to the host the request was sent to
        String reqHost = req.getServerName();
        String host = url.getHost();

        if (!reqHost.equalsIgnoreCase(host)) {
            URL destUrl = new URL(url.getProtocol(), reqHost, url.getPort(), url.getFile());
            redirectUrl = destUrl.toString();
        }
    }
    return redirectUrl;
}

From source file:com.safi.workshop.application.ChooseSafiServerWorkspaceData.java

/**
 * The workspace data is stored in the well known file pointed to by the result of this
 * method.//  w w  w .  j ava2s  .  c  o  m
 * 
 * @param create
 *          If the directory and file does not exist this parameter controls whether it
 *          will be created.
 * @return An url to the file and null if it does not exist or could not be created.
 */
private static URL getPersistenceUrl(URL baseUrl, boolean create) {
    if (baseUrl == null) {
        return null;
    }

    try {
        // make sure the directory exists
        URL url = new URL(baseUrl, PERS_FOLDER);
        File dir = new File(url.getFile());
        if (!dir.exists() && (!create || !dir.mkdir())) {
            return null;
        }

        // make sure the file exists
        url = new URL(dir.toURL(), PERS_FILENAME);
        File persFile = new File(url.getFile());
        if (!persFile.exists() && (!create || !persFile.createNewFile())) {
            return null;
        }

        return persFile.toURL();
    } catch (IOException e) {
        // cannot log because instance area has not been set
        return null;
    }
}

From source file:de.alpharogroup.resourcebundle.properties.PropertiesFileExtensions.java

/**
 * Load the properties file from the given class object. The filename from the properties file
 * is the same as the simple name from the class object and it looks at the same path as the
 * given class object. If locale is not null than the language will be added to the filename
 * from the properties file.//from ww w.  j a  va 2 s  .c om
 *
 * @param clazz
 *            the clazz
 * @param locale
 *            the locale
 * @return the properties
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Properties loadPropertiesFromClassObject(final Class<?> clazz, final Locale locale)
        throws IOException {
    if (null == clazz) {
        throw new IllegalArgumentException("Class object must not be null!!!");
    }
    StringBuilder propertiesName = new StringBuilder();
    Properties properties = null;
    String language = null;
    String filename = null;
    String pathAndFilename = null;
    File propertiesFile = null;
    String absoluteFilename = null;
    final String packagePath = PackageExtensions.getPackagePathWithSlash(clazz);
    final List<String> missedFiles = new ArrayList<>();
    if (null != locale) {
        propertiesName.append(clazz.getSimpleName());
        language = locale.getLanguage();
        if ((null != language) && !language.isEmpty()) {
            propertiesName.append("_").append(language);
        }

        final String country = locale.getCountry();
        if ((null != country) && !country.isEmpty()) {
            propertiesName.append("_").append(country);
        }
        propertiesName.append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }

        if ((null != propertiesFile) && propertiesFile.exists()) {
            properties = PropertiesFileExtensions.loadProperties(pathAndFilename);
        } else {
            propertiesName = new StringBuilder();
            if (null != locale) {
                propertiesName.append(clazz.getSimpleName());
                language = locale.getLanguage();
                if ((null != language) && !language.isEmpty()) {
                    propertiesName.append("_").append(language);
                }
                propertiesName.append(FileExtension.PROPERTIES.getExtension());
                filename = propertiesName.toString().trim();
                pathAndFilename = packagePath + filename;
                url = ClassExtensions.getResource(clazz, filename);

                if (url != null) {
                    absoluteFilename = url.getFile();
                } else {
                    missedFiles.add("File with filename '" + filename + "' does not exists.");
                }
                if (null != absoluteFilename) {
                    propertiesFile = new File(absoluteFilename);
                }
                if ((null != propertiesFile) && propertiesFile.exists()) {
                    properties = PropertiesFileExtensions.loadProperties(pathAndFilename);
                }
            }
        }
    }

    if (null == properties) {
        propertiesName = new StringBuilder();
        propertiesName.append(clazz.getSimpleName()).append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        final URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            properties = PropertiesFileExtensions.loadProperties(pathAndFilename);
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }
        if ((null != propertiesFile) && propertiesFile.exists()) {
            properties = PropertiesFileExtensions.loadProperties(pathAndFilename);
        }
    }
    return properties;
}

From source file:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Displays the file specified by the supplied URL. If the URL specifies a
 * remote file, the file will be downloaded first. The thread will block
 * while the download occurs.//from   ww  w.  ja  v a2  s .  c om
 * 
 * @param fileURL
 *            A URL pointing to the file of interest
 * @param description
 *            A description of the file
 * @param desktop
 *            A reference to the AWT Desktop
 * @throws Exception
 *             If an unrecoverable error occurred while downloading or
 *             displaying the file.
 */
public static void displayFileFromURL(URL fileURL, String description, Desktop desktop) throws Exception {
    String fileName = fileURL.getFile();

    if (fileName.toLowerCase().endsWith(".rtf")) {
        File file = Utils.saveURLToTempFile(fileURL, "Intkey", 30000);
        String rtfSource = FileUtils.readFileToString(file, "cp1252"); // RTF
                                                                       // must
                                                                       // always
                                                                       // be
                                                                       // read
                                                                       // as
                                                                       // windows
                                                                       // cp1252
                                                                       // encoding
        RtfReportDisplayDialog dlg = new RtfReportDisplayDialog(getMainFrame(), new SimpleRtfEditorKit(null),
                rtfSource, description);
        ((SingleFrameApplication) Application.getInstance()).show(dlg);
    } else if (fileName.toLowerCase().endsWith(".html")) {
        if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
            throw new UnsupportedOperationException("Desktop is null or browse not supported");
        }
        desktop.browse(fileURL.toURI());
    } else if (fileName.toLowerCase().endsWith(".ink")) {
        File file = Utils.saveURLToTempFile(fileURL, "Intkey", 30000);
        Utils.launchIntkeyInSeparateProcess(System.getProperty("user.dir"), file.getAbsolutePath());
    } else if (fileName.toLowerCase().endsWith(".wav")) {
        AudioPlayer.playClip(fileURL);
    } else {
        // Open a http link that does not point to a .rtf, .ink or .wav in
        // the browser
        if (fileURL.getProtocol().equalsIgnoreCase("http")) {
            if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) {
                throw new UnsupportedOperationException("Desktop is null or browse not supported");
            }
            desktop.browse(fileURL.toURI());
        } else {
            if (desktop == null || !desktop.isSupported(Desktop.Action.OPEN)) {
                throw new UnsupportedOperationException("Desktop is null or open not supported");
            }
            File file = Utils.saveURLToTempFile(fileURL, "Intkey", 30000);
            desktop.open(file);
        }
    }
}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) {

    File jaasConfigFile = null;/* w w  w. j  ava2s. c o m*/
    final URL jaasConfigURL = SecurityUtil.class.getClassLoader().getResource(fileNameFromClasspath);
    if (jaasConfigURL != null) {
        try {
            jaasConfigFile = new File(URLDecoder.decode(jaasConfigURL.getFile(), "UTF-8"));
        } catch (final UnsupportedEncodingException e) {
            return null;
        }

        if (jaasConfigFile.exists() && jaasConfigFile.canRead()) {
            return jaasConfigFile;
        } else {
            log.error("Cannot read from {}, maybe the file does not exists? ",
                    jaasConfigFile.getAbsolutePath());
        }

    } else {
        log.error("Failed to load " + fileNameFromClasspath);
    }

    return null;

}

From source file:com.tesora.dve.common.PEFileUtils.java

private static String getCanonicalPathFromURL(final URL url) throws PEException {
    File resourceFile;/*from w w w  .ja  va2s.  c  o m*/
    try {
        final String os = System.getProperty("os.name");
        if (StringUtils.containsIgnoreCase(os, "win")) {
            return url.getFile();
        }

        resourceFile = new File(url.toURI());
    } catch (final URISyntaxException e) {
        resourceFile = new File(url.getPath());
    }

    try {
        return resourceFile.getCanonicalPath();
    } catch (final IOException e) {
        throw new PEException("Could not canonicalize the path '" + resourceFile.getAbsolutePath() + "'", e);
    }
}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static boolean setSystemPropertyToAbsoluteFilePathFromClassPath(final String property,
        final String fileNameFromClasspath) {
    if (System.getProperty(property) == null) {
        File jaasConfigFile = null;
        final URL jaasConfigURL = SecurityUtil.class.getClassLoader().getResource(fileNameFromClasspath);
        if (jaasConfigURL != null) {
            try {
                jaasConfigFile = new File(URLDecoder.decode(jaasConfigURL.getFile(), "UTF-8"));
            } catch (final UnsupportedEncodingException e) {
                return false;
            }/*from www .j  av  a  2 s.c o  m*/

            if (jaasConfigFile.exists() && jaasConfigFile.canRead()) {
                System.setProperty(property, jaasConfigFile.getAbsolutePath());

                log.debug("Load " + fileNameFromClasspath + " from {} ", jaasConfigFile.getAbsolutePath());
                return true;
            } else {
                log.error("Cannot read from {}, maybe the file does not exists? ",
                        jaasConfigFile.getAbsolutePath());
            }

        } else {
            log.error("Failed to load " + fileNameFromClasspath);
        }
    } else {
        log.warn("Property " + property + " already set to " + System.getProperty(property));
    }

    return false;
}