Example usage for org.apache.commons.io FilenameUtils getFullPath

List of usage examples for org.apache.commons.io FilenameUtils getFullPath

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getFullPath.

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

@Override
@NonTransactional//  w ww. j  ava  2  s  .  com
public ElectronicInvoiceLoad loadElectronicInvoices() {

    //add a step to check for directory paths
    prepareDirectories(getRequiredDirectoryNames());

    String rejectDirName = getRejectDirName();
    String acceptDirName = getAcceptDirName();
    emailTextErrorList = new StringBuffer();

    boolean moveFiles = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(
            ElectronicInvoiceStep.class,
            PurapParameterConstants.ElectronicInvoiceParameters.FILE_MOVE_AFTER_LOAD_IND);

    int failedCnt = 0;

    if (LOG.isInfoEnabled()) {
        LOG.info("Invoice Base Directory - " + electronicInvoiceInputFileType.getDirectoryPath());
        LOG.info("Invoice Accept Directory - " + acceptDirName);
        LOG.info("Invoice Reject Directory - " + rejectDirName);
        LOG.info("Is moving files allowed - " + moveFiles);
    }

    if (StringUtils.isBlank(rejectDirName)) {
        throw new RuntimeException("Reject directory name should not be empty");
    }

    if (StringUtils.isBlank(acceptDirName)) {
        throw new RuntimeException("Accept directory name should not be empty");
    }

    File[] filesToBeProcessed = getFilesToBeProcessed();
    ElectronicInvoiceLoad eInvoiceLoad = new ElectronicInvoiceLoad();

    if (filesToBeProcessed == null || filesToBeProcessed.length == 0) {

        StringBuffer mailText = new StringBuffer();

        mailText.append("\n\n");
        mailText.append(PurapConstants.ElectronicInvoice.NO_FILES_PROCESSED_EMAIL_MESSAGE);
        mailText.append("\n\n");

        sendSummary(mailText);
        return eInvoiceLoad;
    }

    try {
        /**
         * Create, if not there
         */
        FileUtils.forceMkdir(new File(acceptDirName));
        FileUtils.forceMkdir(new File(rejectDirName));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(filesToBeProcessed.length + " file(s) available for processing");
    }

    StringBuilder emailMsg = new StringBuilder();

    for (int i = 0; i < filesToBeProcessed.length; i++) {

        File xmlFile = filesToBeProcessed[i];
        LOG.info("Processing " + xmlFile.getName() + "....");

        byte[] modifiedXML = null;
        //process only if file exists and not empty
        if (xmlFile.length() != 0L) {
            modifiedXML = addNamespaceDefinition(eInvoiceLoad, xmlFile);
        }

        boolean isRejected = false;

        if (modifiedXML == null) {//Not able to parse the xml
            isRejected = true;
        } else {
            try {
                isRejected = processElectronicInvoice(eInvoiceLoad, xmlFile, modifiedXML);
            } catch (Exception e) {
                String msg = xmlFile.getName() + "\n";
                LOG.error(msg);

                //since getMessage() is empty we'll compose the stack trace and nicely format it.
                StackTraceElement[] elements = e.getStackTrace();
                StringBuffer trace = new StringBuffer();
                trace.append(e.getClass().getName());
                if (e.getMessage() != null) {
                    trace.append(": ");
                    trace.append(e.getMessage());
                }
                trace.append("\n");
                for (int j = 0; j < elements.length; ++j) {
                    StackTraceElement element = elements[j];

                    trace.append("    at ");
                    trace.append(describeStackTraceElement(element));
                    trace.append("\n");
                }

                LOG.error(trace);
                emailMsg.append(msg);
                msg += "\n--------------------------------------------------------------------------------------\n"
                        + trace;
                logProcessElectronicInvoiceError(msg);
                failedCnt++;

                /**
                 * Clear the error map, so that subsequent EIRT routing isn't prevented since rice
                 * is throwing a ValidationException if the error map is not empty before routing the doc.
                 */
                GlobalVariables.getMessageMap().clearErrorMessages();

                //Do not execute rest of code below
                continue;
            }
        }

        /**
         * If there is a single order has rejects and the remainings are accepted in a invoice file,
         * then the entire file has been moved to the reject dir.
         */
        if (isRejected) {
            if (LOG.isInfoEnabled()) {
                LOG.info(xmlFile.getName() + " has been rejected");
            }
            if (moveFiles) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(xmlFile.getName() + " has been marked to move to " + rejectDirName);
                }
                eInvoiceLoad.addRejectFileToMove(xmlFile, rejectDirName);
            }
        } else {
            if (LOG.isInfoEnabled()) {
                LOG.info(xmlFile.getName() + " has been accepted");
            }
            if (moveFiles) {
                if (!moveFile(xmlFile, acceptDirName)) {
                    String msg = xmlFile.getName() + " unable to move";
                    LOG.error(msg);
                    throw new PurError(msg);
                }
            }
        }

        if (!moveFiles) {
            String fullPath = FilenameUtils.getFullPath(xmlFile.getAbsolutePath());
            String fileName = FilenameUtils.getBaseName(xmlFile.getAbsolutePath());
            File processedFile = new File(fullPath + File.separator + fileName + ".processed");
            try {
                FileUtils.touch(processedFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //  delete the .done file
        deleteDoneFile(xmlFile);
    }

    emailTextErrorList.append("\nFAILED FILES\n");
    emailTextErrorList.append("-----------------------------------------------------------\n\n");
    emailTextErrorList.append(emailMsg);
    emailTextErrorList.append("\nTOTAL COUNT\n");
    emailTextErrorList.append("===========================\n");
    emailTextErrorList.append("      " + failedCnt + " FAILED\n");
    emailTextErrorList.append("===========================\n");

    StringBuffer summaryText = saveLoadSummary(eInvoiceLoad);

    StringBuffer finalText = new StringBuffer();
    finalText.append(summaryText);
    finalText.append("\n");
    finalText.append(emailTextErrorList);
    sendSummary(finalText);

    LOG.info("Processing completed");

    return eInvoiceLoad;

}

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

protected File[] getFilesToBeProcessed() {
    File[] filesToBeProcessed;/*  w  w w  . j  a  va 2s.  c  om*/
    String baseDirName = getBaseDirName();
    File baseDir = new File(baseDirName);
    if (!baseDir.exists()) {
        throw new RuntimeException("Base dir [" + baseDirName + "] doesn't exists in the system");
    }
    filesToBeProcessed = baseDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            String fullPath = FilenameUtils.getFullPath(file.getAbsolutePath());
            String fileName = FilenameUtils.getBaseName(file.getAbsolutePath());
            File processedFile = new File(fullPath + File.separator + fileName + ".processed");
            return (!file.isDirectory()
                    && file.getName().endsWith(electronicInvoiceInputFileType.getFileExtension())
                    && !processedFile.exists());
        }
    });

    return filesToBeProcessed;
}

From source file:org.kuali.ole.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

@Override
public ElectronicInvoiceLoad loadElectronicInvoices() {

    //add a step to check for directory paths
    prepareDirectories(getRequiredDirectoryNames());

    String baseDirName = getBaseDirName();
    String rejectDirName = getRejectDirName();
    String acceptDirName = getAcceptDirName();
    emailTextErrorList = new StringBuffer();

    boolean moveFiles = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(
            ElectronicInvoiceStep.class,
            PurapParameterConstants.ElectronicInvoiceParameters.FILE_MOVE_AFTER_LOAD_IND);

    int failedCnt = 0;

    if (LOG.isInfoEnabled()) {
        LOG.info("Invoice Base Directory - " + electronicInvoiceInputFileType.getDirectoryPath());
        LOG.info("Invoice Accept Directory - " + acceptDirName);
        LOG.info("Invoice Reject Directory - " + rejectDirName);
        LOG.info("Is moving files allowed - " + moveFiles);
    }/*from w  ww. j  a  v  a2s  .c o m*/

    if (StringUtils.isBlank(rejectDirName)) {
        throw new RuntimeException("Reject directory name should not be empty");
    }

    if (StringUtils.isBlank(acceptDirName)) {
        throw new RuntimeException("Accept directory name should not be empty");
    }

    File baseDir = new File(baseDirName);
    if (!baseDir.exists()) {
        throw new RuntimeException("Base dir [" + baseDirName + "] doesn't exists in the system");
    }

    File[] filesToBeProcessed = baseDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            String fullPath = FilenameUtils.getFullPath(file.getAbsolutePath());
            String fileName = FilenameUtils.getBaseName(file.getAbsolutePath());
            File processedFile = new File(fullPath + File.separator + fileName + ".processed");
            return (!file.isDirectory() && file.getName().endsWith(".xml") && !processedFile.exists());
        }
    });

    ElectronicInvoiceLoad eInvoiceLoad = new ElectronicInvoiceLoad();

    if (filesToBeProcessed == null || filesToBeProcessed.length == 0) {

        StringBuffer mailText = new StringBuffer();

        mailText.append("\n\n");
        mailText.append(PurapConstants.ElectronicInvoice.NO_FILES_PROCESSED_EMAIL_MESSAGE);
        mailText.append("\n\n");

        sendSummary(mailText);
        return eInvoiceLoad;
    }

    try {
        /**
         * Create, if not there
         */
        FileUtils.forceMkdir(new File(acceptDirName));
        FileUtils.forceMkdir(new File(rejectDirName));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(filesToBeProcessed.length + " file(s) available for processing");
    }

    StringBuilder emailMsg = new StringBuilder();

    for (File element2 : filesToBeProcessed) {

        // MSU Contribution DTT-3014 OLEMI-8483 OLECNTRB-974
        File xmlFile = element2;
        LOG.info("Processing " + xmlFile.getName() + "....");

        byte[] modifiedXML = null;
        // process only if file exists and not empty
        if (xmlFile.length() != 0L) {
            modifiedXML = addNamespaceDefinition(eInvoiceLoad, xmlFile);
        }

        boolean isRejected = false;

        if (modifiedXML == null) {//Not able to parse the xml
            isRejected = true;
        } else {
            try {
                isRejected = processElectronicInvoice(eInvoiceLoad, xmlFile, modifiedXML);
            } catch (Exception e) {
                String msg = xmlFile.getName() + "\n";
                LOG.error(msg);

                //since getMessage() is empty we'll compose the stack trace and nicely format it.
                StackTraceElement[] elements = e.getStackTrace();
                StringBuffer trace = new StringBuffer();
                trace.append(e.getClass().getName());
                if (e.getMessage() != null) {
                    trace.append(": ");
                    trace.append(e.getMessage());
                }
                trace.append("\n");
                for (StackTraceElement element : elements) {
                    trace.append("    at ");
                    trace.append(describeStackTraceElement(element));
                    trace.append("\n");
                }

                LOG.error(trace);
                emailMsg.append(msg);
                msg += "\n--------------------------------------------------------------------------------------\n"
                        + trace;
                logProcessElectronicInvoiceError(msg);
                failedCnt++;

                /**
                 * Clear the error map, so that subsequent EIRT routing isn't prevented since rice is throwing a
                 * ValidationException if the error map is not empty before routing the doc.
                 */
                GlobalVariables.getMessageMap().clearErrorMessages();

                //Do not execute rest of code below
                continue;
            }
        }

        /**
         * If there is a single order has rejects and the remainings are accepted in a invoice file,
         * then the entire file has been moved to the reject dir.
         */
        if (isRejected) {
            if (LOG.isInfoEnabled()) {
                LOG.info(xmlFile.getName() + " has been rejected");
            }
            if (moveFiles) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(xmlFile.getName() + " has been marked to move to " + rejectDirName);
                }
                eInvoiceLoad.addRejectFileToMove(xmlFile, rejectDirName);
            }
        } else {
            if (LOG.isInfoEnabled()) {
                LOG.info(xmlFile.getName() + " has been accepted");
            }
            if (moveFiles) {
                if (!moveFile(xmlFile, acceptDirName)) {
                    String msg = xmlFile.getName() + " unable to move";
                    LOG.error(msg);
                    throw new PurError(msg);
                }
            }
        }

        if (!moveFiles) {
            String fullPath = FilenameUtils.getFullPath(xmlFile.getAbsolutePath());
            String fileName = FilenameUtils.getBaseName(xmlFile.getAbsolutePath());
            File processedFile = new File(fullPath + File.separator + fileName + ".processed");
            try {
                FileUtils.touch(processedFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //  delete the .done file
        deleteDoneFile(xmlFile);
    }

    emailTextErrorList.append("\nFAILED FILES\n");
    emailTextErrorList.append("-----------------------------------------------------------\n\n");
    emailTextErrorList.append(emailMsg);
    emailTextErrorList.append("\nTOTAL COUNT\n");
    emailTextErrorList.append("===========================\n");
    emailTextErrorList.append("      " + failedCnt + " FAILED\n");
    emailTextErrorList.append("===========================\n");

    StringBuffer summaryText = saveLoadSummary(eInvoiceLoad);

    StringBuffer finalText = new StringBuffer();
    finalText.append(summaryText);
    finalText.append("\n");
    finalText.append(emailTextErrorList);
    sendSummary(finalText);

    LOG.info("Processing completed");

    return eInvoiceLoad;

}

From source file:org.kyasuda.docwaza.cli.Convert.java

public static void main(String[] arguments) throws ParseException, JSONException, IOException {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    String outputFormat = null;//from w w  w  .ja  va2s  . c om
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    int port = DEFAULT_OFFICE_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
        String syntax = "java net.sf.jodconverter.cli.Convert [options] input-file output-file; or\n"
                + "[options] -f output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(STATUS_INVALID_ARGUMENTS);
    }

    DocumentFormatRegistry registry;
    if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) {
        File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt()));
        registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile));
    } else {
        registry = new DefaultDocumentFormatRegistry();
    }

    OfficeManager officeManager = new DefaultOfficeManagerConfiguration().setPortNumber(port)
            .buildOfficeManager();
    officeManager.start();
    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry);
    try {
        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            converter.convert(inputFile, outputFile);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat;
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName);
                converter.convert(inputFile, outputFile);
            }
        }
    } finally {
        officeManager.stop();
    }
}

From source file:org.localmatters.lesscss4j.compile.LessCssCompilerErrorTest.java

public void testImportMissingError() throws IOException, URISyntaxException {
    String resource = "less/exceptions/import-error.less";
    compileAndValidate(resource, null);//  w  w w  .ja va 2s . c  o m

    URL url = getClass().getClassLoader().getResource(resource);

    String baseDir = FilenameUtils.getFullPath(new File(url.toURI()).getAbsolutePath());

    assertEquals("import-error.less [2:8] - Import error: \"bogus.less\": File '" + baseDir
            + "bogus.less' does not exist\n"
            + "imported-with-error.less [1:8] - Import error: url(nope.less): File '" + baseDir
            + "nope.less' does not exist\n" + "import-error.less [4:8] - Import error: 'missing.less': File '"
            + baseDir + "missing.less' does not exist\n", _writer.toString());
    assertEquals(3, _errorHandler.getErrorCount());
}

From source file:org.metamorfosis.template.directive.freemarker.AppendFileSection.java

@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
    log.debug("Ejecutando <@" + getDirectiveName() + " .../>");

    // Validar parametros
    if (params.isEmpty()) {
        throw new DirectiveException(msgErr);
    }//from www  . j  a v a 2s.  c  o m

    if (loopVars.length != 0) {
        throw new DirectiveException("<@" + getDirectiveName() + " .../> no acepta loop variables.");
    }

    // If there is non-empty nested content:
    if (body != null) {
        try {
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            String filePath = null;
            String position = null;
            String ocurrenceCount = null;
            String ocurrence = null;

            Set<Entry<String, SimpleScalar>> entrySet = params.entrySet();
            for (Entry<String, SimpleScalar> entry : entrySet) {
                String key = entry.getKey();
                SimpleScalar value = entry.getValue();
                if (key.equals(FILE_PATH)) {
                    filePath = value.getAsString();
                } else if (key.equals(POSITION)) {
                    position = value.getAsString();
                } else if (key.equals(OCURRENCE_COUNT)) {
                    ocurrenceCount = value.getAsString();
                } else if (key.equals(OCURRENCE)) {
                    ocurrence = value.getAsString();
                } else {
                    throw new DirectiveException(
                            "<@" + getDirectiveName() + " .../> no acepta el parmetro '" + key + "'");
                }
            }

            // Escribir resultado del procesamiento en un buffer
            StringWriter sw = new StringWriter();
            BufferedWriter bw = new BufferedWriter(sw);
            body.render(bw);
            env.getOut().flush();
            bw.flush();
            sw.flush();
            bw.close();
            sw.close();

            // =============================================================
            // 1. El filePath debe existir dentro del proyecto
            ExternalProject project = SpringUtils.getProject();
            File absProjectPath = project.getInProjectPath(filePath);
            if (!project.existsInProject(filePath)) {
                throw new DirectiveException("<@AppendFileSection .../> " + "No se encuentra el archivo '"
                        + absProjectPath + "', " + "se requiere que exista el filePath '" + filePath + "' "
                        + "dentro del proyecto original");
            }

            File fFilePath = project.getInProjectPath(filePath);
            String originalFileStr = FileUtils.readFileToString(fFilePath);
            AppendFileSectionLogic logic = new AppendFileSectionLogic(originalFileStr, sw.toString());
            String result = logic.process(position, ocurrenceCount, ocurrence);

            String outputFolder = FilenameUtils.getFullPath(filePath);
            String outputFileName = FilenameUtils.getName(filePath);

            TemplateProcessed tp = new TemplateProcessed(originalFileStr, outputFolder, outputFileName, result);

            // notificar a los observadores
            super.setChanged();
            super.notifyObservers(tp);

        } catch (TemplateException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        } catch (IOException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        }

    } else {
        throw new DirectiveException("<@" + getDirectiveName() + "missing body");
    }
}

From source file:org.metamorfosis.template.freemarker.AbstractFreemarkerTestCase.java

protected void assertEqualsFreemarkerTemplate(Object rootMap, String expectedResult, File template)
        throws Exception {
    String fullPath = FilenameUtils.getFullPath(template.getAbsolutePath());
    cfg.setDirectoryForTemplateLoading(new File(fullPath));

    String relativeTemplate = FilenameUtils.getName(template.getAbsolutePath());
    freemarker.template.Template freeMarkerTemplate = cfg.getTemplate(relativeTemplate);

    StringWriter sw = new StringWriter();
    Environment env = freeMarkerTemplate.createProcessingEnvironment(rootMap, sw);
    env.process(); // process the template

    assertEquals(expectedResult, sw.toString());
    sw.close();/*  w w  w. ja  v a  2 s  . com*/
}

From source file:org.mrgeo.hdfs.vector.shp.ShapefileReader.java

@SuppressFBWarnings(value = { "WEAK_FILENAMEUTILS",
        "PATH_TRAVERSAL_IN" }, justification = "Correctly filtered parameters")
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException {
    fileName = in.readUTF();/*  w w  w  .j  a v a 2 s.c o m*/
    source = Source.values()[in.readInt()];

    if (source == Source.FILE) {
        File f = new File(FilenameUtils.getFullPath(fileName), FilenameUtils.getName(fileName));
        if (f.exists()) {
            load(fileName);
        }
    } else {
        if (HadoopFileUtils.exists(fileName)) {
            load(new Path(fileName));
        }
    }
}

From source file:org.mule.tools.rhinodo.rhino.NodeJsUrlModuleSourceProvider.java

@Override
protected ModuleSource loadFromUri(URI uri, URI base, Object validator) throws IOException, URISyntaxException {

    if (base == null || uri == null) {
        return null;
    }/*from   w ww  .j  a v a 2s. c  o  m*/

    File newUri = null;
    if (!uri.getPath().equals(base.getPath())) {
        String basePath = FilenameUtils.getFullPath(base.getPath().substring(0, base.getPath().length() - 1));
        String originalUri = uri.getPath();

        if (originalUri.contains(base.getPath())) {
            originalUri = basePath + originalUri.replace(base.getPath(), "");
        }

        newUri = NodeModuleImpl.cleanUpPathToModule("", originalUri);
    } else {
        newUri = new File(uri.getPath());
    }

    return super.loadFromUri(newUri.toURI(), base, validator);
}

From source file:org.mule.tools.rhinodo.rhino.NodeRequireBuilder.java

private String getModulePath(Scriptable scope) {
    Scriptable module = (Scriptable) scope.get("module", scope);
    String moduleUriString = Context.toString(module.get("uri", module));
    URI moduleUri;/*from w  w w.  ja v  a2  s  . c  o  m*/
    try {
        moduleUri = new URI(moduleUriString);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Invalid URI " + moduleUriString);
    }

    return FilenameUtils.getFullPath(moduleUri.getPath());
}