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:GitBackend.GitAPI.java

/**
 * Download the file (an image in this example) into the repository.
 *
 * @param sourceURL/*  ww  w  .  j a va 2  s  .  c o m*/
 * @param targetPath
 * @return
 * @throws IOException
 */
public File copyFileFromURL(URL sourceURL, File targetPath, String filename) throws IOException {
    File targetFile = new File(targetPath.getAbsolutePath() + "/" + filename);
    FileUtils.copyURLToFile(sourceURL, targetFile);
    Logger.info("Downloaded file and copied into repository");
    return targetPath;
}

From source file:net.sourceforge.doddle_owl.ui.InputDocumentSelectionPanel.java

private String runStanfordParser(File docFile) {
    File dir = new File(STANFORD_PARSER_MODELS_HOME);
    if (!dir.exists()) {
        dir.mkdir();/*w w  w .  ja v a  2s  .co m*/
    }
    BufferedWriter bw = null;
    StringBuilder builder = new StringBuilder();
    try {
        String modelName = "english-left3words-distsim.tagger";
        String modelPath = STANFORD_PARSER_MODELS_HOME + File.separator + modelName;
        File modelFile = new File(modelPath);
        if (!modelFile.exists()) {
            URL url = DODDLE_OWL.class.getClassLoader()
                    .getResource(Utils.RESOURCE_DIR + "stanford_parser_models/" + modelName);
            if (url != null) {
                FileUtils.copyURLToFile(url, modelFile);
                // System.out.println("copy: " +
                // modelFile.getAbsolutePath());
            }
        }
        bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(STANFORD_PARSER_MODELS_HOME + File.separator + "tmpTagger.txt"), "UTF-8"));
        MaxentTagger tagger = new MaxentTagger(modelFile.getAbsolutePath());
        List<List<HasWord>> sentences = MaxentTagger.tokenizeText(new BufferedReader(new FileReader(docFile)));
        for (List<HasWord> sentence : sentences) {
            List<TaggedWord> tSentence = tagger.tagSentence(sentence);
            bw.write(Sentence.listToString(tSentence, false));
            builder.append(Sentence.listToString(tSentence, false));
        }
        bw.close();
    } catch (IOException ioe) {
        DODDLE_OWL.getLogger().log(Level.DEBUG, "Stanford Parser can not be executed.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null) {
                bw.close();
            }
        } catch (IOException ioe2) {
            ioe2.printStackTrace();
        }
    }
    return builder.toString();
}

From source file:de.interactive_instruments.ShapeChange.Target.ArcGISWorkspace.ArcGISWorkspace.java

public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    appSchemaPkg = p;//from w w w. j  a v a 2  s .  c o m
    model = m;
    options = o;
    result = r;

    // initialize mappings
    this.lengthMappingByTypeName.put("esriFieldTypeInteger", 0);
    this.lengthMappingByTypeName.put("esriFieldTypeDouble", 0);
    this.lengthMappingByTypeName.put("esriFieldTypeDate", 0);

    this.precisionMappingByTypeName.put("esriFieldTypeString", 0);
    this.precisionMappingByTypeName.put("esriFieldTypeInteger", 9);
    this.precisionMappingByTypeName.put("esriFieldTypeDouble", 10);
    this.precisionMappingByTypeName.put("esriFieldTypeDate", 0);

    this.scaleMappingByTypeName.put("esriFieldTypeString", 0);
    this.scaleMappingByTypeName.put("esriFieldTypeInteger", 0);
    this.scaleMappingByTypeName.put("esriFieldTypeDouble", 6);
    this.scaleMappingByTypeName.put("esriFieldTypeDate", 0);

    // get output location
    outputDirectory = options.parameter(this.getClass().getName(), PARAM_OUTPUT_DIR);
    if (outputDirectory == null)
        outputDirectory = options.parameter("outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter(".");

    String outputFilename = appSchemaPkg.name().replace("/", "_").replace(" ", "_") + ".eap";

    // parse default length parameter
    String defaultLengthParamValue = options.parameter(this.getClass().getName(),
            PARAM_LENGTH_TAGGED_VALUE_DEFAULT);
    if (defaultLengthParamValue != null) {

        try {

            int length = Integer.parseInt(defaultLengthParamValue);
            this.lengthTaggedValueDefault = length;

        } catch (NumberFormatException e) {

            result.addError(this, 13);
        }
    }

    // Check if we can use the output directory; create it if it
    // does not exist
    outputDirectoryFile = new File(outputDirectory);
    boolean exi = outputDirectoryFile.exists();
    if (!exi) {
        try {
            FileUtils.forceMkdir(outputDirectoryFile);
        } catch (IOException e) {
            result.addError(this, 5, e.getMessage());
            e.printStackTrace(System.err);
        }
        exi = outputDirectoryFile.exists();
    }
    boolean dir = outputDirectoryFile.isDirectory();
    boolean wrt = outputDirectoryFile.canWrite();
    boolean rea = outputDirectoryFile.canRead();
    if (!exi || !dir || !wrt || !rea) {
        result.addFatalError(this, 1, outputDirectory);
        throw new ShapeChangeAbortException();
    }

    File outputFile = new File(outputDirectoryFile, outputFilename);

    // check if output file already exists - if so, attempt to delete it
    exi = outputFile.exists();
    if (exi) {

        result.addInfo(this, 2, outputFilename, outputDirectory);

        try {
            FileUtils.forceDelete(outputFile);
            result.addInfo(this, 3);
        } catch (IOException e) {
            result.addInfo(this, 4, e.getMessage());
            e.printStackTrace(System.err);
        }
    }

    // read workspace template

    // String pathToWorkspaceTemplateFileInput = options.parameter(this
    // .getClass().getName(), PARAM_WORKSPACE_TEMPLATE);
    // File workspaceTemplateFileInput = null;
    //
    // if (pathToWorkspaceTemplateFileInput == null) {
    // result.addFatalError(this, 6);
    // throw new ShapeChangeAbortException();
    // } else {
    // workspaceTemplateFileInput = new File(
    // pathToWorkspaceTemplateFileInput);
    // if (!workspaceTemplateFileInput.canRead()) {
    // result.addFatalError(this, 7, pathToWorkspaceTemplateFileInput);
    // throw new ShapeChangeAbortException();
    // }
    // }

    workspaceTemplateFilePath = options.parameter(this.getClass().getName(), PARAM_WORKSPACE_TEMPLATE);

    if (workspaceTemplateFilePath == null) {
        workspaceTemplateFilePath = options.parameter(PARAM_WORKSPACE_TEMPLATE);
    }
    // if no path is provided, use the directory of the default template
    if (workspaceTemplateFilePath == null) {
        workspaceTemplateFilePath = WORKSPACE_TEMPLATE_URL;
        result.addInfo(this, 9, PARAM_WORKSPACE_TEMPLATE, WORKSPACE_TEMPLATE_URL);
    }

    // copy template file either from remote or local URI
    if (workspaceTemplateFilePath.toLowerCase().startsWith("http")) {
        try {
            URL templateUrl = new URL(workspaceTemplateFilePath);
            FileUtils.copyURLToFile(templateUrl, outputFile);
        } catch (MalformedURLException e1) {
            result.addFatalError(this, 6, workspaceTemplateFilePath, e1.getMessage());
            throw new ShapeChangeAbortException();
        } catch (IOException e2) {
            result.addFatalError(this, 8, e2.getMessage());
            throw new ShapeChangeAbortException();
        }
    } else {
        File workspacetemplate = new File(workspaceTemplateFilePath);
        if (workspacetemplate.exists()) {
            try {
                FileUtils.copyFile(workspacetemplate, outputFile);
            } catch (IOException e) {
                result.addFatalError(this, 8, e.getMessage());
                throw new ShapeChangeAbortException();
            }
        } else {
            result.addFatalError(this, 7, workspacetemplate.getAbsolutePath());
            throw new ShapeChangeAbortException();
        }
    }

    // File workspaceTemplateFileInput = new File(
    // workspaceTemplateFilePath);
    // if (!workspaceTemplateFileInput.canRead()) {
    // result.addFatalError(this, 7, pathToWorkspaceTemplateFileInput);
    // throw new ShapeChangeAbortException();
    // }

    // // copy template to outputFile
    // try {
    // FileUtils.copyFile(workspaceTemplateFileInput, outputFile);
    // } catch (IOException e) {
    // result.addFatalError(this, 8, e.getMessage());
    // e.printStackTrace(System.err);
    // throw new ShapeChangeAbortException();
    // }

    // connect to EA repository in outputFile
    absolutePathOfOutputEAPFile = outputFile.getAbsolutePath();

    rep = new Repository();

    if (!rep.OpenFile(absolutePathOfOutputEAPFile)) {
        String errormsg = rep.GetLastError();
        r.addError(null, 30, errormsg, outputFilename);
        rep = null;
        throw new ShapeChangeAbortException();
    }

    // get template packages
    rep.RefreshModelView(0);

    Collection<Package> c = rep.GetModels();
    Package root = c.GetAt((short) 0);

    Collection<Package> modelPkgs = root.GetPackages();
    if (modelPkgs.GetCount() == 0 || !modelPkgs.GetAt((short) 0).GetStereotypeEx().equalsIgnoreCase("ArcGIS")) {
        result.addError(this, 9);
        throw new ShapeChangeAbortException();
    } else {
        Package workspacePkg = modelPkgs.GetAt((short) 0);
        this.workspacePkgId = workspacePkg.GetPackageID();

        // eaPkgByModelPkg.put(appSchemaPkg, workspacePkg);
    }

    Integer features = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_FEATURES_NAME);
    if (features == null) {
        result.addError(this, 102, TEMPLATE_PKG_FEATURES_NAME);
        throw new ShapeChangeAbortException();
    } else {
        this.featuresPkgId = features;
        this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(featuresPkgId, new HashMap<PackageInfo, Integer>());
    }

    Integer domains = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_DOMAINS_NAME);
    if (domains == null) {
        result.addError(this, 102, TEMPLATE_PKG_DOMAINS_NAME);
        throw new ShapeChangeAbortException();
    } else {
        this.domainsPkgId = domains;
        this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(domainsPkgId, new HashMap<PackageInfo, Integer>());
    }

    Integer tables = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_TABLES_NAME);
    if (tables == null) {
        result.addError(this, 102, TEMPLATE_PKG_TABLES_NAME);
        throw new ShapeChangeAbortException();
    } else {
        this.tablesPkgId = tables;
        this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(tablesPkgId, new HashMap<PackageInfo, Integer>());
    }

    Integer assocClasses = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId,
            TEMPLATE_PKG_ASSOCIATION_CLASSES_NAME);
    if (assocClasses == null) {
        result.addError(this, 102, TEMPLATE_PKG_ASSOCIATION_CLASSES_NAME);
        throw new ShapeChangeAbortException();
    } else {
        this.assocClassesPkgId = assocClasses;
        this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(assocClassesPkgId, new HashMap<PackageInfo, Integer>());
    }

    ProcessConfiguration pc = o.getCurrentProcessConfig();

    // parse map entries
    List<ProcessMapEntry> mapEntries = pc.getMapEntries();

    Map<String, ProcessMapEntry> mes = new HashMap<String, ProcessMapEntry>();

    for (ProcessMapEntry pme : mapEntries) {
        // TODO ignores value of 'rule' attribute in map entry, so if there
        // were map entries for different rules with same 'type' attribute
        // value, this needs to be updated
        if (pme.hasTargetType()) {
            mes.put(pme.getType(), pme);
        } else {
            result.addError(this, 11, pme.getType());
        }
    }

    this.processMapEntries = mes;

    // initialize set with esri types suited for numeric range constraints
    esriTypesSuitedForRangeConstraint.add("esriFieldTypeInteger");
    esriTypesSuitedForRangeConstraint.add("esriFieldTypeDouble");

    // parse numeric range delta parameter
    String numRangeDeltaParamValue = options.parameter(this.getClass().getName(), PARAM_VALUE_RANGE_DELTA);
    if (numRangeDeltaParamValue != null) {

        try {

            double delta = Double.parseDouble(numRangeDeltaParamValue);
            this.numRangeDelta = delta;

        } catch (NumberFormatException e) {

            result.addError(this, 12);
        }
    }

    // change the default documentation template?
    documentationTemplate = options.parameter(this.getClass().getName(), PARAM_DOCUMENTATION_TEMPLATE);
    documentationNoValue = options.parameter(this.getClass().getName(), PARAM_DOCUMENTATION_NOVALUE);
}

From source file:com.joyent.manta.client.multipart.EncryptedServerSideMultipartManagerIT.java

public final void properlyClosesStreamsAfterUpload() throws IOException {
    final URL testResource = Thread.currentThread().getContextClassLoader().getResource(TEST_FILENAME);
    Assert.assertNotNull(testResource, "Test file missing");

    final File uploadFile = File.createTempFile("upload", ".jpg");
    FileUtils.forceDeleteOnExit(uploadFile);
    FileUtils.copyURLToFile(testResource, uploadFile);
    Assert.assertTrue(0 < uploadFile.length(), "Error preparing upload file");

    final String path = testPathPrefix + UUID.randomUUID().toString();
    EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(path);

    // we are not exercising the FileInputStream code-path due to issues with
    // spies failing the check for inputStream.getClass().equals(FileInputStream.class)
    InputStream contentStream = new FileInputStream(uploadFile);
    InputStream fileInputStreamSpy = Mockito.spy(contentStream);

    MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, fileInputStreamSpy);

    // verify the stream we passed was closed
    Mockito.verify(fileInputStreamSpy, Mockito.times(1)).close();

    MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1 };
    Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts);
    multipart.complete(upload, partsStream);
}

From source file:ca.weblite.codename1.ios.CodenameOneIOSBuildTask.java

@Override
protected void copyNativeLibraries() {
    super.copyNativeLibraries(); //To change body of generated methods, choose Tools | Templates.
    if (debug) {/*from www.ja  v a2  s . co  m*/
        try {
            // We need to copy the fat version of libzbar so that it works in the simulator
            File nativeLibDir = this.getNativeLibsPath();
            File dest = new File(nativeLibDir, "libzbar.a");
            URL src = getClass().getResource("resources/libzbar.a");
            FileUtils.copyURLToFile(src, dest);
        } catch (IOException ex) {
            Logger.getLogger(CodenameOneIOSBuildTask.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:app.MainPanel.java

private boolean downloadXML() {
    try {//from w ww  .  j  a va 2  s  .c o  m
        String filename = "";

        if (jRadioButton1.isSelected()) {
            filename = "http://www.nbp.pl/kursy/xml/Last" + jComboBox1.getSelectedItem().toString() + ".xml";
        } else {
            int year = Calendar.getInstance().get(Calendar.YEAR);
            String filenameDir;

            if (Integer.parseInt(jComboBox3.getSelectedItem().toString()) == year) {
                filenameDir = "http://www.nbp.pl/kursy/xml/dir.txt";
            } else {
                filenameDir = "http://www.nbp.pl/kursy/xml/dir" + jComboBox3.getSelectedItem().toString()
                        + ".txt";
            }

            URL urlDir = new URL(filenameDir);
            File fileDir = new File("dir.txt");

            FileUtils.copyURLToFile(urlDir, fileDir);

            String[] files = readLines("dir.txt");

            String date = jComboBox3.getSelectedItem().toString();
            date = date.replace("20", "");
            date = date.concat(String.format("%02d", 1 + jComboBox4.getSelectedIndex()));
            date = date
                    .concat(String.format("%02d", Integer.parseInt(jComboBox5.getSelectedItem().toString())));

            String filenamePart = "";

            for (String file : files) {
                if (file.contains(date)) {
                    if (file.contains(jComboBox1.getSelectedItem().toString().toLowerCase())) {
                        filenamePart = file;
                        break;
                    }
                }
            }

            filename = "http://www.nbp.pl/kursy/xml/" + filenamePart + ".xml";
        }

        URL url = new URL(filename);
        File file = new File("temp.xml");

        FileUtils.copyURLToFile(url, file);

        return true;
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Dla tej daty brak plikw na serwerze NBP!");
    } catch (MalformedURLException ex) {
        Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:net.rptools.maptool.util.PersistenceUtil.java

public static Token loadToken(URL url) throws IOException {
    // Create a temporary file from the downloaded URL
    File newFile = new File(PackedFile.getTmpDir(), new GUID() + ".url");
    FileUtils.copyURLToFile(url, newFile);
    Token token = loadToken(newFile);/*from   w  ww .j a va  2  s  .  c om*/
    newFile.delete();
    return token;
}

From source file:de.helmholtz_muenchen.ibis.knime.preferences.KNIMEPreferencePage.java

private void downloadBinaries(String dir) {
    if (dir == null)
        return;/*  ww  w .j av a  2s.  c o m*/

    try {
        CheckUtils.checkDestinationDirectory(dir);
    } catch (InvalidSettingsException e1) {
        JOptionPane.showMessageDialog(null, "This directory cannot be used: " + e1.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    for (String tool : IBISKNIMENodesPlugin.TOOLS.keySet()) {
        if (IBISKNIMENodesPlugin.TOOLS.get(tool)) {
            if (IBISKNIMENodesPlugin.getStringPreference(tool).equals("")) {
                try {
                    File f = new File(dir + File.separatorChar + tool);
                    if (!f.exists()) {
                        FileUtils.copyURLToFile(new URL(DOWNLOAD_PATH + tool), f);
                        f.setExecutable(true, false);
                        IBISKNIMENodesPlugin.setStringPreference(tool, dir + "/" + tool);

                        HashSet<String> deps = DEPENDENCIES.get(tool);
                        if (deps == null)
                            continue;
                        for (String dep : deps) {
                            File f1 = new File(dir + File.separatorChar + dep);
                            if (!f1.exists()) {
                                FileUtils.copyURLToFile(new URL(DOWNLOAD_PATH + dep), f1);
                                f1.setExecutable(true, false);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOGGER.error("Downloading " + tool + " failed! Message: " + e.getMessage());
                }
            }
        }
    }

    for (TableItem i : table.getItems()) {
        i.setText(1, IBISKNIMENodesPlugin.getStringPreference(i.getText(0)));
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private void downloadImage(String imageURL, String dest) {
    try {//from www. j a  va2s  . c  o m
        //            System.out.println("DRP4OST.downloadImage()>START Downloading from imageURL=" + imageURL + " to dest=" + dest);
        FileUtils.copyURLToFile(new URL(imageURL), new File(dest));
        //            System.out.println("DRP4OST.downloadImage()>FINISH Downloading from imageURL=" + imageURL + " to dest=" + dest);
    } catch (Exception e) {
        System.out.println("DRP4OST.downloadImage()>Exception downloading the file");
        e.printStackTrace();
    }
}

From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java

private File fromURLtoFile(String url) throws TMFVisibleException {

    LOG.debug("[fromURLtoFile] - BEGIN");

    URL epubUrl;/*from w ww .  j a  v  a 2 s. c o  m*/
    File file;
    try {
        epubUrl = new URL(url);
    } catch (MalformedURLException e) {
        LOG.error("[classifyEpub] - EXCEPTION: ", e);
        throw new TMFVisibleException("Epub URL is malformed");
    }
    try {
        file = new File(TEMPORARY_PATH);
        file.createNewFile();
        FileUtils.copyURLToFile(epubUrl, file);
    } catch (IOException e) {
        LOG.error("[classifyEpub] - EXCEPTION: ", e);
        throw new TMFVisibleException("Cannot read the Epub file");
    }

    LOG.debug("[fromURLtoFile] - END");

    return file;
}