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.izforge.izpack.panels.licence.LicenceLoader.java

/**
 * Loads the licence into a string with the specified {@code encoding}.
 *
 * @param encoding The target character encoding.
 * @return A string representation of the licence in the specified encoding.
 * @throws ResourceException If the licence could not be found or if file
 *      content could not be converted to the specified {@code encoding}.
 */// w  w w  .  j  a  v  a  2  s  .c  o  m
String asString(final String encoding) throws ResourceException {
    URL url = asURL();
    InputStream in = null;

    try {
        in = url.openStream();
        return IOUtils.toString(in, Charsets.toCharset(encoding));
    } catch (IOException e) {
        throw new ResourceNotFoundException("Cannot convert license document from resource " + url.getFile()
                + " to text: " + e.getMessage());

    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:energy.usef.time.Config.java

/***
 * Reads the default properties from the classpath. Used for tests and also used to merge properties from a file.
 *
 * @return - The read properties, named localProperties within the scope of the method
 * @throws java.io.IOException/*from ww w. j  a v a2s  .  com*/
 */
public Properties readDefaultProperties() throws IOException {
    Properties localProperties = new Properties();
    URL defaultConfigURL = Config.class.getClassLoader().getResource(CONFIG_FILE_NAME);
    if (defaultConfigURL != null) {
        try (InputStream input = this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE_NAME)) {
            LOGGER.info("Reading default properties from {}", defaultConfigURL.getFile());
            localProperties.load(input);
        }
    } else {
        throw new TechnicalException("Default properties file " + CONFIG_FILE_NAME + " could not be found");
    }
    return localProperties;
}

From source file:com.viadeo.kasper.exposition.http.jetty.resource.KasperDocResourceTest.java

/**
 * Main run test method//w  w  w. j a  v a 2s .c  om
 * 
 * Scans all available json files, make the request to a standalone HTTP server and compare
 * expected and retrieved results
 * @throws URISyntaxException 
 * 
 * @throws Exception
 */
@Test
public void test() throws IOException, JSONException, URISyntaxException {

    // Traverse available json responses ------------------------------------
    final Predicate<String> filter = new FilterBuilder().include(".*\\.json");
    final Reflections reflections = new Reflections(
            new ConfigurationBuilder().filterInputsBy(filter).setScanners(new ResourcesScanner())
                    .setUrls(Arrays.asList(ClasspathHelper.forClass(this.getClass()))));

    final Set<String> resolved = reflections.getResources(Pattern.compile(".*"));

    // Execute against Kasper documentation -------------------------------
    boolean failed = false;
    for (final String jsonFilename : resolved) {
        LOGGER.info("** Test response file " + jsonFilename);

        final String json = getJson(jsonFilename);

        final String path = jsonFilename.replaceAll("json/", "").replaceAll("-", "/").replaceAll("\\.json", "");

        final WebResource webResource = resource();
        final String responseMsg = webResource.path("/" + path).get(String.class);

        try {

            assertJsonEquals(responseMsg, json);

        } catch (final JSONException e) {
            LOGGER.info("\t--> ERROR");
            throw e;

        } catch (final AssertionError e) {
            if (!UPDATE_TESTS) {
                LOGGER.debug("*** RETURNED RESULT :");
                LOGGER.debug(new JSONObject(responseMsg).toString(2));
                LOGGER.info("\t--> ERROR");
                failed = true;
            }
        }

        if (UPDATE_TESTS) {
            final URL url = ClassLoader.getSystemResource(jsonFilename);
            final String filename = url.getFile().replaceAll("target/test-classes", "src/test/resources");
            LOGGER.info("\t--> SAVE to " + filename);
            final File file = new File(filename);
            final FileOutputStream fos = new FileOutputStream(file);
            fos.write(new JSONObject(responseMsg).toString(2).getBytes(Charsets.UTF_8));
            fos.close();
        }

        LOGGER.info("\t--> OK");
    }

    if (failed) {
        fail();
    }
}

From source file:fr.gael.dhus.datastore.scanner.ScannerFactory.java

private String showPublicURL(URL url) {
    String protocol = url.getProtocol();
    String host = url.getHost();/*from   w w  w  . ja v  a  2s.  co m*/
    int port = url.getPort();
    String path = url.getFile();
    if (protocol == null)
        protocol = "";
    else
        protocol += "://";

    String s_port = "";
    if (port != -1)
        s_port = ":" + port;

    return protocol + host + s_port + path;
}

From source file:fr.gael.dhus.server.http.SolrWebapp.java

@Override
public void configure(String dest_folder) throws IOException {
    String configurationFolder = "fr/gael/dhus/server/http/solr/webapp";
    URL u = Thread.currentThread().getContextClassLoader().getResource(configurationFolder);
    if (u != null && "jar".equals(u.getProtocol())) {
        extractJarFolder(u, configurationFolder, dest_folder);
    } else if (u != null) {
        File webAppFolder = new File(dest_folder);
        copyFolder(new File(u.getFile()), webAppFolder);
    }/*w  w  w .  j ava2  s .co m*/
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.webproject.CreateNewAwsJavaWebProjectRunnable.java

private void addSessionManagerConfigurationFiles(IProject project) throws IOException, CoreException {
    Bundle bundle = ElasticBeanstalkPlugin.getDefault().getBundle();
    URL url = FileLocator.resolve(bundle.getEntry("/"));
    IPath templateRoot = new Path(url.getFile(), "templates");

    FileUtils.copyDirectory(templateRoot.append("dynamodb-session-manager").toFile(),
            project.getLocation().toFile(), new SvnMetadataFilter());

    // Add the user's credentials to context.xml
    File localContextXml = project.getLocation().append(".ebextensions").append("context.xml").toFile();
    AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountManager()
            .getAccountInfo(dataModel.getAccountId());
    String contextContents = FileUtils.readFileToString(localContextXml);
    contextContents = contextContents.replace("{ACCESS_KEY}", accountInfo.getAccessKey());
    contextContents = contextContents.replace("{SECRET_KEY}", accountInfo.getSecretKey());
    FileUtils.writeStringToFile(localContextXml, contextContents);

    project.refreshLocal(IResource.DEPTH_INFINITE, null);

    // Update the J2EE Deployment Assembly by creating a link from the '/.ebextensions'
    // folder to the '/WEB-INF/.ebextensions' folder in the web assembly mapping for WTP
    IVirtualComponent rootComponent = ComponentCore.createComponent(project);
    IVirtualFolder rootFolder = rootComponent.getRootFolder();
    try {/*from   w w  w. j  av a2s.co m*/
        Path source = new Path("/.ebextensions");
        Path target = new Path("/WEB-INF/.ebextensions");
        IVirtualFolder subFolder = rootFolder.getFolder(target);
        subFolder.createLink(source, 0, null);
    } catch (CoreException ce) {
        String message = "Unable to configure deployment assembly to map .ebextension directory";
        AwsToolkitCore.getDefault().logException(message, ce);
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private File downloadJar(URL url) throws IOException {
    String filename = url.getFile();
    int lastSlashIndex = filename.lastIndexOf('/');
    if (lastSlashIndex != -1) {
        filename = filename.substring(lastSlashIndex + 1);
    }/*w w w  .  j  av  a2 s  . co m*/
    File outputJar = new File(localCacheDirectory, filename);
    FileOutputStream output = new FileOutputStream(outputJar);
    URLConnection connection = url.openConnection();
    addSslConnection(connection);
    InputStream input = connection.getInputStream();
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = input.read(buffer);
    while (bytesRead != -1) {
        output.write(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);
    }
    input.close();
    output.close();
    CHECKED.remove(url);
    return outputJar;
}

From source file:com.intellijob.BaseTester.java

/**
 * Reload collection skill_categories.//www  . j  a  v a 2 s .c o  m
 * <p>
 * Drop collection if exist, create a new collection and load data.
 * Read data from skill_categories.json
 *
 * @throws IOException exception.
 */
protected void reloadCollectionSkillCategories() throws Exception {
    skillCategoryRepository.deleteAll();
    URL skillCategoriesURL = Thread.currentThread().getContextClassLoader()
            .getResource("imports/skill_categories.json");

    TypeReference<List<SkillCategory>> typeRef = new TypeReference<List<SkillCategory>>() {
    };
    List<SkillCategory> categories = new ObjectMapper().readValue(new File(skillCategoriesURL.getFile()),
            typeRef);
    skillCategoryRepository.save(categories);
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.webproject.CreateNewAwsJavaWebProjectRunnable.java

private void addTemplateFiles(IProject project) throws IOException, CoreException {
    final String CREDENTIAL_PROFILE_PLACEHOLDER = "{CREDENTIAL_PROFILE}";
    Bundle bundle = ElasticBeanstalkPlugin.getDefault().getBundle();
    URL url = FileLocator.resolve(bundle.getEntry("/"));
    IPath templateRoot = new Path(url.getFile(), "templates");

    AccountInfo currentAccountInfo = AwsToolkitCore.getDefault().getAccountManager()
            .getAccountInfo(dataModel.getAccountId());

    switch (dataModel.getProjectTemplate()) {
    case WORKER://  ww  w  .  ja  va  2s  . c o m
        File workerServlet = templateRoot.append("worker/src/WorkerServlet.java").toFile();
        String workerServletContent = replaceStringInFile(workerServlet, CREDENTIAL_PROFILE_PLACEHOLDER,
                currentAccountInfo.getAccountName());

        FileUtils.copyDirectory(templateRoot.append("worker").toFile(), project.getLocation().toFile(),
                new SvnMetadataFilter());
        FileUtils.writeStringToFile(workerServlet, workerServletContent);
        break;

    case DEFAULT:
        File indexJsp = templateRoot.append("basic/WebContent/index.jsp").toFile();
        String indexJspContent = replaceStringInFile(indexJsp, CREDENTIAL_PROFILE_PLACEHOLDER,
                currentAccountInfo.getAccountName());

        FileUtils.copyDirectory(templateRoot.append("basic").toFile(), project.getLocation().toFile(),
                new SvnMetadataFilter());

        FileUtils.writeStringToFile(indexJsp, indexJspContent);
        break;

    default:
        throw new IllegalStateException("Unknown project template: " + dataModel.getProjectTemplate());
    }

    project.refreshLocal(IResource.DEPTH_INFINITE, null);
}