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:edu.ku.brc.specify.web.JasperReportHelper.java

/**
 * The compiling of the report is complete
 * @param report the completeed report, or null if there was a compiling error
 *///  w  ww  .  j  a v  a  2 s . c  om
public void compileComplete(final File compiledFile) {
    if (compiledFile != null) {
        try {
            System.out.println("Creating report...");

            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(compiledFile.getAbsoluteFile());
            if (jasperReport != null) {
                System.out.println("Loaded report...");

                Map<String, Object> parameters = new HashMap<String, Object>();

                parameters.put("RPT_IMAGE_DIR", JasperReportsCache.getImagePath().getAbsolutePath());
                parameters.put("SUBREPORT_DIR", cachePath.getAbsoluteFile() + File.separator);
                parameters.put("DATASOURCE", dataSource);

                if (recordSet != null) {
                    parameters.put("itemnum", DBTableIdMgr.getInstance().getInClause(recordSet));
                }

                // Add external parameters
                if (params != null) {
                    for (Object key : params.keySet()) {
                        //System.out.println("key["+key+"]  Val["+params.get(key)+"]");
                        parameters.put(key.toString(), params.get(key));
                    }
                }

                // XXX What about losing a connection here?
                if (requiresHibernate) {
                    session = HibernateUtil.getNewSession();
                    parameters.put(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_SESSION, session);
                }

                if (isAsynchronous) {
                    System.out.println("Filling report asynchronously...");

                    //progressLabel.setText(getResourceString("JasperReportFilling"));
                    if (recordSet != null) {
                        asyncFillHandler = AsynchronousFillHandle.createHandle(jasperReport, parameters,
                                DBConnection.getInstance().getConnection());
                    } else {
                        asyncFillHandler = AsynchronousFillHandle.createHandle(jasperReport, parameters,
                                dataSource);
                    }
                    asyncFillHandler.addListener(this);
                    asyncFillHandler.startFill();

                } else {
                    System.out.println("Filling report synchronously...");
                    JasperPrint jasperPrint;
                    if (recordSet != null) {
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,
                                DBConnection.getInstance().getConnection());
                    } else {
                        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
                    }

                    if (jasperPrint != null) {
                        listener.complete(jasperPrint);
                    } else {
                        listener.completedWithError();
                    }
                }

            } else {
                log.error("jasperReport came back null [" + compiledFile.getAbsolutePath() + "]");
                //progressBar.setIndeterminate(false);
                //setLabelText(getResourceString("JasperReportReadingCachedReport"));
            }

        } catch (JRException ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(JasperReportHelper.class, ex);
            //setLabelText(getResourceString("JasperReportCreatingViewer"));
            log.error(ex);
            ex.printStackTrace();
        }
    } else {
        //setLabelText(getResourceString("JasperReportCompileError"));
    }
    compiler = null;
}

From source file:de.nrw.hbz.regal.sync.ingest.Downloader.java

@Override
public String download(String pid, boolean forceDownload) {
    if (map.containsKey(pid))
        throw new AlreadyVisitedException(pid + " already visited!");
    String objectDirectory = null;
    try {/*w  ww.  ja v a 2  s .co  m*/
        objectDirectory = downloadLocation + File.separator + URLEncoder.encode(pid, "utf-8");
    } catch (UnsupportedEncodingException e1) {
        throw new EncodingException(e1);
    }
    File dir = new File(objectDirectory);
    if (!dir.exists()) {
        logger.info("Create Directory " + dir.getAbsoluteFile() + " and start to Download files");
        dir.mkdirs();

        try {
            if (!map.containsKey(pid)) {
                map.put(pid, pid);

            } else {
                throw new AlreadyVisitedException(pid + " already visited!");
            }
            downloadObject(dir, pid);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        setUpdated(false);
        setDownloaded(true);
    } else if (forceDownload) {
        logger.info("Directory " + dir.getAbsoluteFile() + " exists. Force override.");
        try {
            FileUtils.deleteDirectory(dir);
        } catch (IOException e1) {
            throw new DeleteDirectoryException(e1);
        }
        dir.mkdirs();

        try {
            if (!map.containsKey(pid)) {
                map.put(pid, pid);

            } else {
                throw new AlreadyVisitedException(pid + " already visited!");
            }
            downloadObject(dir, pid);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }

        setUpdated(true);
        setDownloaded(true);
    } else {
        logger.info("Directory " + dir.getAbsoluteFile() + " exists. Step over.");
        setDownloaded(false);
        setUpdated(false);
    }
    map.clear();
    return dir.getAbsolutePath();
}

From source file:com.athena.meerkat.controller.web.provisioning.AbstractProvisioningService.java

public void sendLog(WebSocketSession session, int taskHistoryDetailId) {

    TaskHistoryDetail taskDetail = taskService.getTaskHistoryDetail(taskHistoryDetailId);

    LogTailerListener listener = new LogTailerListener(session, true);
    long delay = 2000;
    File file = new File(taskDetail.getLogFilePath());
    LOGGER.debug("log file : {}", file.getAbsoluteFile());

    Tailer tailer = new Tailer(file, listener, delay);
    new Thread(tailer).start();

}

From source file:net.sf.jabref.logic.xmp.XMPUtil.java

/**
 * Try to write the given BibTexEntry in the XMP-stream of the given
 * PDF-file.//from www .  j  av a  2  s  . c o  m
 *
 * Throws an IOException if the file cannot be read or written, so the user
 * can remove a lock or cancel the operation.
 *
 * The method will overwrite existing BibTeX-XMP-data, but keep other
 * existing metadata.
 *
 * @param file
 *            The file to write the entries to.
 * @param bibtexEntries
 *            The entries to write to the file. *
 * @param database
 *            maybenull An optional database which the given bibtex entries
 *            belong to, which will be used to resolve strings. If the
 *            database is null the strings will not be resolved.
 * @param writePDFInfo
 *            Write information also in PDF document properties
 * @throws TransformerException
 *             If the entry was malformed or unsupported.
 * @throws IOException
 *             If the file could not be written to or could not be found.
 */
public static void writeXMP(File file, Collection<BibEntry> bibtexEntries, BibDatabase database,
        boolean writePDFInfo) throws IOException, TransformerException {

    Collection<BibEntry> resolvedEntries;
    if (database == null) {
        resolvedEntries = bibtexEntries;
    } else {
        resolvedEntries = database.resolveForStrings(bibtexEntries, false);
    }

    try (PDDocument document = PDDocument.load(file.getAbsoluteFile())) {
        if (document.isEncrypted()) {
            throw new EncryptedPdfsNotSupportedException();
        }

        if (writePDFInfo && (resolvedEntries.size() == 1)) {
            XMPUtil.writeDocumentInformation(document, resolvedEntries.iterator().next(), null);
            XMPUtil.writeDublinCore(document, resolvedEntries, null);
        }

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDMetadata metaRaw = catalog.getMetadata();

        XMPMetadata meta;
        if (metaRaw == null) {
            meta = new XMPMetadata();
        } else {
            meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream()));
        }
        meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class);

        // Remove all current Bibtex-schemas
        List<XMPSchema> schemas = meta.getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE);
        for (XMPSchema schema : schemas) {
            XMPSchemaBibtex bib = (XMPSchemaBibtex) schema;
            bib.getElement().getParentNode().removeChild(bib.getElement());
        }

        for (BibEntry e : resolvedEntries) {
            XMPSchemaBibtex bibtex = new XMPSchemaBibtex(meta);
            meta.addSchema(bibtex);
            bibtex.setBibtexEntry(e, null);
        }

        // Save to stream and then input that stream to the PDF
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        meta.save(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        PDMetadata metadataStream = new PDMetadata(document, is, false);
        catalog.setMetadata(metadataStream);

        // Save
        try {
            document.save(file.getAbsolutePath());
        } catch (COSVisitorException e) {
            LOGGER.debug("Could not write XMP metadata", e);
            throw new TransformerException("Could not write XMP metadata: " + e.getLocalizedMessage(), e);
        }
    }
}

From source file:com.github.houbie.lesscss.LesscCommandLineParser.java

private void setResourceReader(CommandLine cmd) throws ParseException {
    if (cmd.hasOption(INCLUDE_PATH_OPTION)) {
        String[] paths = cmd.getOptionValue(INCLUDE_PATH_OPTION).split("[:|;]");
        File[] files = new File[paths.length];
        for (int i = 0; i < paths.length; i++) {
            files[i] = new File(paths[i]);
        }/*from w  ww .j  a  va  2s  .  com*/
        resourceReader = new FileSystemResourceReader(encoding, files);
    } else {
        File source = new File(sourceLocation);
        if (!source.exists()) {
            throw new ParseException(
                    sourceLocation + " can not be found. Check the location or use --" + INCLUDE_PATH_OPTION);
        }
        resourceReader = new FileSystemResourceReader(encoding, source.getAbsoluteFile().getParentFile());
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.FileContentStoreDynamic.java

/**
 * @param rootDirectory     the root under which files will be stored.
 *                          The directory will be created if it does not exist.
 *///from   w  ww. j  a  v a2s  . c  o m
public void setResource(File rootDirectory) {
    if (!rootDirectory.exists()) {
        if (!rootDirectory.mkdirs()) {
            throw new ContentIOException("Failed to create store root: " + rootDirectory, null);
        }
    }
    this.rootDirectory = rootDirectory.getAbsoluteFile();
    rootAbsolutePath = rootDirectory.getAbsolutePath();
    allowRandomAccess = true;
    readOnly = false;
}

From source file:CircularGenerator.java

private void extendFastA(File inputFasta) {
    // create the new files
    String fileExtension = com.google.common.io.Files.getFileExtension(inputFasta.getAbsolutePath());
    String fileName = com.google.common.io.Files.getNameWithoutExtension(inputFasta.getAbsolutePath());
    String filePath = inputFasta.getAbsolutePath().substring(0,
            inputFasta.getAbsolutePath().lastIndexOf(File.separator));
    File output = new File(filePath + "/" + fileName + "_" + this.elongationfactor + "." + fileExtension);
    File outputChanged = new File(inputFasta.getAbsoluteFile() + "_" + this.elongationfactor + "_elongated");
    PrintWriter out;/*  www . j ava  2  s.com*/
    // read the sequences
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(output, false)));
        PrintWriter outChanged = new PrintWriter(new BufferedWriter(new FileWriter(outputChanged, false)));
        @SuppressWarnings("resource")
        BufferedReader br = new BufferedReader(new FileReader(inputFasta));
        String currLine = "";
        String header = "";
        Boolean firstEntry = true;
        StringBuffer sequence = new StringBuffer();
        // read the fasta file entry by entry
        while ((currLine = br.readLine()) != null) {
            // start of new sequence
            if (currLine.startsWith(">")) {
                if (!firstEntry) {
                    extendSequence(header, sequence, out, outChanged);
                }
                // reset sequence
                firstEntry = false;
                header = currLine.substring(1);
                sequence.setLength(0);
            } else {
                sequence.append(currLine);
            }
        }
        // modify last entry
        extendSequence(header, sequence, out, outChanged);
        // close the writers
        out.flush();
        outChanged.flush();
        out.close();
        outChanged.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.groupdocs.ui.servlets.ViewDocument.java

private List<PageHtml> GetHtmlPages(String filePath, HtmlOptions htmlOptions)
        throws ServletException, IOException {

    List<PageHtml> htmlPages = null;
    try {/*  w w  w.jav a 2  s  . c o m*/
        htmlPages = ViewerUtils.getViewerHtmlHandler().getPages(filePath, htmlOptions);
    } catch (Exception x) {
        throw new ServletException(x);
    }
    temp_cssList = new ArrayList<String>();

    for (PageHtml page : htmlPages) {

        int indexOfBodyOpenTag = page.getHtmlContent().indexOf("<body>");

        if (indexOfBodyOpenTag > 0) {
            page.setHtmlContent(page.getHtmlContent().substring(indexOfBodyOpenTag + "<body>".length()));
        }

        int indexOfBodyCloseTag = page.getHtmlContent().indexOf("</body>");

        if (indexOfBodyCloseTag > 0) {
            page.setHtmlContent(page.getHtmlContent().substring(0, indexOfBodyCloseTag));
        }

        /////////////////////////

        List<HtmlResource> test = page.getHtmlResources();

        for (HtmlResource resource : page.getHtmlResources()) {

            if (resource.getResourceType() == HtmlResourceType.Style) {
                InputStream cssStream = ViewerUtils.getViewerHtmlHandler().getResource(filePath, resource);
                String text = IOUtils.toString(cssStream, "UTF-8");

                boolean needResave = false;
                if (text.indexOf("url(\"") >= 0
                        && text.indexOf("url(\"/GetResourceForHtml?documentPath=") < 0) {
                    needResave = true;
                    text = text.replace("url(\"", "url(\"/GetResourceForHtml?documentPath=" + filePath
                            + "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName=");
                }

                if (text.indexOf("url('") >= 0 && text.indexOf("url('/GetResourceForHtml?documentPath=") < 0) {
                    needResave = true;
                    text = text.replace("url('", String.format("url(\'/GetResourceForHtml?documentPath="
                            + filePath + "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName="));
                }

                temp_cssList.add(text);

                if (needResave) {

                    String fullPath = ViewerUtils.TEMP_PATH + filePath + "/" + "html" + "/" + "resources" + "/"
                            + "page" + page.getPageNumber() + "/" + resource.getResourceName();
                    File file = new File(fullPath);

                    // if file doesnt exists, then create it
                    if (!file.exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }

                    FileWriter fw = new FileWriter(file.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(text);
                    bw.close();

                }
            }
            /////////////////////////
        }
        ArrayList<String> cssClasses = Utils.GetCssClasses(page.getHtmlContent());
        for (String cssClass : cssClasses) {
            String newCssClass = "page-" + page.getPageNumber() + "-" + cssClass;

            page.setHtmlContent(page.getHtmlContent().replace(cssClass, newCssClass));
            for (int i = 0; i < temp_cssList.size(); i++) {
                temp_cssList.set(i, temp_cssList.get(i).replace(cssClass, newCssClass));
            }
        }
    }
    return htmlPages;

}

From source file:com.viewer.servlets.ViewDocument.java

private List<PageHtml> GetHtmlPages(String filePath, HtmlOptions htmlOptions) throws Exception {

    List<PageHtml> htmlPages = null;
    try {/*from   w w w  .  j  a v  a 2s .  co m*/
        htmlPages = ViewerUtils.getViewerHtmlHandler().getPages(filePath, htmlOptions);
    } catch (Exception x) {
        throw new ServletException(x);
    }
    temp_cssList = new ArrayList<String>();

    for (PageHtml page : htmlPages) {

        String fullHtml = page.getHtmlContent();
        String strippedHtml = "";
        if (fullHtml.indexOf("</title>") > 0 && fullHtml.indexOf("</head>") > 0) {
            strippedHtml += fullHtml.substring(fullHtml.indexOf("</title>") + "</title>".length(),
                    fullHtml.indexOf("</head>"));
        }
        if (fullHtml.indexOf("<body>") > 0 && fullHtml.indexOf("</body>") > 0) {
            strippedHtml += fullHtml.substring(fullHtml.indexOf("<body>") + "<body>".length(),
                    fullHtml.indexOf("</body>"));
        }
        page.setHtmlContent(strippedHtml);

        for (HtmlResource resource : page.getHtmlResources()) {

            if (resource.getResourceType() == HtmlResourceType.Style) {
                InputStream cssStream = ViewerUtils.getViewerHtmlHandler().getResource(filePath, resource);
                String text = IOUtils.toString(cssStream, "UTF-8");

                boolean needResave = false;
                if (text.indexOf("url(\"") >= 0
                        && text.indexOf("url(\"/GetResourceForHtml?documentPath=") < 0) {
                    needResave = true;
                    text = text.replace("url(\"", "url(\"/GetResourceForHtml?documentPath=" + filePath
                            + "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName=");
                }

                if (text.indexOf("url('") >= 0 && text.indexOf("url('/GetResourceForHtml?documentPath=") < 0) {
                    needResave = true;
                    text = text.replace("url('", String.format("url(\'/GetResourceForHtml?documentPath="
                            + filePath + "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName="));
                }

                temp_cssList.add(text);

                if (needResave) {

                    String fullPath = ViewerUtils.TEMP_PATH + filePath + "/" + "html" + "/" + "resources" + "/"
                            + "page" + page.getPageNumber() + "/" + resource.getResourceName();
                    File file = new File(fullPath);

                    // if file doesnt exists, then create it
                    if (!file.exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }

                    FileWriter fw = new FileWriter(file.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);
                    bw.write(text);
                    bw.close();

                }
            }
            /////////////////////////
        }
        ArrayList<String> cssClasses = Utils.GetCssClasses(page.getHtmlContent());
        for (String cssClass : cssClasses) {
            String newCssClass = "page-" + page.getPageNumber() + "-" + cssClass;

            page.setHtmlContent(page.getHtmlContent().replace(cssClass, newCssClass));
            for (int i = 0; i < temp_cssList.size(); i++) {
                temp_cssList.set(i, temp_cssList.get(i).replace(cssClass, newCssClass));
            }
        }
    }
    return htmlPages;

}

From source file:com.athena.meerkat.controller.web.provisioning.AbstractProvisioningService.java

/**
 * <pre>/*w w w .  j  av  a2s.co  m*/
 * send log to client(UI)
 * </pre>
 * 
 * @param session
 * @param jobPath
 */
private void sendLog(WebSocketSession session, String jobPath, boolean lastTask) {

    if (session != null) {

        LogTailerListener listener = new LogTailerListener(session, lastTask);
        long delay = 2000;
        File file = new File(jobPath + File.separator + "build.log");
        LOGGER.debug("log file : {}", file.getAbsoluteFile());

        Tailer tailer = new Tailer(file, listener, delay);
        new Thread(tailer).start();
    }

}