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:org.apache.mxnet.javaapi.ImageTest.java

private static void downloadUrl(String url, String filePath, int maxRetry) throws Exception {
    File tmpFile = new File(filePath);
    Boolean success = false;/*  w  w w .  j av  a2 s .  c  o m*/
    if (!tmpFile.exists()) {
        while (maxRetry > 0 && !success) {
            try {
                FileUtils.copyURLToFile(new URL(url), tmpFile);
                success = true;
            } catch (Exception e) {
                maxRetry -= 1;
            }
        }
    } else {
        success = true;
    }
    if (!success)
        throw new Exception("$url Download failed!");
}

From source file:org.apache.syncope.installer.utilities.FileSystemUtils.java

public void copyFileFromResources(final String filePath, final String destination,
        final AbstractUIProcessHandler handler) {

    try {/*from  ww w .  j  av  a  2  s  .  co m*/
        FileUtils.copyURLToFile(getClass().getResource(filePath), new File(destination));
    } catch (IOException ex) {
        String errorMessage = "Error copying file " + filePath + " to + " + destination + ": "
                + ex.getMessage();
        handler.emitError(errorMessage, errorMessage);
        InstallLog.getInstance().error(errorMessage);
    }
}

From source file:org.apache.zeppelin.python.IPythonInterpreter.java

private void launchIPythonKernel(int ipythonPort) throws IOException {
    LOGGER.info("Launching IPython Kernel at port: " + ipythonPort);
    // copy the python scripts to a temp directory, then launch ipython kernel in that folder
    File pythonWorkDir = Files.createTempDirectory("zeppelin_ipython").toFile();
    String[] ipythonScripts = { "ipython_server.py", "ipython_pb2.py", "ipython_pb2_grpc.py" };
    for (String ipythonScript : ipythonScripts) {
        URL url = getClass().getClassLoader().getResource("grpc/python" + "/" + ipythonScript);
        FileUtils.copyURLToFile(url, new File(pythonWorkDir, ipythonScript));
    }/*from   w  ww .  j  av  a  2  s .  c  o  m*/

    CommandLine cmd = CommandLine.parse(pythonExecutable);
    cmd.addArgument(pythonWorkDir.getAbsolutePath() + "/ipython_server.py");
    cmd.addArgument(ipythonPort + "");
    DefaultExecutor executor = new DefaultExecutor();
    ProcessLogOutputStream processOutput = new ProcessLogOutputStream(LOGGER);
    executor.setStreamHandler(new PumpStreamHandler(processOutput));
    watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);

    if (useBuiltinPy4j) {
        //TODO(zjffdu) don't do hard code on py4j here
        File py4jDestFile = new File(pythonWorkDir, "py4j-src-0.10.7.zip");
        FileUtils.copyURLToFile(getClass().getClassLoader().getResource("python/py4j-src-0.10.7.zip"),
                py4jDestFile);
        if (additionalPythonPath != null) {
            // put the py4j at the end, because additionalPythonPath may already contain py4j.
            // e.g. PySparkInterpreter
            additionalPythonPath = additionalPythonPath + ":" + py4jDestFile.getAbsolutePath();
        } else {
            additionalPythonPath = py4jDestFile.getAbsolutePath();
        }
    }

    Map<String, String> envs = setupIPythonEnv();
    executor.execute(cmd, envs, this);

    // wait until IPython kernel is started or timeout
    long startTime = System.currentTimeMillis();
    while (true) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted by something", e);
        }

        try {
            StatusResponse response = ipythonClient.status(StatusRequest.newBuilder().build());
            if (response.getStatus() == IPythonStatus.RUNNING) {
                LOGGER.info("IPython Kernel is Running");
                break;
            } else {
                LOGGER.info("Wait for IPython Kernel to be started");
            }
        } catch (Exception e) {
            // ignore the exception, because is may happen when grpc server has not started yet.
            LOGGER.info("Wait for IPython Kernel to be started");
        }

        if ((System.currentTimeMillis() - startTime) > ipythonLaunchTimeout) {
            throw new IOException(
                    "Fail to launch IPython Kernel in " + ipythonLaunchTimeout / 1000 + " seconds");
        }
    }
}

From source file:org.apache.zeppelin.WebDriverManager.java

private static void downloadFireBug(int firefoxVersion, String tempPath) {
    String firebugUrlString = null;
    if (firefoxVersion < 23)
        firebugUrlString = "http://getfirebug.com/releases/firebug/1.11/firebug-1.11.4.xpi";
    else if (firefoxVersion >= 23 && firefoxVersion < 30)
        firebugUrlString = "http://getfirebug.com/releases/firebug/1.12/firebug-1.12.8.xpi";
    else if (firefoxVersion >= 30 && firefoxVersion < 33)
        firebugUrlString = "http://getfirebug.com/releases/firebug/2.0/firebug-2.0.7.xpi";
    else if (firefoxVersion >= 33)
        firebugUrlString = "http://getfirebug.com/releases/firebug/2.0/firebug-2.0.17.xpi";

    LOG.info("firebug version: " + firefoxVersion + ", will be downloaded to " + tempPath);
    try {/*from   ww  w.j  a  v a2  s.  c  o  m*/
        File firebugFile = new File(tempPath + "firebug.xpi");
        URL firebugUrl = new URL(firebugUrlString);
        if (!firebugFile.exists()) {
            FileUtils.copyURLToFile(firebugUrl, firebugFile);
        }

        File firepathFile = new File(tempPath + "firepath.xpi");
        URL firepathUrl = new URL(
                "https://addons.cdn.mozilla.net/user-media/addons/11900/firepath-0.9.7.1-fx.xpi");
        if (!firepathFile.exists()) {
            FileUtils.copyURLToFile(firepathUrl, firepathFile);
        }

    } catch (IOException e) {
        LOG.error("Download of firebug version: " + firefoxVersion + ", falied in path " + tempPath);
    }
    LOG.info("Download of firebug version: " + firefoxVersion + ", successful");
}

From source file:org.arkhamnetwork.arcade.core.Arcade.java

@Override
public void onEnable() {
    try {//from   ww w . j a v a2 s  . c o  m
        // Needed - ArcadePlugin.
        super.onEnable();

        instance = this;

        SpigotHook.injectAsyncCatcher(false);
        BukkitHook.disableChunkGC(this);
        MinecraftServerHook.disableAutoSave();

        // Create the data folder and the default configs.
        ConfigUtils.createFolderIfNotExists(getDataFolder());
        ConfigUtils.createConfigWithDefaultsIfNotExists(new File(getDataFolder(), "config.yml"),
                getResource("config.yml"));
        ConfigUtils.createConfigWithDefaultsIfNotExists(new File(getDataFolder(), "internalData.yml"),
                getResource("internalData.yml"));
        ConfigUtils.createFolderIfNotExists(new File(getDataFolder(), "cache"));

        // Load the default config.
        YamlConfiguration localConfig = YamlConfiguration
                .loadConfiguration(new File(getDataFolder(), "config.yml"));
        ArcadeConfiguration
                .setServerType(ServerType.valueOf(localConfig.getString("SERVER_TYPE").toUpperCase()));
        ArcadeConfiguration.setWebServerURL(URLUtils.toWorkingURL(localConfig.getString("WEBSERVER")));
        ArcadeConfiguration.setMysqlCredentials(new MySQLCredentials(localConfig.getString("MYSQL.HOSTNAME"),
                localConfig.getInt("MYSQL.PORT"), localConfig.getString("MYSQL.USER"),
                localConfig.getString("MYSQL.PASSWORD"), localConfig.getString("MYSQL.DATABASENAME")));
        ArcadeConfiguration.setServerName(localConfig.getString("SERVERNAME"));
        ArcadeConfiguration.setGamemodes(localConfig.getStringList("GAMEMODES"));

        // Download the Arcade.yml configuration from the web server.
        log("Attempting to download the web Arcade.yml.");
        File cacheConfigLocation = new File(Arcade.getInstance().getDataFolder() + File.separator + "cache",
                "Arcade.yml");
        if (cacheConfigLocation.exists()) {
            cacheConfigLocation.delete();
        }
        try {
            FileUtils.copyURLToFile(new URL(ArcadeConfiguration.getWebServerURL() + WEB_CONFIG_LOCATION),
                    cacheConfigLocation);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        log("The web Arcade.yml downloaded successfuly!");

        // Load the webConfiguration.
        FileConfiguration webConfig = YamlConfiguration.loadConfiguration(cacheConfigLocation);
        ArcadeWebConfiguration.setBungeeLobbyServerName(webConfig.getString("bungeeLobbyServer"));
        ArcadeWebConfiguration.setLobbySignLines(webConfig.getStringList("lobbysignligns"));

        // Load all of the mini-plugins.
        log("Attempting to load mini-plugins");

        loadedMiniPlugins.add(new mySQLConnector("mySQL-Connector", "0.1-SNAPSHOT", getServer()));
        loadedMiniPlugins.add(new NameDatabase("NameDatabase", "0.1-SNAPSHOT", getServer()));

        for (ArcadeMiniPlugin miniPlugin : this.loadedMiniPlugins) {
            miniPlugin.onEnable();
            miniPlugin.postEnable();
        }
        log("Finished loading mini-plugins");

        // Register events.
        PluginManager pluginManager = getServer().getPluginManager();
        pluginManager.registerEvents(new LobbySignsListener(), this);
        pluginManager.registerEvents(new UserManager(), this);
        pluginManager.registerEvents(new BarUtils(), this);

        // Hook any messaging channels.
        getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");

        // Register needed tasks.
        getServer().getScheduler().runTaskTimer(this, new TileEntityMemoryLeakFixTask(), 100L, 100L);

        // We have to call this manually.
        postEnable();

        // Needed - ArcadePlugin
        super.postEnable();
    } catch (Exception ex) {
        ex.printStackTrace();
        shutdown("Error caught while starting up.");
        return;
    }
}

From source file:org.arkhamnetwork.arcade.minigame.skywars.SkyWars.java

@Override
public void onEnable() {
    try {//from w  ww . j a  v  a2  s .c om
        // Needed - ArcadeMiniPlugin
        super.onEnable();

        // Generate and load the PreGame lobby's and worlds.
        PreGameManager.setup(this);

        // Download the web Skywars.yml
        log("Attempting to download the web Skywars.yml to the cache");
        File cacheConfigLocation = new File(Arcade.getInstance().getDataFolder() + File.separator + "cache",
                "Skywars.yml");
        if (cacheConfigLocation.exists()) {
            cacheConfigLocation.delete();
        }
        FileUtils.copyURLToFile(new URL(ArcadeConfiguration.getWebServerURL() + WEB_CONFIG_LOCATION),
                cacheConfigLocation);
        log("Skywars.yml download completed succuessfuly.");

        // Load the skywars web configuration.
        FileConfiguration skywarsWebConfiguration = YamlConfiguration.loadConfiguration(cacheConfigLocation);
        chatFormat = skywarsWebConfiguration.getString("chatFormat");
        for (String map : skywarsWebConfiguration.getStringList("maps")) {
            String[] split = map.split(":");
            if (split.length == 2) {
                int mapID = Integer.valueOf(split[0]);
                String mapName = split[1];
                log("* Loaded map " + mapName + " with id " + mapID + ".");
                configuredMaps.put(mapID, mapName);
            }
        }
        for (String kitName : skywarsWebConfiguration.getConfigurationSection("kits").getKeys(false)) {
            kits.put(kitName, KitUtils
                    .getKitFromSection(skywarsWebConfiguration.getConfigurationSection("kits." + kitName)));
            log("Loaded kit " + ChatColor.GREEN + kitName);
        }
        for (Kit kit : kits.values()) {
            for (Podium podium : PreGameManager.getPodiums()) {
                if (!podium.isOccupied()) {
                    KitShop shop = new KitShop(podium, kit);
                    kitShops.put(shop.getVillager().getUniqueId(), shop);
                    podium.setOccupied(true);
                    break;
                }
            }
        }

        // Load the internalDataConfig and set the last map played ID.
        FileConfiguration internalDataConfig = YamlConfiguration
                .loadConfiguration(new File(Arcade.getInstance().getDataFolder(), "internalData.yml"));
        lastPlayedMapID = internalDataConfig.getInt("skywars.lastPlayedMapID");

        // Find the next map.
        log("The last played map was " + this.getConfiguredMaps().get(lastPlayedMapID)
                + " attempting to find the next map...");
        final int nextMapID = SkywarsRotationManager.getNextMap();
        final String nextMapName = this.getConfiguredMaps().get(nextMapID);
        log("The next map playing is " + nextMapName + ".");

        // Set the lastPlayedMap as the found nextMap.
        log("Saving " + nextMapName + " as the new last played map.");
        internalDataConfig.set("skywars.lastPlayedMapID", nextMapID);
        internalDataConfig.save(new File(Arcade.getInstance().getDataFolder(), "internalData.yml"));

        // Download and load the next map.
        log("Attempting to load the map with name " + nextMapName);
        currentMapData = SkywarsMapManager.downloadAndLoadMapWithName(this, nextMapName);
        log("Map downloaded and loaded successfuly.");

        // Print out the currentMap information.
        log("Current map minimum players: " + currentMapData.getMinPlayers());
        log("Current map maximum players: " + currentMapData.getMaxPlayers());
        log("Current map timer length: " + currentMapData.getTimerLengthSeconds());
        log("Current map authors: " + currentMapData.getAuthors().keySet().toString());

        // Load the current gameDescription message.
        this.gameDescriptionMessage = DescriptionUtils.buildGameDescriptionMessage(this.getCustomName(),
                this.getPluginDescription(), nextMapName, this.getCurrentMapData().getAuthors(),
                this.getCurrentMapData().getMinPlayers(), this.getCurrentMapData().getMaxPlayers());

        // Craft the ScoreboardManager.
        this.scoreboardManager = new SkywarsScoreboardManager(this);

        // Craft the signs manager.
        this.signsManager = new SkywarsSignsManager(this);

        // Register all events.
        PluginManager pm = getServer().getPluginManager();
        pm.registerEvents(new SkywarsPlayerListener(), Arcade.getInstance());
        pm.registerEvents(new SkywarsBlockListener(), Arcade.getInstance());
        pm.registerEvents(new SkywarsEntityListener(), Arcade.getInstance());
        pm.registerEvents(new SkywarsMiscListener(), Arcade.getInstance());
        pm.registerEvents(new SkywarsInventoryListener(), Arcade.getInstance());

        // Set the current game stage.
        currentStage = stages.get(0);

        // Start the gameTask.
        gameTask = new SkywarsGameTask();
        gameTask.runTaskTimerAsynchronously(Arcade.getInstance(), 0L, 20L);

        // Needed - ArcadeMiniPlugin
        super.postEnable();
    } catch (IOException | IllegalArgumentException | IllegalStateException ex) {
        ex.printStackTrace();
    }
}

From source file:org.arquillian.cube.kubernetes.impl.utils.ProcessUtil.java

public static int runCommand(final Logger log, URL scriptUrl, Map<String, String> env) throws IOException {
    File scriptFile = File.createTempFile("arquillian-cube-script", getSuffix());
    FileUtils.copyURLToFile(scriptUrl, scriptFile);
    scriptFile.setExecutable(true, false);
    return runCommand(log, getCommand(), Arrays.asList(new String[] { scriptFile.getAbsolutePath() }), env,
            true);//from  ww  w .  j a  va  2  s.co m
}

From source file:org.arquillian.extension.recorder.screenshooter.BlurLevelTestCase.java

@Before
public void init() throws Exception {
    bind(ApplicationScoped.class, ServiceLoader.class, serviceLoader);
    bind(ApplicationScoped.class, ScreenshooterConfiguration.class, configuration);
    bind(ApplicationScoped.class, Screenshooter.class, screenshooter);
    bind(ApplicationScoped.class, RecorderStrategyRegister.class, recorderStrategyRegister);

    Mockito.when(screenshooter.getScreenshotType()).thenReturn(ScreenshotType.PNG);

    Mockito.doNothing().when(cleaner).clean(configuration);

    Mockito.when(serviceLoader.onlyOne(ScreenshooterEnvironmentCleaner.class,
            DefaultScreenshooterEnvironmentCleaner.class)).thenReturn(cleaner);

    screenshotFile = folder.newFile("screenshot.png");
    URL resource = BlurLevelTestCase.class.getResource("/arquillian_ui_success_256px.png");
    FileUtils.copyURLToFile(resource, screenshotFile);
    originalSize = (int) screenshotFile.length();
    OUTPUT_FILE = screenshotFile.getAbsoluteFile();
}

From source file:org.artifactory.common.ArtifactoryHome.java

/**
 * Checks the existence of the logback configuration file under the etc directory. If the file doesn't exist this
 * method will extract a default one from the war.
 *///from  ww  w . j  av a2 s.  c  o  m
public File getLogbackConfig() {
    File etcDir = new File(getHomeDir(), "etc");
    File logbackFile = new File(etcDir, LOGBACK_CONFIG_FILE_NAME);
    if (!logbackFile.exists()) {
        try {
            //Copy from default
            URL configUrl = ArtifactoryHome.class.getResource("/META-INF/default/" + LOGBACK_CONFIG_FILE_NAME);
            FileUtils.copyURLToFile(configUrl, logbackFile);
        } catch (IOException e) {
            // we don't have the logger configuration - use System.err
            System.err.printf("Could not create default %s into %s\n", LOGBACK_CONFIG_FILE_NAME, logbackFile);
            e.printStackTrace();
        }
    }
    return logbackFile;
}

From source file:org.artifactory.common.ArtifactoryHome.java

public void writeBundledHomeArtifactoryProperties() {
    File artifactoryPropertiesFile = getHomeArtifactoryPropertiesFile();
    //Copy the artifactory.properties file into the data folder
    try {/*w  w  w  .  j a v  a 2  s  .com*/
        //Copy from default
        FileUtils.copyURLToFile(getDefaultArtifactoryPropertiesUrl(), artifactoryPropertiesFile);
    } catch (IOException e) {
        throw new RuntimeException("Could not copy " + ARTIFACTORY_PROPERTIES_FILE + " to "
                + artifactoryPropertiesFile.getAbsolutePath(), e);
    }
}