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.bugs.JnlpAccessWithSecuredHudsonTest.java

@PresetData(DataSet.NO_ANONYMOUS_READACCESS)
@SuppressWarnings("SleepWhileInLoop")
@Test// www .  jav  a  2 s.  c  o  m
public void serviceUsingDirectSecret() throws Exception {
    Slave slave = createNewJnlpSlave("test");
    r.jenkins.setNodes(Collections.singletonList(slave));
    r.createWebClient().goTo("computer/test/slave-agent.jnlp?encrypt=true", "application/octet-stream");
    String secret = slave.getComputer().getJnlpMac();
    // To watch it fail: secret = secret.replace('1', '2');
    File slaveJar = tmp.newFile();
    FileUtils.copyURLToFile(new Slave.JnlpJar("slave.jar").getURL(), slaveJar);
    Proc p = new hudson.Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().stdout(System.out)
            .stderr(System.err).cmds(JavaEnvUtils.getJreExecutable("java"), "-jar", slaveJar.getAbsolutePath(),
                    "-jnlpUrl", r.getURL() + "computer/test/slave-agent.jnlp", "-secret", secret)
            .start();
    try {
        while (!slave.toComputer().isOnline()) { // TODO can use r.waitOnline(slave) after https://github.com/jenkinsci/jenkins-test-harness/pull/80
            Thread.sleep(100);
        }
        Channel channel = slave.getComputer().getChannel();
        assertFalse("SECURITY-206", channel.isRemoteClassLoadingAllowed());
        r.jenkins.getExtensionList(AdminWhitelistRule.class).get(AdminWhitelistRule.class)
                .setMasterKillSwitch(false);
        final File f = new File(r.jenkins.getRootDir(), "config.xml");
        assertTrue(f.exists());
        try {
            fail("SECURITY-206: " + channel.call(new Attack(f.getAbsolutePath())));
        } catch (Exception x) {
            assertThat(Functions.printThrowable(x), containsString("https://jenkins.io/redirect/security-144"));
        }
    } finally {
        p.kill();
    }
}

From source file:me.ryandowling.allmightybot.data.Settings.java

public void setupExampleStuff() {
    // Timed messages
    App.INSTANCE.getTimedMessages().add(new TimedMessage()
            .create("This is a test message which the bot will run " + "" + " every now and then"));

    try {//from  ww  w. j  av a 2  s  .  c om
        FileUtils.writeStringToFile(Utils.getTimedMessagesFile().toFile(),
                AllmightyBot.GSON.toJson(App.INSTANCE.getTimedMessages()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Spam timeouts
    App.INSTANCE.getSpams()
            .add(new Spam().create("Go fuck yourself",
                    "This is what the bot will say back! Make " + "sure to be witty! [Timed out] [30 minutes]",
                    SpamActionType.TIMEOUT, 30));
    App.INSTANCE.getSpams()
            .add(new Spam().create("Knob gobbler", "The bot says ban! [Ban]", SpamActionType.BAN, 30));

    try {
        FileUtils.writeStringToFile(Utils.getSpamFile().toFile(),
                AllmightyBot.GSON.toJson(App.INSTANCE.getSpams()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Link whitelist
    App.INSTANCE.getAllowedLinks().add(".*?\\.*twitter.com.*?");

    try {
        FileUtils.writeStringToFile(Utils.getLinksFile().toFile(),
                AllmightyBot.GSON.toJson(App.INSTANCE.getAllowedLinks()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Commands file
    try {
        URL inputUrl = System.class.getResource("/json/commands.json");
        FileUtils.copyURLToFile(inputUrl, Utils.getCommandsFile().toFile());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to copy commands.json to disk! Exiting!");
        System.exit(1);
    }

    // Lang file
    try {
        URL inputUrl = System.class.getResource("/json/lang.json");
        FileUtils.copyURLToFile(inputUrl, Utils.getLangFile().toFile());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to copy lang.json to disk! Exiting!");
        System.exit(1);
    }
}

From source file:com.anritsu.mcrepositorymanager.utils.Packing.java

public boolean downloadPackage(McPackage p) {
    boolean result = false;
    for (String link : p.getDownloadLinks()) {
        try {//from   w w w .  java2 s  .com
            String dowloadLink[] = link.split("/");
            String fileName = dowloadLink[dowloadLink.length - 1];
            status.getDownloadedPackages().add(fileName);
            System.out.println("Downloading package " + fileName + ": " + link);
            if (!new File(FOLDER_PATH + fileName).exists()) {
                FileUtils.copyURLToFile(new URL(link), new File(FOLDER_PATH + fileName));
            }
            LOGGER.log(Level.INFO, link + " succesfully downloaded!");
            result = true;
        } catch (IOException ex) {
            Logger.getLogger(Packing.class.getName()).log(Level.SEVERE, null, ex);
            result = false;
        }
    }
    return result;
}

From source file:ffx.numerics.fft.RowMajorComplex3DCuda.java

/**
 * {@inheritDoc}/* www .  j  a  va  2 s .c  o  m*/
 */
@Override
public void run() {
    JCudaDriver.setExceptionsEnabled(true);
    JCufft.setExceptionsEnabled(true);
    JCudaDriver.setLogLevel(LogLevel.LOG_ERROR);

    // Initialize the driver and create a context for the first device.
    cuInit(0);
    CUcontext pctx = new CUcontext();
    CUdevice dev = new CUdevice();
    CUdevprop prop = new CUdevprop();
    cuDeviceGetProperties(prop, dev);
    logger.info(" CUDA " + prop.toFormattedString());

    cuDeviceGet(dev, 0);
    cuCtxCreate(pctx, 0, dev);

    KernelLauncher kernelLauncher = null;
    // Load the CUBIN file and obtain the "recipSummation" function.
    try {
        String bit = System.getProperty("sun.arch.data.model").trim();
        URL source = getClass().getClassLoader()
                .getResource("ffx/numerics/fft/recipSummation-" + bit + ".cubin");
        File cubinFile = File.createTempFile("recipSummation", "cubin");
        FileUtils.copyURLToFile(source, cubinFile);
        String kernelPath = cubinFile.getCanonicalPath();
        kernelLauncher = KernelLauncher.load(kernelPath, "recipSummation");
    } catch (Exception e) {
        String message = "Error loading the reciprocal summation kernel";
        logger.log(Level.SEVERE, message, e);
    }

    // Copy the data array to the device.
    dataDevice = new CUdeviceptr();
    cuMemAlloc(dataDevice, len * 2 * Sizeof.DOUBLE);
    dataPtr = Pointer.to(data);
    cuMemcpyHtoD(dataDevice, dataPtr, len * 2 * Sizeof.DOUBLE);

    // Copy the recip array to the device.
    recipDevice = new CUdeviceptr();
    cuMemAlloc(recipDevice, len * Sizeof.DOUBLE);
    recipPtr = Pointer.to(recip);
    cuMemcpyHtoD(recipDevice, recipPtr, len * Sizeof.DOUBLE);

    // Create a CUFFT plan for the data
    plan = new cufftHandle();
    cufftPlan3d(plan, nX, nY, nZ, cufftType.CUFFT_Z2Z);

    int threads = 512;
    int nBlocks = len / threads + (len % threads == 0 ? 0 : 1);
    int gridSize = (int) Math.floor(Math.sqrt(nBlocks)) + 1;

    dim3 gridDim = new dim3(gridSize, gridSize, 1);
    dim3 blockDim = new dim3(threads, 1, 1);
    kernelLauncher.setup(gridDim, blockDim);

    logger.info(format(" CUDA thread initialized with %d threads per block", threads));
    logger.info(format(" Grid Size: (%d x %d x 1).", gridSize, gridSize));

    assert (gridSize * gridSize * threads >= len);

    synchronized (this) {
        while (!free) {
            if (doConvolution) {
                cuMemcpyHtoD(dataDevice, dataPtr, len * 2 * Sizeof.DOUBLE);
                cufftExecC2C(plan, dataDevice, dataDevice, CUFFT_FORWARD);
                kernelLauncher.call(dataDevice, recipDevice, len);
                cufftExecC2C(plan, dataDevice, dataDevice, CUFFT_INVERSE);
                cuMemcpyDtoH(dataPtr, dataDevice, len * 2 * Sizeof.DOUBLE);
                doConvolution = false;
                notify();
            }
            try {
                wait();
            } catch (InterruptedException e) {
                logger.severe(e.toString());
            }
        }
        cufftDestroy(plan);
        cuMemFree(dataDevice);
        cuMemFree(recipDevice);
        dead = true;
        notify();
    }
    logger.info(" CUDA Thread Done!");
}

From source file:hudson.lifecycle.WindowsInstallerLink.java

/**
 * Copies a single resource into the target folder, by the given name, and handle errors gracefully.
 *//*  w  w  w .j  av  a  2  s  .  c o  m*/
private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name)
        throws ServletException, IOException {
    try {
        FileUtils.copyURLToFile(src, new File(dir, name));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to copy " + name, e);
        sendError("Failed to copy " + name + ": " + e.getMessage(), req, rsp);
        throw new AbortException();
    }
}

From source file:me.bramhaag.discordselfbot.Bot.java

/**
 * Copy file from {@code url} to {@code destination}
 *
 * @param url url to file// w w  w  .  j a va 2  s. c o  m
 * @param destination destination file
 *
 * @throws IOException if {@code url} cannot be opened
 * @throws IOException if {@code destination} is a directory
 * @throws IOException if {@code destination} cannot be written
 * @throws IOException if {@code destination} needs creating but can't be
 * @throws IOException if an IO error occurs during copying
 */
private void extract(URL url, File destination) throws IOException {
    if (!destination.exists())
        FileUtils.copyURLToFile(url, destination);
}

From source file:Data.c_Card.java

public ImageIcon getImage() {
    try {/*w ww.  j  a  va 2  s. com*/
        ImageIcon icon = new ImageIcon(
                ImageIO.read(new File(getImagePath())).getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH));
        return icon;
    } catch (Exception ex) {
        try {
            FileUtils.copyURLToFile(new URL(WebBrowserPanel.getCardImageURL(MID)), new File(getImagePath()));
            return getImage();
        } catch (Exception ex2) {
            int i = 0;
        }
    }
    return null;
}

From source file:com.comcast.magicwand.spells.web.chrome.ChromePhoenixDriver.java

/**
 * {@inheritDoc}/*  w w  w  . ja  v  a  2  s.  c o m*/
 */
public boolean verify(PhoenixDriverIngredients i) {
    Map<String, Object> driverConfigs = i.getDriverConfigs();

    ChromePlatformSpecifics cps = createChromePlatformSpecifics(
            (String) driverConfigs.get(CHROME_DRIVER_VERSION));

    LOG.debug("Using cps[{}, {}, {}]", cps.getSuffix(), cps.getExtension(), cps.getVersion());

    String version = cps.getVersion();
    String osName = cps.getSuffix();
    String pwd = System.getProperty("user.dir");

    //determine the driver name
    String driverName = String.format("chromedriver%s-%s", osName, version);
    String driverTargetDir = Paths.get(pwd, "target", "drivers").toString();
    File driver = Paths.get(driverTargetDir, driverName + cps.getExtension()).toFile();

    if (!driver.exists()) {
        LOG.debug("No cached chromedriver driver found");

        /* Download chromedriver zip */
        File zipDriver = Paths.get(driverTargetDir, driverName + ".zip").toFile();
        if (!zipDriver.exists()) {
            String driverURL = String.format(DRIVER_URL_FORMAT, version, osName);
            try {
                URL driverZipURL = new URL(driverURL);
                LOG.debug("Will download driver package [{}]", driverURL);

                FileUtils.copyURLToFile(driverZipURL, zipDriver);
            } catch (IOException e) {
                LOG.error("Error downloading [{}]: {}", driverURL, e);
                return false;
            }
        }

        /* Exctract chromedriver zip */
        try {
            extractZip(zipDriver, driverTargetDir);
        } catch (IOException e) {
            LOG.error("Error extracting [{}]: {}", zipDriver, driverTargetDir, e);
            return false;
        }

        /* For caching purposes, rename chromedriver to keep os and version info */
        File genericDriver = Paths.get(driverTargetDir, "chromedriver" + cps.getExtension()).toFile();
        try {
            FileUtils.moveFile(genericDriver, driver);
        } catch (IOException e) {
            LOG.error("Error moving [{}] to [{}]: {}", genericDriver, driver, e);
            return false;
        }

        driver.setExecutable(true);
    }

    LOG.debug("Will use driver at [{}]", driver);
    systemSetProperty("webdriver.chrome.driver", driver.toString());

    this.webDriver = this.createDriver(i.getDriverCapabilities());

    return true;
}

From source file:net.doubledoordev.cmd.CurseModpackDownloader.java

public int run() throws IOException, ZipException {
    final long start = System.currentTimeMillis();
    inputCheck();/* w  w  w  .j a  v a2 s.  com*/

    manifestFile = new File(output, "manifest.json");
    inputEqualsOutput = manifestFile.getCanonicalPath().equals(input.getCanonicalPath());
    if (!inputEqualsOutput && manifestFile.exists())
        manifestFile.delete();

    unpackOrMoveJson();
    startModDownloadThreads();

    mcVersion = manifest.minecraft.version;
    forgeVersion = getForgeVersion();

    if (!noForge) {
        if (forgeVersion != null) {
            downloadForgeJson();
            if (forgeJson != null) {
                installerFile = downloadForgeInstaller();
                if (installerFile != null && server) {
                    installerProcess = runForgeInstaller(installerFile);
                }
            }
        } else {
            URL mcServerJar = new URL("http://s3.amazonaws.com/Minecraft.Download/versions/" + mcVersion
                    + "/minecraft_server." + mcVersion + ".jar");
            FileUtils.copyURLToFile(mcServerJar,
                    new File(output, FilenameUtils.getName(mcServerJar.getFile())));
        }
    }

    if (server && eula && !quiet) {
        FileUtils.writeStringToFile(new File(output, "eula.txt"),
                "#No bullshit EULA file, courtesy of CurseModpackDownloader\n#https://account.mojang.com/documents/minecraft_eula\n#"
                        + new Date().toString() + "\neula=true");
    }

    waitTillDone();
    if (!quiet)
        writeModpackinfo();

    if (!quiet)
        logger.println("Done downloading mods.");

    if (!server) {
        if (!quiet)
            logger.println(
                    "You need to manually install the client, if applicable, the forge installer has already been downloaded to the output directory.");
    }
    long time = System.currentTimeMillis() - start;
    if (!quiet)
        logger.println(String.format("Total time to completion: %.2f seconds", time / 1000.0));

    return failCounter.get() == 0 ? 0 : 1;
}

From source file:gobblin.aws.AWSJobConfigurationManager.java

private void fetchJobConf() throws IOException, ConfigurationException {
    // Refresh job config pull details from config
    fetchJobConfSettings();/*from ww w .j  a  va2 s .  co  m*/

    // TODO: Eventually when config store supports job files as well
    // .. we can replace this logic with config store
    if (this.jobConfS3Uri.isPresent() && this.jobConfDirPath.isPresent()) {

        // Download the zip file
        final String zipFile = appendSlash(this.jobConfDirPath.get())
                + StringUtils.substringAfterLast(this.jobConfS3Uri.get(), File.separator);
        LOGGER.debug("Downloading to zip: " + zipFile + " from uri: " + this.jobConfS3Uri.get());

        FileUtils.copyURLToFile(new URL(this.jobConfS3Uri.get()), new File(zipFile));
        final String extractedPullFilesPath = appendSlash(this.jobConfDirPath.get()) + "files";

        // Extract the zip file
        LOGGER.debug("Extracting to directory: " + extractedPullFilesPath + " from zip: " + zipFile);
        unzipArchive(zipFile, new File(extractedPullFilesPath));

        // Load all new job configurations
        // TODO: Currently new and updated jobs are handled, we should un-schedule deleted jobs as well
        final File jobConfigDir = new File(extractedPullFilesPath);
        if (jobConfigDir.exists()) {
            LOGGER.info("Loading job configurations from " + jobConfigDir);
            final Properties properties = new Properties();
            properties.setProperty(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY,
                    jobConfigDir.getAbsolutePath());

            final List<Properties> jobConfigs = SchedulerUtils.loadGenericJobConfigs(properties);
            LOGGER.info("Loaded " + jobConfigs.size() + " job configuration(s)");
            for (Properties config : jobConfigs) {
                LOGGER.debug("Config value: " + config);

                // If new config or existing config got updated, then post new job config arrival event
                final String jobConfigPathIdentifier = config
                        .getProperty(ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY);
                if (!jobConfFiles.containsKey(jobConfigPathIdentifier)) {
                    jobConfFiles.put(jobConfigPathIdentifier, config);

                    postNewJobConfigArrival(config.getProperty(ConfigurationKeys.JOB_NAME_KEY), config);
                    LOGGER.info("New config arrived for job: " + jobConfigPathIdentifier);
                } else if (!config.equals(jobConfFiles.get(jobConfigPathIdentifier))) {
                    jobConfFiles.put(jobConfigPathIdentifier, config);

                    postNewJobConfigArrival(config.getProperty(ConfigurationKeys.JOB_NAME_KEY), config);
                    LOGGER.info("Config updated for job: " + jobConfigPathIdentifier);
                } else {
                    LOGGER.info("Config not changed for job: " + jobConfigPathIdentifier);
                }
            }
        } else {
            LOGGER.warn("Job configuration directory " + jobConfigDir + " not found");
        }
    }
}