Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

In this page you can find the example usage for java.io File getAbsoluteFile.

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:net.osten.watermap.batch.FetchPCTWaypointsJob.java

private void unZipIt(File zipFile, File outputFolder) {
    byte[] buffer = new byte[1024];

    try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName);

            log.log(Level.FINER, "file unzip : {0}", new Object[] { newFile.getAbsoluteFile() });

            // create all non existing folders else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }/*from  w ww . j av  a2  s.c om*/
            }
            ze = zis.getNextEntry();

            // move newFile to data directory
            try {
                // have to delete first since FileUtils does not overwrite
                File destinationFile = new File(outputFolder + File.separator + newFile.getName());
                if (destinationFile.exists()) {
                    destinationFile.delete();
                }
                FileUtils.moveFileToDirectory(newFile, outputFolder, false);
            } catch (FileExistsException ioe) {
                log.warning(ioe.getLocalizedMessage());
            } catch (IOException ioe) {
                log.warning(ioe.getLocalizedMessage());
            }
        }

        // close the last entry
        zis.closeEntry();
    } catch (IOException e) {
        log.warning(e.getLocalizedMessage());
    }
}

From source file:de.thischwa.pmcms.gui.listener.ListenerAddSite.java

@Override
public void widgetSelected(SelectionEvent e) {
    logger.debug("SEL add site");
    Site site = new Site();
    if (DialogManager.startDialogPersitentPojo(e.display.getActiveShell(), site)) {
        File defaultResourceDir = new File(InitializationManager.getBean(PropertiesManager.class)
                .getProperty("pmcms.dir.defaultresources"));
        File srcDir = new File(defaultResourceDir.getAbsoluteFile(), "sites");
        File srcConfigDir = new File(srcDir, "configuration");
        File destDir = PoPathInfo.getSiteDirectory(site);
        File destConfigDir = new File(destDir, "configuration");
        destConfigDir.mkdirs();/*from   w w  w. jav  a2 s . c  o  m*/
        try {
            // copy required files
            FileUtils.copyFileToDirectory(new File(srcDir, "format.css"), destDir);
            FileUtils.copyFileToDirectory(new File(srcConfigDir, "fckconfig.js"), destConfigDir);
            FileUtils.copyFileToDirectory(new File(srcConfigDir, "fckstyles.xml"), destConfigDir);

            // read the templates
            site.add(buildTemplate(srcDir, "layout.html", site, null));
            File srcTemplatedir = new File(srcDir, "templates");
            site.add(buildTemplate(srcTemplatedir, "gallery.html", site, TemplateType.GALLERY));
            site.add(buildTemplate(srcTemplatedir, "image.html", site, TemplateType.IMAGE));
            site.add(buildTemplate(srcTemplatedir, "page.html", site, TemplateType.PAGE));

            // read the macro
            Macro macro = new Macro();
            macro.setParent(site);
            macro.setName("user_menu.vm");
            macro.setText(FileTool.toString(new File(srcConfigDir, "user_menu.vm")));
        } catch (IOException e1) {
            throw new FatalException("While construct the default file structure of a site: " + e1.getMessage(),
                    e1);
        }

        SiteHolder siteHolder = InitializationManager.getBean(SiteHolder.class);
        siteHolder.setSite(site);
        TreeViewManager treeViewManager = InitializationManager.getBean(TreeViewManager.class);
        treeViewManager.fillAndExpands(site);
        BrowserManager browserManager = InitializationManager.getBean(BrowserManager.class);
        browserManager.showHelp();

        WorkspaceToolBarManager.actionAfterSiteRenamed(site);
    }
}

From source file:com.dchq.docker.volume.driver.adaptor.LocalVolumeAdaptorImpl.java

@Override
public BaseResponse create(CreateRequest request) {
    BaseResponse response = new BaseResponse();
    try {//from www  .  ja v  a  2  s. c  o  m
        File file = new File(new File(TMP_LOC), request.getName());
        FileUtils.forceMkdir(file);
        logger.info("Created Volume [{}] on path [{}]", file.getName(), file.getAbsoluteFile());

    } catch (Exception e) {
        logger.warn(e.getLocalizedMessage(), e);
        response.setErr(e.getLocalizedMessage());
    }
    return response;
}

From source file:com.dchq.docker.volume.driver.adaptor.LocalVolumeAdaptorImpl.java

@Override
public BaseResponse remove(RemoveRequest request) {
    BaseResponse response = new BaseResponse();
    try {/*from   w  w  w.  j  av a 2 s .  c om*/
        File file = new File(new File(TMP_LOC), request.getName());
        FileUtils.forceDelete(file);
        logger.info("Removed Volume [{}] on path [{}]", file.getName(), file.getAbsoluteFile());
    } catch (Exception e) {
        logger.warn(e.getLocalizedMessage(), e);
        response.setErr(e.getLocalizedMessage());
    }
    return response;
}

From source file:com.doculibre.constellio.services.SynonymServicesImpl.java

@Override
public void writeSynonymsFile(RecordCollection collection) {
    List<List<String>> collectionSynonyms = getSynonyms(collection.getName());
    List<String> lines = new ArrayList<String>();
    for (List<String> syn : collectionSynonyms) {
        StringBuilder synDefLine = new StringBuilder();
        for (String term : syn) {
            synDefLine.append(term + ", ");
        }/*  w ww.  j  a v  a2 s .c o  m*/
        String synDefLineString = synDefLine.toString();
        if (!synDefLineString.isEmpty()) {
            synDefLineString = org.apache.commons.lang.StringUtils.substringBeforeLast(synDefLineString, ",");
            lines.add(synDefLineString);
        }
    }
    //TODO : lors que les filtres auront les parametres necessaires 
    //Pour chacun des analyseurs qui a un filtre de synonymes : "solr.SynonymFilterFactory"
    //1. lire le fichier des synonymes (dans conf ou data) (le creer le cas echeant)
    //2. remplacer son contenu avec lines
    File synonymsFile = ClasspathUtils.getSynonymsFile(collection);

    FileOutputStream ecraserSynonymsFile = null;

    try {
        ecraserSynonymsFile = new FileOutputStream(synonymsFile.getAbsoluteFile());
        IOUtils.writeLines(lines, System.getProperty("line.separator"), ecraserSynonymsFile);
        ecraserSynonymsFile.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(ecraserSynonymsFile);
    }
}

From source file:com.hmiard.blackwater.projects.Builder.java

/**
 * Deleting a server from a project./*w  w  w .  j a v  a 2s. c  om*/
 *
 * @param projectRoot String
 * @param serverName String
 * @param listener ConsoleEmulator
 * @return Boolean
 */
public static Boolean deleteServer(String projectRoot, String serverName, ConsoleEmulator listener) {

    serverName = serverName.substring(0, 1).toUpperCase() + serverName.substring(1).toLowerCase();
    serverName += "Server";
    File checker = new File(projectRoot + "\\src\\" + serverName);
    File composerJSON = new File(projectRoot + "\\composer.json");

    if (!checker.exists()) {
        listener.push("This server is missing ! Operation aborted.");
        return false;
    }
    if (!composerJSON.exists()) {
        listener.push("File composer.json is missing ! Operation aborted.");
        return false;
    }

    try {
        FileUtils.deleteDirectory(checker);

        if (checker.exists()) {
            listener.push("Woops ! It seems impossible to delete " + checker.getAbsolutePath());
            return false;
        }

        JSONObject composer = new JSONObject(readFile(composerJSON.getAbsolutePath()));
        JSONObject autoload = composer.getJSONObject("autoload");
        JSONObject psr0 = autoload.getJSONObject("psr-0");

        psr0.remove(serverName);

        BufferedWriter cw = new BufferedWriter(new FileWriter(composerJSON.getAbsoluteFile()));
        String content = composer.toString(4).replaceAll("\\\\", "");
        cw.write(content);
        cw.close();

        listener.push("\n" + serverName + " was deleted successfully !\n");

    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:net.sf.keystore_explorer.gui.actions.GenerateCsrAction.java

/**
 * Do action./* w w w  .  j  a v a 2  s.  c om*/
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:com.knowbout.epg.processor.Downloader.java

private boolean downloadFile(FTPFile remoteFile) throws IOException {
    boolean success = false;
    File file = new File(destinationFolder + File.separator + remoteFile.getName());
    long lastModified = remoteFile.getTimestamp().getTimeInMillis();
    log.debug("Remote file is " + remoteFile.getName() + " local file is " + file.getAbsoluteFile()
            + " does it exist:" + file.exists());
    if (forceDownload || !file.exists() || (file.lastModified() < lastModified)) {
        log.debug("Downloading " + remoteFile.getName() + " " + remoteFile.getSize() + " to "
                + file.getAbsolutePath());

        FileOutputStream fos = new FileOutputStream(file);
        client.retrieveFile(remoteFile.getName(), fos);
        fos.close();//from  w  w w  .ja v a  2 s  . c  o  m
        fos.flush();
        file.setLastModified(lastModified);
        success = true;
    }
    return success;
}

From source file:org.zywx.wbpalmstar.engine.EDownloadDialog.java

private void saveToFile() throws Exception {
    mInStream = mConnection.getInputStream();
    if (mInStream == null) {
        return;//from  www .  j  a  v  a2 s  .  c o m
    }
    if (contentLength <= 0) {
        String cLength = mConnection.getHeaderField("Content-Length");
        if (cLength != null) {
            contentLength = Long.parseLong(cLength);
        }
    }
    MimeTypeMap mtm = MimeTypeMap.getSingleton();
    String extension = mtm.getExtensionFromMimeType(mimetype);
    File tm = Environment.getExternalStorageDirectory();
    File target = new File(tm.getAbsoluteFile() + "/Download/");
    if (!target.exists()) {
        target.mkdirs();
    }
    mTmpFile = File.createTempFile("/Download/", "." + extension, tm);
    OutputStream outStream = new FileOutputStream(mTmpFile);
    byte buffer[] = new byte[1024 * 3];
    while (true) {
        int numread = mInStream.read(buffer);
        if (numread == -1) {
            mProgressHandler.sendEmptyMessage(100);
            break;
        }
        outStream.write(buffer, 0, numread);
        downLoaderSise += numread;
        int p = (int) (((float) downLoaderSise / contentLength) * 100);
        mProgressHandler.sendEmptyMessage(p);
    }
    if (contentLength <= 0) {
        mProgressHandler.sendEmptyMessage(100);
    }
}

From source file:dk.netarkivet.common.distribute.AbstractRemoteFile.java

/** Copy this remote file to the given file.
 * This method will make a fileoutputstream, and use appendTo to write
 * the remote file to this stream./* w  w  w . j  av  a2 s.  c  om*/
 * @param destFile The file to write the remote file to.
 * @throws ArgumentNotValid on null destFile, or parent to destfile is not
 * a writeable directory, or destfile exists and cannot be overwritten.
 * @throws IOFailure on I/O trouble writing remote file to destination.
 */
public void copyTo(File destFile) {
    ArgumentNotValid.checkNotNull(destFile, "File destFile");
    destFile = destFile.getAbsoluteFile();
    if ((!destFile.isFile() || !destFile.canWrite())
            && (!destFile.getParentFile().isDirectory() || !destFile.getParentFile().canWrite())) {
        throw new ArgumentNotValid(
                "Destfile '" + destFile + "' does not point to a writable file for remote file '" + file + "'");
    }
    try {
        FileOutputStream fos = null;
        int retry = 0;
        boolean success = false;

        // retry if it fails, but always make at least one attempt.
        do {
            try {
                try {
                    fos = new FileOutputStream(destFile);
                    appendTo(fos);
                    success = true;
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
            } catch (IOFailure e) {
                if (retry == 0) {
                    log.warn("Could not retrieve the file '" + getName()
                            + "' on first attempt. Will retry up to '" + getNumberOfRetries() + "' times.", e);
                } else {
                    log.warn("Could not retrieve the file '" + getName() + "' on retry number '" + retry
                            + "' of '" + getNumberOfRetries() + "' retries.", e);
                }
            }
            retry++;
            if (!success && retry < getNumberOfRetries()) {
                log.debug("CopyTo attempt #" + retry + " of max " + getNumberOfRetries()
                        + " failed. Will sleep a while before trying to " + "copyTo again.");
                TimeUtils.exponentialBackoffSleep(retry, Calendar.MINUTE);
            }
        } while (!success && retry < getNumberOfRetries());

        // handle case when the retrieval is unsuccessful.
        if (!success) {
            throw new IOFailure("Unable to retrieve the file '" + getName() + "' in '" + getNumberOfRetries()
                    + "' attempts.");
        }
    } catch (Exception e) {
        FileUtils.remove(destFile);
        throw new IOFailure("IO trouble transferring file", e);
    }
}