Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:org.squidy.designer.model.NodeShape.java

/**
 * @param file/*from   w ww.  j  a va2  s . com*/
 * @param content
 */
public void persistCode(File file, String newName, String content) {

    // Flag if something failed while persisting node.
    boolean failed = false;

    try {
        FileWriter writer = new FileWriter(file);
        writer.write(content);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        failed = true;
        publishFailure(e);
    }

    Class<? extends Node> valveType;
    try {
        Node node = (Node) getProcessable();

        valveType = ReflectionUtil.<Node>loadClass(node.getClass().getPackage().getName() + "." + newName);

        node = ReflectionUtil.createInstance(valveType);

        failed = rebuildWithValve(node);
    } catch (Exception e) {
        failed = true;
        publishFailure(e);
    }

    // Set url to new source code.
    try {
        sourceCode.setSourceCodeURL(file.toURL());
    } catch (MalformedURLException e) {
        failed = true;
        publishFailure(e);
    }

    // Resolve failure if everything went fine.
    if (!failed) {
        resolveFailure();
    }
}

From source file:KeyNavigateTest.java

private MediaContainer loadSoundFile(String szFile) {
    try {//from  w w w.j a  v a2 s .  c  om
        File file = new File(System.getProperty("user.dir"));
        URL url = file.toURL();

        URL soundUrl = new URL(url, szFile);
        return new MediaContainer(soundUrl);
    } catch (Exception e) {
        System.err.println("Error could not load sound file: " + e);
        System.exit(-1);
    }

    return null;
}

From source file:org.smigo.SeleniumTest.java

License:asdf

@Test(enabled = true)
public void uploadFromKitchenGardenAidTest() throws InterruptedException, IOException {
    String speciesPath = "resources/species.xml";
    InputStream stream = PlantList.class.getResourceAsStream("/" + speciesPath);
    PlantList.initialize(stream);/*w w w .j  av  a  2  s .co  m*/

    File htmlFile = Files.createTempFile("upload", ".html").toFile();
    PrintWriter printWriter = new PrintWriter(htmlFile);
    printWriter.print(
            "<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n<meta charset=\"UTF-8\">\n</head>\n<body>\n<form name=\"uploadform\" method=\"post\" action=\""
                    + HOST_URL + "/plant/upload\">\n");
    int counter = 0;
    for (Plant p : PlantList.getResources().getPlants()) {
        if (p.getImage() != null) {
            printWriter.print("<input type=\"hidden\" name=\"plants[" + counter + "].speciesId\" value=\""
                    + p.getId() + "\"/>");
            printWriter.print("<input type=\"hidden\" name=\"plants[" + counter + "].year\" value=\"2002\"/>");
            printWriter.print("<input type=\"hidden\" name=\"plants[" + counter + "].x\" value=\"0\"/>");
            printWriter.print(
                    "<input type=\"hidden\" name=\"plants[" + counter + "].y\" value=\"" + counter + "\"/>");
            ++counter;
        }
    }

    printWriter.print(
            "</form>\n<h1>Loading...</h1>\n<script>\nwindow.onload = function () {\nconsole.log(\'a\', document.getElementsByTagName(\'form\'));\ndocument.uploadform.submit();\n}\n</script>\n</body>\n</html>");
    printWriter.flush();
    printWriter.close();
    d.navigate().to(htmlFile.toURL());
    final List<WebElement> plant = d.findElements(By.className("plant"));
    Assert.assertEquals(plant.size(), 127);

}

From source file:org.apache.axis2.deployment.DeploymentEngine.java

public void loadRepository(String repoDir) throws DeploymentException {
    File axisRepo = new File(repoDir);
    if (!axisRepo.exists()) {
        throw new DeploymentException(Messages.getMessage("cannotfindrepo", repoDir));
    }//from  w w w.ja va2  s .c o  m
    setDeploymentFeatures();
    prepareRepository(repoDir);
    // setting the CLs
    setClassLoaders(repoDir);
    repoListener = new RepositoryListener(this, false);
    org.apache.axis2.util.Utils.calculateDefaultModuleVersion(axisConfig.getModules(), axisConfig);
    try {
        try {
            axisConfig.setRepository(axisRepo.toURL());
        } catch (MalformedURLException e) {
            log.info(e.getMessage());
        }
        axisConfig.validateSystemPredefinedPhases();
    } catch (AxisFault axisFault) {
        throw new DeploymentException(axisFault);
    }
}

From source file:org.ops4j.pax.scanner.dir.internal.DirScanner.java

/**
 * Reads the bundles from the file specified by the urlSpec.
 * {@inheritDoc}//ww w.j  a va  2  s.  co m
 */
public List<ScannedBundle> scan(final ProvisionSpec provisionSpec)
        throws MalformedSpecificationException, ScannerException {
    NullArgumentException.validateNotNull(provisionSpec, "Provision spec");

    LOGGER.debug("Scanning [" + provisionSpec.getPath() + "]");
    final ScannerConfiguration config = createConfiguration();
    final Pattern filter = provisionSpec.getFilterPattern();
    final String spec = provisionSpec.getPath();
    final Integer defaultStartLevel = getDefaultStartLevel(provisionSpec, config);
    final Boolean defaultStart = getDefaultStart(provisionSpec, config);
    final Boolean defaultUpdate = getDefaultUpdate(provisionSpec, config);
    // try out an url
    LOGGER.trace("Searching for [" + spec + "]");
    URL url = null;
    try {
        url = new URL(spec);
    } catch (MalformedURLException ignore) {
        // ignore this as the spec may be resolved other way
        LOGGER.trace("Specification is not a valid url: " + ignore.getMessage() + ". Continue discovery...");
    }
    File file = null;
    if (url != null && "file".equals(url.getProtocol()))
    // if we have an url and it's a file url
    {
        try {
            final URI uri = new URI(url.toExternalForm().replaceAll(" ", "%20"));
            file = new File(uri);
        } catch (Exception ignore) {
            // ignore this as the spec may be resolved other way
            LOGGER.trace("Specification is not a valid file url: " + ignore.getMessage()
                    + ". Continue discovery...");
        }
    } else
    // if we don't have an url then let's try out a direct file
    {
        file = new File(spec);
    }
    if (file != null && file.exists())
    // if we have a directory
    {
        if (file.isDirectory()) {
            try {
                return list(new DirectoryLister(file, filter), defaultStartLevel, defaultStart, defaultUpdate);
            } catch (MalformedURLException e) {
                throw new MalformedSpecificationException(e);
            }
        } else {
            LOGGER.trace("Specification is not a directory. Continue discovery...");
        }
    } else {
        LOGGER.trace("Specification is not a valid file. Continue discovery...");
    }
    // on this point we may have a zip
    try {
        ZipFile zip = null;
        URL baseUrl = null;
        if (file != null && file.exists())
        // try out a zip from the file we have
        {
            zip = new ZipFile(file);
            baseUrl = file.toURL();
        } else if (url != null) {
            zip = new ZipFile(url.toExternalForm());
            baseUrl = url;
        }
        if (zip != null && baseUrl != null) {
            try {
                return list(new ZipLister(baseUrl, zip.entries(), filter), defaultStartLevel, defaultStart,
                        defaultUpdate);
            } catch (MalformedURLException e) {
                throw new MalformedSpecificationException(e);
            }
        }
    } catch (IOException ignore) {
        // ignore for the moment
        LOGGER.trace("Specification is not a valid zip: " + ignore.getMessage() + "Continue discovery...");
    }
    // finaly try with a zip protocol
    if (url != null && !url.toExternalForm().startsWith("jar")) {
        try {
            final URL jarUrl = new URL("jar:" + url.toURI().toASCIIString() + "!/");
            final JarURLConnection jar = (JarURLConnection) jarUrl.openConnection();
            return list(new ZipLister(url, jar.getJarFile().entries(), filter), defaultStartLevel, defaultStart,
                    defaultUpdate);
        } catch (Exception ignore) {
            LOGGER.trace("Specification is not a valid jar: " + ignore.getMessage());
        }
    }
    // if we got to this point then we cannot go further
    LOGGER.trace("Specification urlSpec cannot be used. Stopping.");
    throw new MalformedSpecificationException(
            "Specification [" + provisionSpec.getPath() + "] could not be used");
}

From source file:org.dataconservancy.ui.dcpmap.DataFileMapperTest.java

/**
 * Mocks the scenario when creating a DCP for a DataFile that <em>is</em> in the archive.  The DataFile in
 * the archive has only one version; the archive contains one Root DU, and one State DU for the DataFile.  The
 * archive <em>does</em> contain the DcsFile for the DataFile.
 *
 * @throws Exception/*  w w w .j a  v  a2  s. c om*/
 */
@Test
public void testToDcpWithArchiveStateSingleVersionFileInArchive() throws Exception {
    final String archiveParentEntityId = "archive:dataitem:1";
    final String businessDataFileId = "business:datafile:1";

    final String archiveRootDuEntityId = "root:1";
    final String archiveStateDuEntityId = "state:1";
    final String lineageId = "lineage:1";

    final String archiveDcsFileId = "dcsfile:1";

    final File sourceFile = createTemp();
    final DataFile df = new DataFile();
    df.setFormat("application/text");
    df.setId(businessDataFileId);
    df.setName(sourceFile.getName());

    when(searcher.findLatestState(businessDataFileId)).thenReturn(new BusinessObjectState() {
        @Override
        public DcsDeliverableUnit getRoot() {
            final String rootXml = String.format(ROOT_DU_TEMPLATE, archiveRootDuEntityId, lineageId,
                    archiveParentEntityId, businessDataFileId);
            try {
                return dmb.buildDeliverableUnit(IOUtils.toInputStream(rootXml));
            } catch (InvalidXmlException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        @Override
        public DcsDeliverableUnit getLatestState() {
            final String stateXml = String.format(STATE_DU_TEMPLATE, archiveStateDuEntityId, lineageId,
                    archiveRootDuEntityId, businessDataFileId);
            try {
                return dmb.buildDeliverableUnit(IOUtils.toInputStream(stateXml));
            } catch (InvalidXmlException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    });

    final DcsFile dcsFile = new DcsFile();
    dcsFile.setId(archiveDcsFileId);
    dcsFile.setSizeBytes(sourceFile.length());
    dcsFile.setExtant(true);
    dcsFile.setName(sourceFile.getName());
    dcsFile.setSource(sourceFile.toURL().toExternalForm());
    dcsFile.addAlternateId(new DcsResourceIdentifier(Id.getAuthority(), businessDataFileId, DATAFILE_ID_TYPE));

    when(searcher.findDataFile(businessDataFileId)).thenReturn(dcsFile);

    final Dcp dcp = underTest.toDcp(archiveParentEntityId, df);
    assertNotNull(dcp);

    //        for (DcsEntity e : dcp) {
    //            e.toString(hpp);
    //        }
    //
    //        System.out.println(hpp.toString());

    final DcsDeliverableUnit stateDu = assertSingleStateDuPresent(dcp, STATE_DU_TYPE);
    assertFormerRef(stateDu, businessDataFileId);
    assertHasSingleManifestation(stateDu.getId(), STATE_MANIFESTATION_TYPE, dcp);
    assertHasSuccessor(stateDu, archiveStateDuEntityId);
    assertHasParentRef(stateDu, archiveRootDuEntityId);
    final DcsManifestation fileMan = assertHasSingleManifestation(stateDu.getId(), DATAFILE_MAN_TYPE, dcp);
    final String ref = fileMan.getManifestationFiles().iterator().next().getRef().getRef();
    assertEquals(archiveDcsFileId, ref);
    assertDoesNotHaveFile(archiveDcsFileId, dcp);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find the resource with the given name.  A resource is some data
 * (images, audio, text, etc.) that can be accessed by class code in a
 * way that is independent of the location of the code.  The name of a
 * resource is a "/"-separated path name that identifies the resource.
 * If the resource cannot be found, return <code>null</code>.
 * <p>/*from  w w w.ja va 2s  .c  o m*/
 * This method searches according to the following algorithm, returning
 * as soon as it finds the appropriate URL.  If the resource cannot be
 * found, returns <code>null</code>.
 * <ul>
 * <li>If the <code>delegate</code> property is set to <code>true</code>,
 *     call the <code>getResource()</code> method of the parent class
 *     loader, if any.</li>
 * <li>Call <code>findResource()</code> to find this resource in our
 *     locally defined repositories.</li>
 * <li>Call the <code>getResource()</code> method of the parent class
 *     loader, if any.</li>
 * </ul>
 *
 * @param name Name of the resource to return a URL for
 */
public URL getResource(String name) {

    if (log.isDebugEnabled())
        log.debug("getResource(" + name + ")");
    URL url = null;

    // (1) Delegate to parent if requested
    if (delegate) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader " + parent);
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        url = loader.getResource(name);
        if (url != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning '" + url.toString() + "'");
            return (url);
        }
    }

    // (2) Search local repositories
    url = findResource(name);
    if (url != null) {
        // Locating the repository for special handling in the case 
        // of a JAR
        ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
        try {
            String repository = entry.codeBase.toString();
            if ((repository.endsWith(".jar")) && (!(name.endsWith(".class")))) {
                // Copy binary content to the work directory if not present
                File resourceFile = new File(loaderDir, name);
                url = resourceFile.toURL();
            }
        } catch (Exception e) {
            // Ignore
        }
        if (log.isDebugEnabled())
            log.debug("  --> Returning '" + url.toString() + "'");
        return (url);
    }

    // (3) Delegate to parent unconditionally if not already attempted
    if (!delegate) {
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        url = loader.getResource(name);
        if (url != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning '" + url.toString() + "'");
            return (url);
        }
    }

    // (4) Resource was not found
    if (log.isDebugEnabled())
        log.debug("  --> Resource not found, returning null");
    return (null);

}

From source file:org.talend.repository.imports.ImportItemUtil.java

@SuppressWarnings("unchecked")
private void deployJarToDes(final ResourcesManager manager, Set<String> extRoutines) {
    File file = null;
    if (extRoutines.isEmpty()) {
        return;/* w  w w . jav a2  s.  c  om*/
    }

    for (Iterator iterator = manager.getPaths().iterator(); iterator.hasNext();) {
        String value = iterator.next().toString();
        file = new File(value);
        if (extRoutines.contains(file.getName())) {
            try {
                CorePlugin.getDefault().getLibrariesService().deployLibrary(file.toURL());
            } catch (MalformedURLException e) {
                ExceptionHandler.process(e);
            } catch (IOException e) {
                ExceptionHandler.process(e);
            }
        }

    }

}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

/**
 * Gets JobInfo properties.//from   w  ww.ja  va2s  .c  om
 * 
 * @param process
 * @return
 */
protected List<URL> getJobInfoFile(ExportFileResource process, String contextName) {
    List<URL> list = new ArrayList<URL>();
    try {
        String tmpFoler = getTmpFolder();
        String jobInfoPath = tmpFoler + File.separator + JOBINFO_FILE;

        boolean addStat = false;// TDI-23641, in studio, false always.
        if (CommonsPlugin.isHeadless()) {
            addStat = isOptionChoosed(ExportChoice.addStatistics);
        }
        JobInfoBuilder jobInfoBuilder = new JobInfoBuilder(process, contextName,
                isOptionChoosed(ExportChoice.applyToChildren), addStat, jobInfoPath);
        jobInfoBuilder.buildProperty();
        File jobInfoFile = new File(jobInfoPath);
        URL url = jobInfoFile.toURL();
        list.add(url);
    } catch (Exception e) {
        ExceptionHandler.process(e);
    }
    return list;
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Get URL./*from   ww  w.j a va2 s. c  om*/
 */
protected URL getURL(File file) throws MalformedURLException {

    File realFile = file;
    try {
        realFile = realFile.getCanonicalFile();
    } catch (IOException e) {
        // Ignore
    }
    return realFile.toURL();

}