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:de.akquinet.innovation.play.maven.Play2InstallPlayMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (StringUtils.isEmpty(play2version)) {
        throw new MojoExecutionException("play2version configuration parameter is not set");
    }/*from   w ww.  j ava  2  s  . c  om*/
    String debugLogPrefix = "AutoInstall - Play! " + play2version + ' ';
    File play2basedirFile = new File(play2basedir);
    File play2home = new File(play2basedirFile, "play-" + play2version);
    File play2 = new File(play2home, AbstractPlay2Mojo.isWindows() ? "play.bat" : "play");

    // Is the requested Play! version already installed?
    if (play2.isFile() && play2.canExecute()) {

        getLog().info(debugLogPrefix + "is already installed in " + play2home);
        return;

    }

    getLog().info("Play! " + play2version + " download and installation, please be patient ...");
    File zipFile = new File(play2basedirFile, "play-" + play2version + ".zip");

    try {

        URL zipUrl = new URL("http://download.playframework.org/releases/play-" + play2version + ".zip");
        FileUtils.forceMkdir(play2basedirFile);

        // Download
        getLog().debug(debugLogPrefix + "is downloading to " + zipFile);
        FileUtils.copyURLToFile(zipUrl, zipFile);

        // Extract
        getLog().debug(debugLogPrefix + "is extracting to " + play2basedir);
        UnArchiver unarchiver = archiverManager.getUnArchiver(zipFile);
        unarchiver.setSourceFile(zipFile);
        unarchiver.setDestDirectory(play2basedirFile);
        unarchiver.extract();

        // Prepare
        File framework = new File(play2home, "framework");
        File build = new File(framework, AbstractPlay2Mojo.isWindows() ? "build.bat" : "build");
        if (!build.canExecute() && !build.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + build + " execution bit");
        }
        if (!play2.canExecute() && !play2.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + play2 + " execution bit");
        }

        getLog().debug(debugLogPrefix + "is now installed in " + play2home);

    } catch (NoSuchArchiverException ex) {
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (IOException ex) {
        try {
            if (play2home.exists()) {
                // Clean extracted data
                FileUtils.forceDelete(play2home);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete extracted Play! distribution after error: " + play2home);
        }
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Cannot unzip Play " + play2version + " in " + play2basedir, e);
    } finally {
        try {
            if (zipFile.exists()) {
                // Clean downloaded data
                FileUtils.forceDelete(zipFile);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete downloaded Play! distribution: " + zipFile);
        }
    }
}

From source file:ca.weblite.xmlvm.XMLVMTest.java

@Test
public void testCreateXMLVMClassStub() throws Exception {

    File input = File.createTempFile("input", ".xmlvm");
    File output = File.createTempFile("output", ".xmlvm");

    XMLVM xmlvm = new XMLVM();

    FileUtils.copyURLToFile(this.getClass().getResource("resources/com_codename1_cloud_CloudObject.xmlvm"),
            input);/*  w w  w .j a  va2s  .co  m*/
    xmlvm.createXMLVMClassStub(input, output);

    System.out.println(FileUtils.readFileToString(output));

}

From source file:edu.scripps.fl.pubchem.report.ReportController.java

public File imagesInTempDir() throws IOException {
    File file = new DirUtils().createTempDirectory("JasperReport", "");

    URL url = getClass().getClassLoader().getResource(jasperReport + ".jasper");
    FileUtils.copyURLToFile(url, new File(file.getAbsolutePath() + "\\" + jasperReport + ".jasper"));

    if (isInternal) {
        //         Scripps Report
        url = getClass().getClassLoader().getResource("logo.png");
        FileUtils.copyURLToFile(url, new File(file.getAbsolutePath() + "\\logo.png"));
        url = getClass().getClassLoader().getResource("Screening Center Logo.png");
        FileUtils.copyURLToFile(url, new File(file.getAbsolutePath() + "\\Screening Center Logo.png"));
    } else {//from   w w w  .  ja  v  a2s.  c om
        //         External Report
        url = getClass().getClassLoader().getResource("YourLogoHere.png");
        FileUtils.copyURLToFile(url, new File(file.getAbsolutePath() + "\\YourLogoHere.png"));
    }

    return file;
}

From source file:cz.cas.lib.proarc.common.imports.TiffImporterTest.java

@Before
public void setUp() throws Exception {
    junit = new UserProfile();
    junit.setUserName("junit");
    File root = temp.getRoot();//from ww  w .j  ava 2s.c om
    System.out.println("root: " + root.toString());
    tiff1 = new File(root, "img1.tiff");

    URL resource = TiffImporterTest.class.getResource("testscan-lzw.tiff");
    FileUtils.copyURLToFile(resource, tiff1);
    assertTrue(tiff1.length() > 0);

    ocr1 = new File(root, "img1.ocr.txt");
    FileUtils.writeStringToFile(ocr1, "test", "UTF-8");

    alto1 = new File(root, "img1.ocr.xml");
    FileUtils.writeStringToFile(alto1, "<alto xmlns=\"http://www.loc.gov/standards/alto/ns-v2#\">"
            + "<Layout><Page ID=\"Page1\" PHYSICAL_IMG_NR=\"1\"/></Layout>" + "</alto>", "UTF-8");

    ac1 = new File(root, "img1.ac.jp2");
    resource = TiffImporterTest.class.getResource("testscan.uc.jp2");
    FileUtils.copyURLToFile(resource, ac1);
    assertTrue(ac1.length() > 0);
    uc1 = new File(root, "img1.uc.jp2");
    FileUtils.copyURLToFile(resource, uc1);
    assertTrue(uc1.length() > 0);

    config = AppConfigurationFactory.getInstance().create(new HashMap<String, String>() {
        {
            put(AppConfiguration.PROPERTY_APP_HOME, temp.getRoot().getPath());
        }
    });

    jhoveContext = JhoveUtility.createContext(temp.newFolder("jhove"));

    DaoFactory daos = createMockDaoFactory();
    ibm = new ImportBatchManager(config, daos);

    //        MetaModelRepository.setInstance(new String[]{K4Plugin.ID});
    MetaModelRepository.setInstance(new String[] { NdkPlugin.ID });
    DigitalObjectManager.setDefault(new DigitalObjectManager(config, ibm, null,
            MetaModelRepository.getInstance(), EasyMock.createNiceMock(UserManager.class)));
}

From source file:com.compomics.pladipus.controller.setup.InstallActiveMQ.java

/**
 * Updates the activeMQ properties in the local propertyfile
 *
 * @param host the activeMQ host name//from w w w.  ja v  a2s .c  om
 * @param amqPort the port to connect to activeMQ
 * @param jmxPort the port to listen to connect and query JMX
 * @throws IOException
 */
public void updateProperties(String host, String amqPort, String jmxPort) throws IOException {
    NetworkProperties properties = NetworkProperties.getInstance();
    properties.setProperty("AMQ.host", host);
    properties.setProperty("AMQ.port.queue", amqPort);
    properties.setProperty("AMQ.version", "5.11.1");
    properties.setProperty("app.classpath", System.getProperty("user.home") + "/pladipus/external/");
    properties.save();
    URL inputUrl = new InstallActiveMQ().getClass().getResource("/doc/activemq.xml");
    File conf = findFile(activeMQFolder, "conf");
    File activeMQSettingsFile = new File(conf, "activemq.xml");
    FileUtils.copyURLToFile(inputUrl, activeMQSettingsFile);
    //update properties in the activeMQ file
    ActiveMQPropertyUpdater.updateActiveMQProperties(activeMQSettingsFile, host, amqPort, jmxPort);

}

From source file:com.fxforbiz.softphone.core.managers.UpdateManager.java

/**
 * This method allow to download a file identified by the URL given in parameters, and record it in a file in the file path given in parameters.
 * @param URL The URL of the file to download.
 * @param pathOfFile The path to record the file downloaded.
 * @return Either the file is downloaded successfully or not.
 *//* www.  j  a  v  a2  s .  com*/
private boolean downloadFile(String URL, String pathOfFile) {

    try {
        URL url = new URL(URL);
        File destination = new File(pathOfFile);
        FileUtils.copyURLToFile(url, destination);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File verifFile = new File(pathOfFile);
    return verifFile.exists();
}

From source file:GUI.WebBrowserPanel.java

@Override
public void onLoadingEnded() {
    if (m_frame != null) {
        try {/* w  w  w  . j a v a  2s. co  m*/
            String urltext = getDocument().getDocumentURI();
            URL url = new URL(urltext);
            InputStreamReader isr = new InputStreamReader(url.openStream());
            BufferedReader in = new BufferedReader(isr);
            String inputLine;

            urltext = null;
            url = null;

            m_content.clear();
            while ((inputLine = in.readLine()) != null) {
                m_content.add(inputLine);
            }
            in.close();

            isr = null;
            in = null;
            inputLine = null;

            Action action = parseHtml();
            if (action.value() == Action.ACTION_BROWSER_LOADING_DONE
                    && action.toString().equals(Action.COMMAND_CARD_PREVIEW)) {
                FileUtils.copyURLToFile(new URL(getCardImageURL(m_card.MID)), new File(m_card.getImagePath()));
                fireActionEvent(MainWindow.class, action.value(), action.toString());
            }

            action = null;

        } catch (Exception ex) {
            Dialog.ErrorBox(m_frame, ex.getStackTrace());
        }
    }
    m_loading = false;
}

From source file:hudson.lifecycle.WindowsSlaveInstaller.java

/**
 * Called when the install menu is selected
 *//*from w  ww. java  2 s  .  c  o m*/
public void actionPerformed(ActionEvent e) {
    int r = JOptionPane.showConfirmDialog(dialog,
            "This will install a slave agent as a Windows service,\n"
                    + "so that this slave will connect to Hudson as soon as the machine boots.\n"
                    + "Do you want to proceed with installation?",
            Messages.WindowsInstallerLink_DisplayName(), JOptionPane.OK_CANCEL_OPTION);
    if (r != JOptionPane.OK_OPTION)
        return;

    if (!DotNet.isInstalled(2, 0)) {
        JOptionPane.showMessageDialog(dialog, ".NET Framework 2.0 or later is required for this feature",
                Messages.WindowsInstallerLink_DisplayName(), JOptionPane.ERROR_MESSAGE);
        return;
    }

    final File dir = new File(rootDir);

    try {
        final File slaveExe = new File(dir, "hudson-slave.exe");
        FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe);

        // write out the descriptor
        URL jnlp = new URL(engine.getHudsonUrl(), "computer/" + engine.slaveName + "/slave-agent.jnlp");
        String xml = generateSlaveXml(System.getProperty("java.home") + "\\bin\\java.exe",
                "-jnlpUrl " + jnlp.toExternalForm());
        FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"), xml, "UTF-8");

        // copy slave.jar
        URL slaveJar = new URL(engine.getHudsonUrl(), "jnlpJars/remoting.jar");
        File dstSlaveJar = new File(dir, "slave.jar").getCanonicalFile();
        if (!dstSlaveJar.exists()) // perhaps slave.jar is already there?
            FileUtils.copyURLToFile(slaveJar, dstSlaveJar);

        // install as a service
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamTaskListener task = new StreamTaskListener(baos);
        r = new LocalLauncher(task).launch().cmds(slaveExe, "install").stdout(task).pwd(dir).join();
        if (r != 0) {
            JOptionPane.showMessageDialog(dialog, baos.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        r = JOptionPane.showConfirmDialog(dialog,
                "Installation was successful. Would you like to\n"
                        + "Stop this slave agent and start the newly installed service?",
                Messages.WindowsInstallerLink_DisplayName(), JOptionPane.OK_CANCEL_OPTION);
        if (r != JOptionPane.OK_OPTION)
            return;

        // let the service start after we close our connection, to avoid conflicts
        Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
            public void run() {
                try {
                    StreamTaskListener task = new StreamTaskListener(System.out);
                    int r = new LocalLauncher(task).launch().cmds(slaveExe, "start").stdout(task).pwd(dir)
                            .join();
                    task.getLogger()
                            .println(r == 0 ? "Successfully started" : "start service failed. Exit code=" + r);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        System.exit(0);
    } catch (Exception t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        JOptionPane.showMessageDialog(dialog, sw.toString(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorBuilderTest.java

private void copyPluginToThePluginDirectory(File pluginDir, String destinationFilenameOfPlugin)
        throws IOException, URISyntaxException {
    URL resource = getClass().getClassLoader().getResource("defaultFiles/" + destinationFilenameOfPlugin);
    FileUtils.copyURLToFile(resource, new File(pluginDir, destinationFilenameOfPlugin));
}

From source file:com.blackducksoftware.tools.commonframework.standard.protex.report.template.TemplateReader.java

/**
 * Copies one excel file into another Populates internal mappings. ONLY USE
 * THIS IF THE TEMPLATE IS AN INTERNAL RESOURCE
 *
 * @param templateName/*w ww. ja v a  2  s .  c  om*/
 *            the template name
 * @param outputLocation
 *            the output location
 * @throws Exception
 *             the exception
 */
public void copyTemplateIntoFile(String templateName, File outputLocation) throws Exception {
    this.outputLocation = outputLocation;

    if (outputLocation != null) {
        URL srcDir = getClass().getResource("/" + templateName);
        if (srcDir == null) {
            throw new IOException(templateName + " does not exist!");
        }
        FileUtils.copyURLToFile(srcDir, outputLocation);
        log.info("Finished copying from template: " + templateName);
    }

    String fileName = outputLocation.getName();
    if (fileName.endsWith("xlsx")) {
        templateBook = generateWorkBookFromFile(outputLocation);
    }

    populateTemplateMap();
}