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:com.kaikoda.cah.CardGenerator.java

private File generateHTML(Deck deck) {

    this.feedback("Generating HTML...");
    File htmlOutputLocation = null;
    try {/*from w w w  .j a va2 s  .  c  om*/

        String html = deck.toHtml();

        htmlOutputLocation = new File("cards_against_humanity.html");
        FileUtils.writeStringToFile(htmlOutputLocation, html, "UTF-8");

        this.feedback("...file saved:");
        this.feedback(htmlOutputLocation.getAbsolutePath() + "\n");

    } catch (SAXException e) {
        this.feedback("Unable to save cards to file.", true);
    } catch (IOException e) {
        this.feedback("Unable to save cards to file.", true);
    } catch (TransformerException e) {
        this.feedback("Unable to save cards to file.", true);
    } catch (ParserConfigurationException e) {
        this.feedback("Unable to save cards to file.", true);
    }

    this.feedback("Adding a dash of style...");
    try {

        String directoryPath = "assets";

        File outputDirectory = new File(directoryPath);
        outputDirectory.mkdir();

        // TODO: Implement solution that either copies the entire directory
        // or loops through its contents.

        String path = outputDirectory.getName() + File.separator + "style.css";
        FileUtils.copyURLToFile(this.getClass().getResource(File.separator + path), new File(path));

        path = outputDirectory.getName() + File.separator + "branding_on_black.png";
        FileUtils.copyURLToFile(this.getClass().getResource(File.separator + path), new File(path));

        path = outputDirectory.getName() + File.separator + "branding_on_white.png";
        FileUtils.copyURLToFile(this.getClass().getResource(File.separator + path), new File(path));

        path = outputDirectory.getName() + File.separator + "branding_on_black_cards.png";
        FileUtils.copyURLToFile(this.getClass().getResource(File.separator + path), new File(path));

        this.feedback("...file saved:");
        this.feedback(outputDirectory.getAbsolutePath());

    } catch (IOException e) {
        e.printStackTrace();
        this.feedback("Unable to style.  Do it yourself.", true);
    }

    return htmlOutputLocation;

}

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

private File downloadForgeInstaller() throws IOException {
    ForgeBuild forgeBuild;// w  w  w .  j a  va  2s  .  c o m
    if (forgeVersion.equalsIgnoreCase("forge-recommended") || forgeVersion.equalsIgnoreCase("forge-latest"))
        forgeBuild = forgeJson.number.get(
                String.valueOf(forgeJson.promos.get(forgeVersion.replace("forge", manifest.manifestVersion))));
    else
        forgeBuild = forgeJson.number.get(forgeVersion.substring(forgeVersion.lastIndexOf('.') + 1));
    if (forgeBuild == null) {
        logger.println("ERROR Forge version: " + forgeVersion + " something random went wrong.");
        return null;
    }

    for (ForgeFile file : forgeBuild.files) {
        if (file.type.equalsIgnoreCase("installer")) {
            StringBuilder urlString = new StringBuilder(
                    "http://files.minecraftforge.net/maven/net/minecraftforge/forge/")
                            .append(forgeBuild.mcversion).append('-').append(forgeBuild.version);
            if (forgeBuild.branch != null)
                urlString.append('-').append(forgeBuild.branch);
            urlString.append('/').append(forgeJson.artifact).append('-').append(forgeBuild.mcversion)
                    .append('-').append(forgeBuild.version);
            if (forgeBuild.branch != null)
                urlString.append('-').append(forgeBuild.branch);
            urlString.append('-').append(file.type).append('.').append(file.extention);
            URL url = new URL(urlString.toString());
            File installer = new File(output, FilenameUtils.getName(url.getFile()));
            FileUtils.copyURLToFile(url, installer);
            return installer;
        }
    }

    logger.println("ERROR Forge version: " + forgeVersion + " has no installer");
    return null;
}

From source file:com.bitplan.rest.RestServerImpl.java

/**
 * get the given Store/*from   w  ww . j  a  v  a2  s .  c  om*/
 * 
 * @param type
 * @param name
 * @return the store file
 * @throws IOException
 */
public File getStoreFile(String type, String name) throws IOException {
    final ClassLoader cl = RestServerImpl.class.getClassLoader();
    URL surl = cl.getResource(name);
    File result = null;
    if (surl != null) {
        LOGGER.log(Level.WARNING, "getting " + type + " from " + surl.toString());
        result = File.createTempFile(name, ".tmp");
        FileUtils.copyURLToFile(surl, result);
    } else {
        LOGGER.log(Level.WARNING, "could not get " + type + " from resource " + name);
    }
    return result;
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.main.SmartDeploymentService.java

@POST
@Path("/CAMFTosca/enrich/CSAR/{serviceName}")
@Consumes(MediaType.TEXT_PLAIN)/*w w w .  j  a va 2 s  .co  m*/
@Produces(MediaType.TEXT_PLAIN)
public String enrich_CAMF_CSAR(String csarURL, @PathParam("serviceName") String serviceName) {
    SalsaConfiguration.getArtifactStorage();
    // download the CSAR
    String csarTmp = SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + ".csar";
    try {
        FileUtils.copyURLToFile(new URL(csarURL), new File(csarTmp));
        return enrich_CAMF_CSAR_Process(csarTmp, serviceName);
    } catch (IOException ex) {
        EngineLogger.logger.error("Fail to download CSAR file at URL: {} and save to {}", csarURL, csarTmp, ex);
        return null;
    }
}

From source file:com.t3.model.AssetManager.java

/**
 * Create an asset from a file.//from ww  w  .  j  a  va2s  .c  o  m
 * 
 * @param file
 *            File to use for asset
 * @return Asset associated with the file
 * @throws IOException
 */
public static Asset createAsset(URL url) throws IOException {
    // Create a temporary file from the downloaded URL
    File newFile = File.createTempFile("remote", null, null);
    try {
        FileUtils.copyURLToFile(url, newFile);
        if (!newFile.exists() || newFile.length() < 20)
            return null;
        Asset temp = new Asset(FileUtil.getNameWithoutExtension(url), FileUtils.readFileToByteArray(newFile));
        return temp;
    } finally {
        newFile.delete();
    }
}

From source file:com.ssn.listener.SSNHiveAlbumSelectionListner.java

private void getAlbumMedia(String accessToken, int pageCount, SSNAlbum album) {
    try {//from w ww .j  a v a 2s . c om
        String urlString = SSNConstants.SSN_WEB_HOST + "api/albums/view/%s/page:%s.json";
        URL url = new URL(String.format(urlString, album.getId(), pageCount));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String input = "access_token=%s";
        input = String.format(input, URLEncoder.encode(accessToken, "UTF-8"));

        OutputStream os = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(os, "UTF-8");
        writer.write(input);
        writer.close();
        os.close();

        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;
            StringBuilder response = new StringBuilder();

            while ((output = br.readLine()) != null) {
                response.append(output);
            }
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> outputJSON = mapper.readValue(response.toString(), Map.class);

            boolean success = (Boolean) outputJSON.get("success");
            if (success) {
                List<Map<String, Object>> mediaFileListJSON = (List<Map<String, Object>>) outputJSON
                        .get("MediaFile");
                ssnHiveAlbumAllMedia = new HashMap<String, SSNAlbumMedia>();
                if (mediaFileListJSON.size() > 0) {
                    for (Map<String, Object> mediaFileJSON : mediaFileListJSON) {
                        SSNAlbumMedia ssnAlbumMedia = mapper.readValue(mapper.writeValueAsString(mediaFileJSON),
                                SSNAlbumMedia.class);
                        String name = "";
                        String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;

                        final List<String> videoSupportedList = Arrays.asList(videoSupported);
                        String fileType = ssnAlbumMedia.getFile_type()
                                .substring(ssnAlbumMedia.getFile_type().lastIndexOf("/") + 1,
                                        ssnAlbumMedia.getFile_type().length())
                                .toUpperCase();

                        if (videoSupportedList.contains(fileType)) {
                            name = ssnAlbumMedia.getFile_name();
                        } else {
                            name = ssnAlbumMedia.getThumbnail().substring(
                                    ssnAlbumMedia.getThumbnail().lastIndexOf("/") + 1,
                                    ssnAlbumMedia.getThumbnail().length());
                        }

                        File mediaFile = new File(
                                SSNHelper.getSsnTempDirPath() + album.getName() + File.separator + name);
                        ssnHiveAlbumAllMedia.put(name, ssnAlbumMedia);

                        int lastModificationComparision = -1;
                        if (mediaFile.exists()) {
                            String mediaFileModifiedDate = SSNDao.getSSNMetaData(mediaFile.getAbsolutePath())
                                    .getModiFied();
                            String ssnMediaModifiedDate = ssnAlbumMedia.getModified();
                            lastModificationComparision = compareDates(mediaFileModifiedDate,
                                    ssnMediaModifiedDate);
                        }

                        if ((!mediaFile.exists() && !ssnAlbumMedia.isIs_deleted())
                                || (lastModificationComparision < 0)) {
                            if (ssnAlbumMedia.getFile_url() != null && !ssnAlbumMedia.getFile_url().isEmpty()
                                    && !ssnAlbumMedia.getFile_url().equalsIgnoreCase("false")) {
                                try {
                                    URL imageUrl = null;
                                    if (videoSupportedList.contains(fileType)) {
                                        imageUrl = new URL(ssnAlbumMedia.getFile_url().replaceAll(" ", "%20"));
                                    } else {
                                        imageUrl = new URL(ssnAlbumMedia.getThumbnail().replaceAll(" ", "%20"));
                                    }
                                    FileUtils.copyURLToFile(imageUrl, mediaFile);
                                } catch (IOException e) {
                                    logger.error(e);
                                }
                            }
                        }
                    }
                }

                Map<String, Object> pagingJSON = (Map<String, Object>) outputJSON.get("paging");
                if (pagingJSON != null) {
                    boolean hasNextPage = Boolean.parseBoolean(pagingJSON.get("nextPage") + "");
                    if (hasNextPage) {
                        getAlbumMedia(accessToken, ++pageCount, album);
                    }
                }
            }
        }

    } catch (EOFException e) {
        logger.error(e);
        SSNMessageDialogBox dialogBox = new SSNMessageDialogBox();
        dialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                "No Response from server.");
    } catch (Exception ee) {
        logger.error(ee);
    }
}

From source file:com.taobao.android.builder.tools.ideaplugin.ApDownloader.java

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);/* w ww.  j a  v a2s  .c o  m*/
    }

    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;

}

From source file:deincraftlauncher.InstallController.java

private void createGameDir(String Path) {

    System.out.println("filling DC Dir");

    new File(Path).mkdirs();
    try {/* w  ww .  j  a  v  a2s. c om*/
        URL inputUrl = getClass().getResource("/deincraftlauncher/Images/DCInstall.zip");
        String zipFile = Path + "DCInstall.zip";
        File dest = new File(zipFile);
        FileUtils.copyURLToFile(inputUrl, dest);
        extractArchive(zipFile, Path);
    } catch (Exception ex) {
        System.err.println("unable to create game directory " + ex);
        ex.printStackTrace();
    }

}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * Keystore file needs to be in place in order for c3pr to validate the
 * certificate./*w  w w  .jav  a 2 s. c o  m*/
 * 
 * @throws IOException
 */
private void prepareServiceKeystore() throws IOException {
    // In case this test is running on a developer's machine, keystore file
    // might already be present
    // and this test will overwrite it because the keystore file path at
    // this point is still hardcoded.
    // So if we find an existent file, we will try to save it and restore
    // later upon tearing down.
    // tearDown() might never get called, so there is still a risk of
    // loosing a developer's original keystore file.

    backupKeystoreFileIfNeeded();

    File keystoreFile = new File(SERVICE_KEYSTORE_FILE);
    logger.info("Creating " + keystoreFile.getCanonicalPath());
    FileUtils.copyURLToFile(
            C3PREmbeddedTomcatTestBase.class.getResource(TESTDATA + "/" + SERVICE_KEYSTORE_BASENAME),
            keystoreFile);

}

From source file:dynamicrefactoring.util.io.FileManager.java

/**
 * Copia un directorio empaquetado en el plugin en un directorio del sistema
 * de ficheros.//from   w ww  .ja  v a 2 s.c  o m
 * 
 * @param bundleDir ruta del directorio en el bundle
 * @param fileSystemDir ruta del directorio del sistema
 * @throws IOException si ocurre algun problema al acceder a las rutas
 */
public static void copyBundleDirToFileSystem(String bundleDir, String fileSystemDir) throws IOException {
    final Bundle bundle = Platform.getBundle(RefactoringPlugin.BUNDLE_NAME);
    final Enumeration<?> entries = bundle.findEntries(FilenameUtils.separatorsToUnix(bundleDir), "*", true);
    final List<?> lista = Collections.list(entries);
    for (Object entrada : lista) {
        URL entry = (URL) entrada;
        File fichero = new File(entry.getFile());
        if (!entry.toString().endsWith("/")) {
            FileUtils.copyURLToFile(entry, new File(fileSystemDir + entry.getFile()));

        }
    }
}