Example usage for org.apache.commons.io FileUtils copyURLToFile

List of usage examples for org.apache.commons.io FileUtils copyURLToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyURLToFile.

Prototype

public static void copyURLToFile(URL source, File destination) throws IOException 

Source Link

Document

Copies bytes from the URL source to a file destination.

Usage

From source file:hudson.PluginManager.java

/**
 * If the war file has any "/WEB-INF/plugins/*.hpi", extract them into the plugin directory.
 *//*from w  ww . j a  va 2s .  co  m*/
private void loadBundledPlugins() {
    // this is used in tests, when we want to override the default bundled plugins with .hpl versions
    if (System.getProperty("hudson.bundled.plugins") != null) {
        return;
    }
    Set paths = context.getResourcePaths("/WEB-INF/plugins");
    if (paths == null)
        return; // crap
    for (String path : (Set<String>) paths) {
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        if (fileName.length() == 0) {
            // see http://www.nabble.com/404-Not-Found-error-when-clicking-on-help-td24508544.html
            // I suspect some containers are returning directory names.
            continue;
        }
        try {
            URL url = context.getResource(path);
            long lastModified = url.openConnection().getLastModified();
            File file = new File(rootDir, fileName);
            if (!file.exists() || file.lastModified() != lastModified) {
                FileUtils.copyURLToFile(url, file);
                file.setLastModified(url.openConnection().getLastModified());
                // lastModified is set for two reasons:
                // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade
                // - to make sure the value is not changed after each restart, so we can avoid
                // unpacking the plugin itself in ClassicPluginStrategy.explode
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin " + fileName, e);
        }
    }
}

From source file:dpfmanager.shell.modules.client.core.ClientService.java

/**
 * Download/*from   w  w w  .  ja v a2 s . com*/
 */
private void downloadFile(String path) {
    try {
        URL url = new URL(parameters.get("-url") + path);
        File downloaded = Files.createTempFile("report", "zip").toFile();
        FileUtils.copyURLToFile(url, downloaded);
        unZipReport(downloaded);
        downloaded.delete();
    } catch (Exception e) {
        context.send(BasicConfig.MODULE_MESSAGE,
                new LogMessage(getClass(), Level.ERROR, bundle.getString("cannotDownload")));
    }
}

From source file:com.compomics.pladipus.controller.setup.InstallPladipus.java

private void installPladipusModules() throws IOException {
    //search//from w ww .j  av  a  2s .c o m
    for (String aModuleName : modulesToInstall) {
        LOGGER.debug("Installing " + aModuleName);
        URL inputUrl = getClass().getResource("/modules/Pladipus-" + aModuleName + "-" + version + ".jar");
        File dest = new File(pladipusFolder, "/external/Pladipus-" + aModuleName + "-" + version + ".jar");
        dest.getParentFile().mkdirs();
        FileUtils.copyURLToFile(inputUrl, dest);
    }
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

private Path extractBinary(final String binaryName) throws IOException, URISyntaxException {
    final URI sourceHoverflyUrl = findResourceOnClasspath(binaryName);
    final Path temporaryHoverflyPath = Files.createTempFile(binaryName, "");
    LOGGER.info("Storing binary in temporary directory " + temporaryHoverflyPath);
    final File temporaryHoverflyFile = temporaryHoverflyPath.toFile();
    FileUtils.copyURLToFile(sourceHoverflyUrl.toURL(), temporaryHoverflyFile);
    if (SystemUtils.IS_OS_WINDOWS) {
        temporaryHoverflyFile.setExecutable(true);
        temporaryHoverflyFile.setReadable(true);
        temporaryHoverflyFile.setWritable(true);
    } else {//  w  w w .  j av a2 s.c o  m
        Files.setPosixFilePermissions(temporaryHoverflyPath, new HashSet<>(asList(OWNER_EXECUTE, OWNER_READ)));
    }

    return temporaryHoverflyPath;
}

From source file:com.anritsu.mcreleaseportal.tcintegration.ProcessTCRequest.java

public Release extractRelease(String changesXMLFileName) throws Exception {
    Release rel;/*from ww  w.j  av  a2  s  . com*/
    File dir = new File(Configuration.getInstance().getSavePath());
    if (!dir.isDirectory()) {
        new File(Configuration.getInstance().getSavePath()).mkdirs();
    }
    String fileName = buildName + "_" + buildNumber + "_" + System.currentTimeMillis();
    File file = new File(dir, fileName);
    file.createNewFile();

    FileUtils.copyURLToFile(new URL(artifactsLocation + changesXMLFileName), file);

    pXML = new ProcessChangesXML(file.getAbsolutePath());
    // Check if xml is succesfully validated. If validateXmlXsd() returns an non empty string result code is 1
    result.setResultMessage(pXML.validateXmlXsd());
    if (!result.getResultMessage().replace("Success", "").equalsIgnoreCase("")) {
        result.setResultCode("1");
    }
    rel = pXML.getRelease();
    file.delete();
    return rel;
}

From source file:it.uniud.ailab.dcore.wrappers.external.OpenNlpBootstrapperAnnotator.java

/**
 * Checks if the database entry for the POStagger are local or web resources
 * and downloads the online ones.//from ww  w . j a v a 2 s.  c  o m
 *
 */
private static void prepareModels() {

    Map<String, String> correctPaths = new HashMap<>();

    for (Map.Entry e : databasePaths.entrySet()) {

        String entryKey = (String) e.getKey();
        String entryValue = (String) e.getValue();

        try {

            URL url = new URL((String) e.getValue());
            // if we're dealing with a local file, then
            // we don't care and continue.
            if (isLocalFile(url)) {
                Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO,
                        "Using {0} as local path...", e.getValue());
                continue;
            }

            // Download the new file and put it in a local folder
            String newFileName = FileSystem.getDistillerTmpPath().concat(FileSystem.getSeparator())
                    .concat("OpenNLPmodels").concat(FileSystem.getSeparator()).concat(url.getPath()
                            .substring(url.getPath().lastIndexOf("/") + 1, url.getPath().length()));
            ;

            // Check if the file already exists (i.e. we have probably
            // downloaded it before). If exists, then we're happy and 
            // don't download anything
            File f = new File(newFileName);
            if (f.exists()) {
                //LOG.log(Level.INFO, "Using {0} as local cache...", newFileName);
                correctPaths.put(entryKey, f.getCanonicalPath());
                continue;
            }

            Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO,
                    "Downloading model from {0}...", e.getValue());
            FileUtils.copyURLToFile(url, f);
            Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO,
                    "OpenNLP database saved in {0}", f.getCanonicalPath());

            correctPaths.put(entryKey, f.getAbsolutePath());

        } catch (MalformedURLException ex) {
            //LOG.log(Level.INFO, "Using {0} as local path...", e.getValue());
        } catch (IOException ex) {
            //LOG.log(Level.SEVERE, "Savefile error", ex);
            throw new AnnotationException(new OpenNlpBootstrapperAnnotator(),
                    "Failed to download " + e.getValue(), ex);
        } finally {

            // if something went wrong, put the default value.
            if (!correctPaths.containsKey(entryKey)) {
                correctPaths.put(entryKey, entryValue);
            }
        }
    }

    // update the old map with the new values
    databasePaths.clear();
    databasePaths.putAll(correctPaths);

}

From source file:ca.weblite.codename1.ios.CodenameOneIOSBuildTask.java

/**
 * Extracts the iOSPort that is bundled inside the module's jar file
 * and saves it in the iOSPort directory.
 *///from  ww w. j a v a  2  s  . co m
private void extractIOSPort() throws IOException {
    File dir = getIOSPortDir();
    if (!dir.exists()) {
        dir.mkdir();

        URL src = getClass().getResource("resources/iOSPort.zip");

        File tmp = File.createTempFile("iosport", "zip");
        tmp.delete();
        FileUtils.copyURLToFile(src, tmp);
        Expand unzip = (Expand) getProject().createTask("unzip");
        unzip.setTaskType("unzip");

        unzip.setSrc(tmp);
        unzip.setDest(getiOSPort());
        unzip.execute();
    }

}

From source file:fr.inria.eventcloud.deployment.cli.launchers.EventCloudsManagementServiceDeployer.java

private static void downloadResources(String resourcesUrl, boolean activateLoggers) throws IOException {
    resourcesDirPath = System.getProperty("java.io.tmpdir") + File.separator + "eventcloud-resources";

    File tmpResourcesDir = new File(resourcesDirPath);
    tmpResourcesDir.mkdir();//from ww w .jav  a  2  s  .  co m

    FileUtils.copyURLToFile(new URL(resourcesUrl + "proactive.security.policy"),
            new File(tmpResourcesDir, "proactive.security.policy"));

    if (activateLoggers) {
        FileUtils.copyURLToFile(new URL(resourcesUrl + "log4j-console.properties"),
                new File(tmpResourcesDir, "log4j-console.properties"));

        FileUtils.copyURLToFile(new URL(resourcesUrl + "logback-console.xml"),
                new File(tmpResourcesDir, "logback-console.xml"));
    } else {
        FileUtils.copyURLToFile(new URL(resourcesUrl + "log4j-inactive.properties"),
                new File(tmpResourcesDir, "log4j-inactive.properties"));

        FileUtils.copyURLToFile(new URL(resourcesUrl + "logback-inactive.xml"),
                new File(tmpResourcesDir, "logback-inactive.xml"));
    }

    FileUtils.copyURLToFile(new URL(resourcesUrl + "eventcloud.properties"),
            new File(tmpResourcesDir, "eventcloud.properties"));
    List<String> eventCloudProperties = FileUtils
            .readLines(new File(resourcesDirPath + File.separator + "eventcloud.properties"));
    for (String property : eventCloudProperties) {
        if (property.startsWith(EventCloudProperties.REPOSITORIES_PATH.getName() + "=")) {
            repositoriesDirPath = property.substring(property.indexOf('=') + 1);
        }
    }
}

From source file:com.htmlhifive.pitalium.core.io.FilePersisterTest.java

/**
 * result.json???//from w w w  .j  av  a 2s.c  om
 */
@Test
public void testLoadTestResult() throws Exception {
    File file = new File(BASE_DIRECTORY + "/test1/testClass/result.json");
    file.getParentFile().mkdirs();
    FileUtils.copyURLToFile(getClass().getResource("FilePersister_TestResult.json"), file);

    PersistMetadata metadata = new PersistMetadata("test1", "testClass");
    TestResult actual = persister.loadTestResult(metadata);

    TestResult expected = JSONUtils.readValue(getClass().getResourceAsStream("FilePersister_TestResult.json"),
            TestResult.class);
    Field imageField = TargetResult.class.getDeclaredField("image");
    imageField.setAccessible(true);
    for (ScreenshotResult sr : expected.getScreenshotResults()) {
        ScreenshotImage image = new PersistedScreenshotImage(persister,
                new PersistMetadata(expected.getResultId(), sr.getTestClass(), sr.getTestMethod(),
                        sr.getScreenshotId(), new IndexDomSelector(SelectorType.TAG_NAME, "body", 0), null,
                        new PtlCapabilities(sr.getCapabilities())));
        imageField.set(sr.getTargetResults().get(0), image);
    }

    assertThat(actual, is(expected));
}

From source file:com.inikah.slayer.service.impl.PhotoLocalServiceImpl.java

public long createPortrait(long imageId) {

    Photo photo = null;//  w  ww .  j a va  2 s .c o  m
    try {
        photo = fetchPhoto(imageId);
    } catch (SystemException e) {
        e.printStackTrace();
    }

    if (Validator.isNull(photo))
        return 0l;

    long profileId = photo.getClassPK();

    String fileName = imageId + StringPool.PERIOD + photo.getContentType();

    StringBuilder sb = new StringBuilder().append("http://")
            .append(AppConfig.get(IConstants.CFG_AWS_CLOUDFRONT_DOMAIN)).append(StringPool.SLASH)
            .append(profileId).append(StringPool.SLASH).append(photo.getUploadDate().getTime())
            .append(StringPool.SLASH).append(fileName);

    URL url = null;
    try {
        url = new URL(sb.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    File file = FileUtils.getFile(fileName);
    try {
        FileUtils.copyURLToFile(url, file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String publicId = String.valueOf(imageId);
    try {
        CloudinaryUtil.getService().uploader().upload(file, Cloudinary.asMap("public_id", publicId));
    } catch (IOException e) {
        e.printStackTrace();
    }

    file.delete();

    long thumbnailId = savePortrait(imageId, profileId);

    try {
        CloudinaryUtil.getService().uploader().destroy(publicId, Cloudinary.asMap("public_id", publicId));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return thumbnailId;
}