Java Code Examples for org.apache.commons.io.FileUtils.copyURLToFile()

The following are Jave code examples for showing how to use copyURLToFile() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sonar-ps-plugin   File: TokenizerSensorTest.java   View Source Code Vote up 6 votes
@Test
public void testExecute() throws IOException, InterruptedException {

	File baseFile = folder.newFile("test.ps1");

	FileUtils.copyURLToFile(getClass().getResource("/testFiles/test.ps1"), baseFile);

	DefaultFileSystem fs = new DefaultFileSystem(folder.getRoot());
	DefaultInputFile ti = new DefaultInputFile("test", "test.ps1");
	ti.initMetadata(new String(Files.readAllBytes(baseFile.toPath())));
	ti.setLanguage(PowershellLanguage.KEY);
	fs.add(ti);

	SensorContextTester ctxTester = SensorContextTester.create(folder.getRoot());
	ctxTester.setFileSystem(fs);
	TokenizerSensor s = new TokenizerSensor(new Settings(), temp);
	s.execute(ctxTester);
	Assert.assertEquals(16, ctxTester.cpdTokens("test:test.ps1").size());
	Assert.assertEquals(1, ctxTester.highlightingTypeAt("test:test.ps1", 1, 5).size());

}
 
Example 2
Project: OneClient   File: MinecraftUtil.java   View Source Code Vote up 6 votes
public static void resolveAssets(Version versionData) throws Throwable {
	Version.AssetIndex assetIndex = versionData.assetIndex;
	File assetsInfo = new File(ASSETS, "indexes" + File.separator + assetIndex.id + ".json");
	FileUtils.copyURLToFile(new URL(assetIndex.url), assetsInfo);
	AssetIndex index = new Gson().fromJson(new FileReader(assetsInfo), AssetIndex.class);
	Map<String, AssetObject> parent = index.getFileMap();
	i = 0;
	count = parent.entrySet().size();
	NotifyUtil.setProgress(-1);
	NotifyUtil.setText("Resolving %s Minecraft Assets", count);
	parent.entrySet().parallelStream().forEach(entry -> {
		AssetObject object = entry.getValue();
		String sha1 = object.getHash();
		File file = new File(ASSETS, "objects" + File.separator + sha1.substring(0, 2) + File.separator + sha1);
		NotifyUtil.setProgressAscend(i++, count);
		if (!file.exists() || !MiscUtil.checksumEquals(file, sha1)) {
			OneClientLogging.info("Downloading asset " + entry.getKey() + " from " + Constants.RESOURCES_BASE + sha1.substring(0, 2) + "/" + sha1 + " to " + file);
			try {
				FileUtils.copyURLToFile(new URL(Constants.RESOURCES_BASE + sha1.substring(0, 2) + "/" + sha1), file);
				FileUtils.copyURLToFile(new URL(Constants.RESOURCES_BASE + sha1.substring(0, 2) + "/" + sha1), file);
			} catch (IOException e) {
				OneClientLogging.error(e);
			}
		}
	});
}
 
Example 3
Project: gw2_launcher   File: FastUpdater.java   View Source Code Vote up 6 votes
public void downloadINI(){
  	File ini=new File(path+"\\bin64\\arcdps.ini");
  	if (ini.exists()) ini.delete(); //Delete existing ini file to prevent an exception
  	log.log( Level.INFO,"Downloading configuration file");
  	try {
  		//Download default configuration from the website
	FileUtils.copyURLToFile(new URL("http://www.deltaconnected.com/arcdps/x64/arcdps.ini"),ini, 10000, 10000);
	log.log( Level.INFO,"archdps.ini installed successfully");
	//Exceptions if something goes wrong (Connection/IO)
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	cf.status.setText("  Cannot connect to the update server");
          cf.status.setForeground(Color.RED);
          log.log( Level.SEVERE,"IOException when downloading ini");
}

  }
 
Example 4
Project: gw2_launcher   File: Operations.java   View Source Code Vote up 6 votes
public static synchronized void downloadINI(CoreFrame cf, String path){
Operations.LogSetup(log,true);
  	File ini=new File(path+"\\bin64\\arcdps.ini");
  	if (ini.exists()) ini.delete();     	//Delete existing ini file to prevent an exception
  	log.log( Level.INFO,"Downloading configuration file");
  	try {
  		//Download default configuration from the website
	FileUtils.copyURLToFile(new URL("http://www.deltaconnected.com/arcdps/x64/arcdps.ini"),ini, 10000, 10000);
	log.log( Level.INFO,"archdps.ini installed successfully");
//Exceptions if something goes wrong (Connection/IO)
  	} catch (IOException e) {
	
	e.printStackTrace();
	cf.status.setText("- Cannot connect to the update server");
          cf.status.setForeground(Color.RED);
          log.log( Level.SEVERE,"IOException when downloading ini");
}
  	Operations.closeLogHandlers(log);
  }
 
Example 5
Project: WurstSDK   File: GuiInstallScreen.java   View Source Code Vote up 6 votes
@Override
public void run() {
    if (artifact.endsWith(".jar")) {
        artifact = artifact.replaceAll("jar", "wpk");
    } else
        artifact += ".wpk";
    File pluginFile = new File("plugins", artifact);
    try {
        FileUtils.copyURLToFile(url, pluginFile);
        ((WurstSDK) SDK.getClient()).getPluginManager().installPlugin(pluginFile, token);
    } catch (IOException e) {
        message = "Failed to download!: " + e.getMessage();
    }
    prevScreen.updateScreen();
    mc.displayGuiScreen(prevScreen);
}
 
Example 6
Project: OneClient   File: ForgeUtils.java   View Source Code Vote up 6 votes
public static JarFile downloadForgeJar(File versionsDir, String mcVer, String forgeVer) throws IOException {
	ForgeVersions.ForgeVersion version = getForgeVersion(forgeVer);
	String jarName = getForgeJar(mcVer, forgeVer, null);
	File forgeJar = new File(Constants.TEMPDIR, jarName);
	File forgeSHA1 = new File(Constants.TEMPDIR, jarName + ".sha1");
	if(forgeJar.exists() && forgeSHA1.exists()){
		if(MiscUtil.checksumEquals(forgeJar, FileUtils.readFileToString(forgeSHA1, StandardCharsets.UTF_8))){
			return new JarFile(forgeJar);
		}
	}
	OneClientLogging.logger.info("Downloading forge jar to " + versionsDir.getAbsolutePath());
	if (version.branch != null && !version.branch.isEmpty()) {
		jarName = getForgeJar(mcVer, forgeVer, version.branch);
	}
	URL forgeSHA1URL = new URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/" + jarName + ".sha1");
	URL forgeJarURL = new URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/" + jarName);
	FileUtils.copyURLToFile(forgeSHA1URL, forgeSHA1);
	FileUtils.copyURLToFile(forgeJarURL, forgeJar);
	return new JarFile(forgeJar);
}
 
Example 7
Project: SuitAgent   File: Update.java   View Source Code Vote up 6 votes
/**
 * 下载更新文件
 * @return
 */
private boolean downloadUpdatePack(){
    try {
        URL url = new URL(downloadUrl);

        File f = new File(updateDownloadFilePath);
        log.info("{}downloading update file from {} ...",log4UpdateStart,downloadUrl);
        FileUtils.copyURLToFile(url, f);
        log.info("{}update file download completed!",log4UpdateStart);
        File zipDownloadFile = new File(updateFilesTempDir);
        if(zipDownloadFile.exists()){
            FileUtils.deleteDirectory(zipDownloadFile);
        }
        log.info("{}unpack update file to {}",log4UpdateStart,updateFilesTempDir);
        ZipUtil.unzip(updateDownloadFilePath, updateFilesTempDir);

        if(f.delete()){
            log.info("{}delete temp file {}",log4UpdateStart,updateDownloadFilePath);
        }
    } catch (Exception e) {
        log.info("{}download update file <FAILED>",log4UpdateStart,e);
        return false;
    }
    return true;
}
 
Example 8
Project: MoMuOSB   File: WebClient.java   View Source Code Vote up 6 votes
/**
 * Download file from url.
 * 
 * @param url The url you want to download from.
 * @param target The target-file.
 * @return boolean
 */
public static boolean downloadFile( String url, File target )
{
    try
    {

        //Run download.
        FileUtils.copyURLToFile( new URL( url ), target );
                
        //Success.
        return true;
        
    }
    catch ( Exception ex )
    {
        
        //Post fail message.
        Console.debug( "Failed to download \"" + url + "\" to " + target.getPath() );

        
        //Failed.
        return false;
        
    }
}
 
Example 9
Project: Hydroangeas   File: Configuration.java   View Source Code Vote up 5 votes
public void createDefaultConfiguration()
{
    try
    {
        File destinationFile = new File(MiscUtils.getJarFolder(), "config.json");
        FileUtils.copyURLToFile(Configuration.class.getResource("/config.json"), destinationFile);
    } catch (IOException e)
    {
        e.printStackTrace();
    }

    this.instance.log(Level.INFO, "Default configuration file created.");
    System.exit(3);
}
 
Example 10
Project: OneClient   File: MinecraftUtil.java   View Source Code Vote up 5 votes
public static void installMinecraft(Instance instance) throws Throwable {
	instance.setInstalling(true);
	NotifyUtil.setText("Installing minecraft for " + instance.getName());
	OneClientTracking.sendRequest("minecraft/install/" + instance.getGameVersion());

	Version versionData = getVersion(instance.getGameVersion());

	if (versionData == null) {
		OneClientLogging.error("Unknown Game Version! Please Notify the Devs!");
		return;
	}

	File mcJar = new File(VERSIONS, instance.getGameVersion() + ".jar");

	OneClientLogging.logger.info("Downloading Minecraft jar");
	if (!MiscUtil.checksumEquals(mcJar, versionData.downloads.get("client").sha1)) {
		FileUtils.copyURLToFile(new URL(versionData.downloads.get("client").url), mcJar);
	}

	installLibraries(versionData);

	File natives = new File(VERSIONS, "natives-" + instance.gameVersion);
	extractNatives(natives, versionData);
	resolveAssets(versionData);

	if (!instance.getForgeVersion().isEmpty())
		ForgeUtils.resolveForgeLibrarys(instance.getGameVersion(), instance.getForgeVersion());

	OneClientLogging.logger.info("Done minecraft files are all downloaded");
	instance.setInstalling(false);
	NotifyUtil.clear();
}
 
Example 11
Project: pysonar2   File: Parser.java   View Source Code Vote up 5 votes
private void startPythonProcesses()
{
    if (python2Process != null)
    {
        python2Process.destroy();
    }
    if (python3Process != null)
    {
        python3Process.destroy();
    }

    // copy dump_python.py to temp dir
    try
    {
        URL url = Thread.currentThread().getContextClassLoader().getResource(dumpPythonResource);
        FileUtils.copyURLToFile(url, new File(jsonizer));
    } catch (Exception e)
    {
        $.die("Failed to copy resource file:" + dumpPythonResource);
    }

    python2Process = startInterpreter(PYTHON2_EXE);
    if (python2Process != null)
    {
        $.msg("started: " + PYTHON2_EXE);
    }

    python3Process = startInterpreter(PYTHON3_EXE);
    if (python3Process != null)
    {
        $.msg("started: " + PYTHON3_EXE);
    }

    if (python2Process == null && python3Process == null)
    {
        $.die("You don't seem to have either of Python or Python3 on PATH");
    }
}
 
Example 12
Project: sagiri   File: Config.java   View Source Code Vote up 5 votes
public Config() throws Exception {
    configFile = new File("config.json");
    if(!configFile.exists()) {
        URL configResource = getClass().getClassLoader().getResource("config.json");
        FileUtils.copyURLToFile(configResource, configFile);
    }

    FileReader reader = new FileReader(configFile);
    json = new JSONObject(IOUtils.toString(reader));
    reader.close();
}
 
Example 13
Project: Word2VecfJava   File: CNNSentenceClassification.java   View Source Code Vote up 5 votes
public static void aclImdbDownloader(String DATA_URL, String DATA_PATH) {
    try {
        //Create directory if required
        File directory = new File(DATA_PATH);
        if (!directory.exists()) directory.mkdir();
        //Download file:
        String archivePath = DATA_PATH + "aclImdb_v1.tar.gz";
        File archiveFile = new File(archivePath);
        String extractedPath = DATA_PATH + "aclImdb";
        File extractedFile = new File(extractedPath);

        if (!archiveFile.exists()) {
            System.out.println("Starting data download (80MB)...");
            FileUtils.copyURLToFile(new URL(DATA_URL), archiveFile);
            System.out.println("Data (.tar.gz file) downloaded to " + archiveFile.getAbsolutePath());
            //Extract tar.gz file to output directory
            extractTarGz(archivePath, DATA_PATH);
        } else {
            //Assume if archive (.tar.gz) exists, then data has already been extracted
            System.out.println("Data (.tar.gz file) already exists at " + archiveFile.getAbsolutePath());
            if (!extractedFile.exists()) {
                //Extract tar.gz file to output directory
                extractTarGz(archivePath, DATA_PATH);
            } else {
                System.out.println("Data (extracted) already exists at " + extractedFile.getAbsolutePath());
            }
        }
    } catch(IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: monarch   File: StatArchiveWithConsecutiveResourceInstGeneratorTest.java   View Source Code Vote up 5 votes
@Before
public void setUpGeneratorTest() throws Exception {
  URL url = getClass().getResource(ARCHIVE_FILE_NAME);
  File testFolder = this.temporaryFolder.newFolder(getClass().getSimpleName());
  this.expectedStatArchiveFile = new File(testFolder, ARCHIVE_FILE_NAME);
  FileUtils.copyURLToFile(url, this.expectedStatArchiveFile);
}
 
Example 15
Project: monarch   File: DtdResolver.java   View Source Code Vote up 5 votes
@Deprecated
public InputSource resolveEntity(String publicId, String systemId) throws IOException {
  if (!isHttpUrlOK(systemId)) {
    URL dtdURL = getClass().getResource(CacheXml.LATEST_DTD_LOCATION);
    File dtd = new File(DistributionConfig.GEMFIRE_PREFIX + "dtd");
    FileUtils.copyURLToFile(dtdURL, dtd);
    InputSource inputSource = new InputSource(FileUtils.openInputStream(dtd));
    FileUtils.deleteQuietly(dtd);
    return inputSource;
  } else {
    return null;
  }
}
 
Example 16
Project: esct-messenger-bot   File: ImageParser.java   View Source Code Vote up 5 votes
public static File urlToFile(String url, String path) throws IOException {
    URL imageURL = new URL(url);
    File f =new File(path);
    f.createNewFile();

    FileUtils.copyURLToFile(imageURL, f);

    return f;
}
 
Example 17
Project: NapBot   File: NapchartHandler.java   View Source Code Vote up 5 votes
static synchronized File downloadNapchart(String chart, File f) throws IOException
{
	if (f.exists())
	{
		charts.add(chart);
		return f;
	}
	else
	{
		try
		{
			/*
			driver.get("https://napchart.com/" + chart);
			File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
			*/
			File screenshot = File.createTempFile("napchart", "png");
			FileUtils.copyURLToFile(new URL("https://napchart.com/api/getImage?chartid=" + chart + "&width=600&height=600&shape=circle"), screenshot);
			BufferedImage image = ImageIO.read(screenshot);
			screenshot.delete();
			/*
			WebElement canvas = driver.findElement(By.className("canvas"));
			Point canvasLocation = canvas.getLocation();
			int canvasWidth = canvas.getSize().getWidth();
			int canvasHeight = canvas.getSize().getHeight();
			BufferedImage eleScreenshot = image.getSubimage(canvasLocation.getX(), canvasLocation.getY(), canvasWidth, canvasHeight);
			*/
			BufferedImage eleScreenshot = image.getSubimage(20, 0, 560, 600); // slight edge crop
			ImageIO.write(eleScreenshot, "png", f);
			charts.add(chart);
		}
		catch (Throwable t)
		{
			throw new IOException("Failed to download image from napchart.com", t);
		}
	}
	return f;
}
 
Example 18
Project: dlface   File: Util.java   View Source Code Vote up 5 votes
public static void copyURLToFile(URL source, File destination, Proxy proxy) throws IOException {
    if(proxy == null) {
        FileUtils.copyURLToFile(source, destination);
    } else {
        downloadUsingProxy(source, destination, proxy);
    }
}
 
Example 19
Project: EMC-Installer   File: Utils.java   View Source Code Vote up 4 votes
public static void getInit(File output, String targetPatch) throws IOException {
	URL url = new URL("https://github.com/Moudoux/EMC-Installer/blob/master/init/" + targetPatch + "?raw=true");
	FileUtils.copyURLToFile(url, output);
}
 
Example 20
Project: atlas   File: ApDownloader.java   View Source Code Vote up 3 votes
public static File downloadAP(String mtlConfigUrl, File root) throws Exception {

        Pattern p = Pattern.compile("buildConfigId=(\\d+)");
        Matcher m = p.matcher(mtlConfigUrl);

        String configId = "";

        if (m.find()) {
            configId = m.group(1);
        }

        String apiUrl = "http://" +
                AtlasBuildContext.sBuilderAdapter.tpatchHistoryUrl + "/rpc/androidPlugin/getAp.json?buildConfigId=" + configId;

        URL api = new URL(apiUrl);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(api.openStream()));

        String inputLine = in.readLine();
        in.close();

        String downloadUrl = inputLine.trim().replace("\"", "").replace("\\", "");

        File file = new File(root, MD5Util.getMD5(downloadUrl) + ".ap");
        if (file.exists()) {
            return file;
        }

        URL downloadApi = new URL(downloadUrl);
        System.out.println("start to download ap from " + downloadUrl);

        File tmpFile = new File(file.getParentFile(), String.valueOf(System.currentTimeMillis()));

        FileUtils.copyURLToFile(downloadApi, file);
        return file;

    }