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.forgerock.doc.maven.PreSiteBuildMojo.java

/**
 * Copy fonts needed to the project build directory.
 *
 * @throws MojoExecutionException Copy failed
 *///from   w  ww .  j av a2  s. co m
final void copyFonts() throws MojoExecutionException {
    // If you update this method, also see buildFO().
    String[] fonts = { "/fonts/DejaVuSans-Oblique.ttf", "/fonts/DejaVuSans.ttf",
            "/fonts/DejaVuSansCondensed-Bold.ttf", "/fonts/DejaVuSansCondensed-BoldOblique.ttf",
            "/fonts/DejaVuSansMono-Bold.ttf", "/fonts/DejaVuSansMono-BoldOblique.ttf",
            "/fonts/DejaVuSansMono-Oblique.ttf", "/fonts/DejaVuSansMono.ttf", "/fonts/DejaVuSerif-Italic.ttf",
            "/fonts/DejaVuSerif.ttf", "/fonts/DejaVuSerifCondensed-Bold.ttf",
            "/fonts/DejaVuSerifCondensed-BoldItalic.ttf" };

    for (String font : fonts) {
        URL src = getClass().getResource(font);
        File dest = new File(getBuildDirectory() + font.replaceAll("/", File.separator));
        try {
            FileUtils.copyURLToFile(src, dest);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to copy file: " + font + "\n" + e.getMessage());
        }
    }
}

From source file:org.forgerock.doc.maven.PreSiteBuildMojo.java

/**
 * Add SyntaxHighlighter JavaScript files in each HTML document source directory.
 *
 * @throws MojoExecutionException Failed to add scripts.
 *//*from w w w . j a  va 2s . c  o  m*/
void addShScripts() throws MojoExecutionException {

    final Set<String> docNames = DocUtils.getDocumentNames(sourceDirectory, getDocumentSrcName());
    if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
    }

    for (String scriptName : shJavaScriptFiles) {
        URL scriptUrl = getClass().getResource("/js/" + scriptName);

        // The html.script parameter should probably take URLs.
        // When local files are referenced,
        // the DocBook XSL stylesheets do not copy the .js files.
        // Instead the files must be copied to the output directories.
        final String[] outputDirectories = { "",
                File.separator + FilenameUtils.getBaseName(getDocumentSrcName()) };

        for (final String outputDirectory : outputDirectories) {

            for (final String docName : docNames) {

                final File parent = new File(getDocbkxOutputDirectory(),
                        "html" + File.separator + docName + outputDirectory + File.separator + "sh");
                final File scriptFile = new File(parent, scriptName);

                try {
                    FileUtils.copyURLToFile(scriptUrl, scriptFile);
                } catch (IOException ie) {
                    throw new MojoExecutionException("Failed to write to " + scriptFile.getPath(), ie);
                }
            }
        }
    }
}

From source file:org.forgerock.doc.maven.PreSiteBuildMojo.java

/**
 * Add SyntaxHighlighter CSS files in each HTML document source directory.
 *
 * @throws MojoExecutionException Failed to add scripts.
 *//*from  ww w .j a va2 s .  c  o  m*/
void addShCss() throws MojoExecutionException {

    final Set<String> docNames = DocUtils.getDocumentNames(sourceDirectory, getDocumentSrcName());
    if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
    }

    for (String styleSheetName : shCssFiles) {
        URL styleSheetUrl = getClass().getResource("/css/" + styleSheetName);

        // The html.stylesheet parameter should probably take URLs.
        // When local files are referenced,
        // the DocBook XSL stylesheets do not copy the .css files.
        // Instead the files must be copied to the output directories.
        final String[] outputDirectories = { "",
                File.separator + FilenameUtils.getBaseName(getDocumentSrcName()) };

        for (final String outputDirectory : outputDirectories) {

            for (final String docName : docNames) {

                final File parent = new File(getDocbkxOutputDirectory(),
                        "html" + File.separator + docName + outputDirectory + File.separator + "sh");
                final File styleSheetFile = new File(parent, styleSheetName);

                try {
                    FileUtils.copyURLToFile(styleSheetUrl, styleSheetFile);
                } catch (IOException ie) {
                    throw new MojoExecutionException("Failed to write to " + styleSheetFile.getPath(), ie);
                }
            }
        }
    }
}

From source file:org.forgerock.doc.maven.SiteBuildMojo.java

/**
 * {@inheritDoc}/*  w w w .j  ava 2 s.c  o m*/
 */
@Override
public final void execute() throws MojoExecutionException {
    Executor exec = new Executor();
    getLog().info("Laying out site...");
    exec.layout();

    getLog().info("Adding .htaccess file...");
    String layoutDir = getSiteDirectory().getPath() + File.separator + "doc";
    File htaccess = new File(getBuildDirectory().getPath() + File.separator + ".htaccess");
    FileUtils.deleteQuietly(htaccess);
    try {
        FileUtils.copyURLToFile(getClass().getResource("/.htaccess"), htaccess);
        HTMLUtils.addHtaccess(layoutDir, htaccess);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to copy .htaccess: " + e.getMessage());
    }

    getLog().info("Add redirect to docs.html under layout directory...");
    try {
        File file = new File(
                getSiteDirectory().getPath() + File.separator + "doc" + File.separator + "index.html");
        if (!file.exists()) {
            String redirect = IOUtils.toString(getClass().getResourceAsStream("/index.html"), "UTF-8");
            redirect = redirect.replaceAll("PROJECT", getProjectName()).replaceAll("LOWERCASE",
                    getProjectName().toLowerCase());
            FileUtils.write(file, redirect, "UTF-8");
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to copy redirect file: " + e.getMessage());
    }

    // Test links in document source, and generate a report.
    if (!runLinkTester().equalsIgnoreCase("false")) {
        getLog().info("Running linktester...");
        exec.testLinks();
    }
}

From source file:org.fseek.simon.swing.filetree.dnd.FileTransferHandler.java

private File[] getFromURL(Transferable transferable) {
    try {//from  w  ww.j  av a2 s  .c o m
        java.net.URL url = (java.net.URL) transferable.getTransferData(urlFlavor);
        File tmpFile = new File(FileUtils.getTempDirectory(), url.getFile());
        FileUtils.copyURLToFile(url, tmpFile);
        return new File[] { tmpFile };
    } catch (UnsupportedFlavorException | IOException ex) {
        //Logger.getLogger(FileTransferhandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.fuin.kickstart4j.ConfigUpdater.java

/**
 * Copies the remote file to a local file and informs the listener.
 * /*from w  w w .  j  a  va2s.  c o  m*/
 * @param remoteFile
 *            Remote file to copy.
 * @param file
 *            Target file.
 * @param nr
 *            Current file number.
 * @param max
 *            Total files.
 * 
 * @throws IOException
 *             Error while copying.
 */
private void copyToFile(final RemoteFile remoteFile, final File file, final int nr, final int max)
        throws IOException {

    try {
        FileUtils.copyURLToFile(remoteFile.getSrcFileUrl(), file);
        listener.onCopy(remoteFile, file, nr, max);
    } catch (final FileNotFoundException ex) {
        if (remoteFile.isErrorIfNotFound()) {
            throw ex;
        } else {
            listener.onNotFound(remoteFile, file, nr, max);
        }
    }

}

From source file:org.fuin.kickstart4j.Utils.java

/**
 * Copies bytes from the URL source to a file destination. The directories
 * up to destination will be created if they don't already exist.
 * destination will be overwritten if it already exists. Possible
 * <code>IOException</code>s are wrapped into <code>RuntimeException</code>.
 * /*from ww w .  jav  a 2s  .  co  m*/
 * @param url
 *            The URL to copy bytes from, must not be <code>null</code>. A
 *            possible <code>MalformedURLException</code> when converting
 *            this argument into an URL is wrapped into a
 *            <code>RuntimeException</code>.
 * @param file
 *            The non-directory File to write bytes to (possibly
 *            overwriting), must not be <code>null</code>.
 */
public static void copyURLToFile(final String url, final File file) {
    try {
        FileUtils.copyURLToFile(new URL(url), file);
    } catch (final IOException ex) {
        throw new RuntimeException("Error copying URL to file!", ex);
    }
}

From source file:org.geopublishing.atlasViewer.AtlasConfig.java

/**
 * Copies bytes from the URL <code>source</code> to a file
 * <code>destination</code>. The directories up to <code>destination</code>
 * will be created if they don't already exist. <code>destination</code>
 * will be overwritten if it already exists.
 * //from  w ww  .  j a v  a2 s  .  co m
 * If an IO error occurs during copying it is not thrown!
 */
public static void exportURLtoFileNoEx(URL source, File dest) {
    try {
        FileUtils.copyURLToFile(source, dest);
    } catch (IOException e) {
    }
}

From source file:org.geopublishing.atlasViewer.AVProps.java

/**
 * Deletes the .properties in the ApplicationPreferences directory creates a
 * default geopublisher.properties from the one saved in the jar. The new
 * .properties are automatically loaded.
 * // www  .  jav  a 2 s .co m
 * @param guiOwner
 *            If not <code>null</code> a JDialog message will inform the
 *            user.
 * @author <a href="mailto:skpublic@wikisquare.de">Stefan Alfons Tzeggai</a>
 */
public void resetProperties(final Component guiOwner) {

    // Delete the old one
    getPropertiesFile().delete();

    // Create the new one
    LOGGER.info("Resetting " + getPropertiesFile().getAbsolutePath());
    // If we don't have a .properties file, we copy the one from the jar
    URL inJar = null;
    try {
        inJar = atlasConfig.getResource("/" + PROPERTIESFILE_RESOURCE_NAME);
        // LOGGER.debug("inJar = " + inJar);

        if (inJar == null)
            throw new RuntimeException("Can't find original av.properties");

        FileUtils.copyURLToFile(inJar, getPropertiesFile());

        /**
         * After creating the new default file, we may not forget to read it
         * ;-)
         */
        properties.load(new FileInputStream(getPropertiesFile()));

        if (guiOwner != null) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JOptionPane.showMessageDialog(guiOwner, "A default " + propertiesFilename
                            + " file has been created in " + getPropertiesFile().getAbsolutePath());
                }
            });
        }

    } catch (Exception e1) {
        if (guiOwner != null) {
            ExceptionDialog.show(guiOwner, e1);
        } else {
            LOGGER.error("Can't find original av.properties", e1);
        }
    }

}

From source file:org.geopublishing.atlasViewer.dp.layer.DpLayerRaster_Reader.java

/**
 * Exports the raster file and all related files. Only failure on the main
 * file produces an {@link IOException}//w  ww  . ja  v  a  2s.c  om
 */
@Override
public void exportWithGUI(Component owner) throws IOException {

    AtlasExportTask exportTask = new AtlasExportTask(owner, getTitle().toString()) {

        @Override
        protected Boolean doInBackground() throws Exception {

            setPrefix("Exporting ");

            try {
                // waitDialog.setVisible(false);
                exportDir = AVSwingUtil.selectExportDir(owner, getAtlasConfig());
                // waitDialog.setVisible(true);

                if (exportDir == null) {
                    // The fodler selection was cancelled.
                    return false;
                }

                URL url = AVSwingUtil.getUrl(DpLayerRaster_Reader.this, owner);
                final File file = new File(exportDir, getFilename());

                // ****************************************************************************
                // Copy main file and possibly throw an Exception
                // ****************************************************************************
                publish(file.getAbsolutePath());
                FileUtils.copyURLToFile(AVSwingUtil.getUrl(DpLayerRaster_Reader.this, owner), file);

                // Try to copy pending world files...
                for (WORLD_POSTFIXES pf : GeoImportUtil.WORLD_POSTFIXES.values()) {
                    final File changeFileExt = IOUtil.changeFileExt(file, pf.toString());
                    publish(changeFileExt.getAbsolutePath());
                    AtlasConfig.exportURLtoFileNoEx(IOUtil.changeUrlExt(url, pf.toString()), changeFileExt);
                }

                final File changeFileExt = IOUtil.changeFileExt(file, "prj");
                publish(changeFileExt.getAbsolutePath());
                AtlasConfig.exportURLtoFileNoEx(IOUtil.changeUrlExt(url, "prj"), changeFileExt);
                AtlasConfig.exportURLtoFileNoEx(IOUtil.changeUrlExt(url, "sld"),
                        IOUtil.changeFileExt(file, "sld"));
                // publish("done");
                success = true;
            } catch (Exception e) {
                done();
            }
            return success;
        }

    };
    exportTask.execute();
}