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

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

Introduction

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

Prototype

public static String getPathNoEndSeparator(String filename) 

Source Link

Document

Gets the path from a full filename, which excludes the prefix, and also excluding the final directory separator.

Usage

From source file:org.bdval.ConsensusBDVModel.java

/**
 * Save the juror models to a set of files. The files will contain all the information needed
 * to apply the BDVal model to new samples.
 *
 * @param zipStream The stream used to write the models to
 * @param options The options associated with this model
 * @param task The classification task used for this model
 * @param splitPlan The split plan used to generat this model
 * @param writeModelMode The mode saving the model
 * @throws IOException if there is a problem writing to the files
 *///from   w  w w  .j a  va2  s . c om
private synchronized void saveJurorModels(final ZipOutputStream zipStream, final DAVOptions options,
        final ClassificationTask task, final SplitPlan splitPlan, final WriteModel writeModelMode)
        throws IOException {
    if (!jurorModelsAreLoaded) {
        throw new IllegalStateException("juror models must be loaded before save");
    }

    // add the models directory entry for juror models (must end in "/")
    zipStream.putNextEntry(new ZipEntry(JUROR_MODEL_DIRECTORY + "/"));
    zipStream.closeEntry();

    final String jurorModelDirectory = JUROR_MODEL_DIRECTORY + "/"
            + FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(modelFilenamePrefix)) + "/";
    zipStream.putNextEntry(new ZipEntry(jurorModelDirectory));
    zipStream.closeEntry();

    for (final BDVModel jurorModel : jurorModels) {
        // NOTE: for zip files, the directory MUST use "/" regardless of OS

        final String jurorModelFilename = jurorModelDirectory
                + FilenameUtils.getName(jurorModel.getModelFilenamePrefix()) + ".zip";

        // Add ZIP entry for the model to output stream.
        zipStream.putNextEntry(new ZipEntry(jurorModelFilename));

        // Create the ZIP file for the juror
        LOG.debug("Writing juror model as entry: " + jurorModelFilename);
        final ZipOutputStream jurorZipStream = new ZipOutputStream(zipStream);
        jurorZipStream.setComment("Juror model: " + jurorModel.getModelFilenamePrefix());
        jurorModel.save(jurorZipStream, options, task, splitPlan, writeModelMode);
        jurorZipStream.finish(); // NOTE: we don't close the stream, that will close everything

        zipStream.closeEntry();
    }
}

From source file:org.geoserver.web.GeoServerResourceStreamLocator.java

@Override
public IResourceNameIterator newResourceNameIterator(String path, Locale locale, String style, String variation,
        String extension, boolean strict) {

    Iterable<String> extensions = null;

    // if the resource under the geoserver or wicket namespace?
    if (path.startsWith("org/geoserver") || path.startsWith("org/apache/wicket")) {
        String ext = extension;/*  w  ww.  jav a  2 s  . co  m*/
        if (ext == null) {
            // no extension passed in, strip it from the path
            ext = FilenameUtils.getExtension(path);
        }

        if (ext != null) {
            // we have an extension, look it up in the whitelist
            extensions = PREFIXES.get(ext);
        }
    }

    if (extensions != null) {
        // ensure the path doesn't contain the extension, sometimes this method is called with extension == null, 
        // in which case the extension is usually in the path
        path = FilenameUtils.getPathNoEndSeparator(path) + "/" + FilenameUtils.getBaseName(path);
        return new ResourceNameIterator(path, style, variation, null, extensions, false);
    }

    // couldn't optimize, just pass through to parent
    return super.newResourceNameIterator(path, locale, style, variation, extension, strict);
}

From source file:org.jfrog.build.extractor.clientConfiguration.util.PublishedItemsHelper.java

/**
 * Calculates the target deployment path of an artifact by it's name
 *
 * @param targetPattern an Ant pattern of the target path
 * @param artifactFile  the artifact file to calculate target deployment path for
 * @return the calculated target path//from  ww w .  j  a v  a  2s .c o m
 */
public static String calculateTargetPath(String targetPattern, File artifactFile) {
    String relativePath = calculateTargetRelativePath(artifactFile);
    if (relativePath == null) {
        throw new IllegalArgumentException("Cannot calculate a target path given a null relative path.");
    }

    if (StringUtils.isBlank(targetPattern)) {
        return relativePath;
    }

    relativePath = FilenameUtils.separatorsToUnix(relativePath);
    targetPattern = FilenameUtils.separatorsToUnix(targetPattern);

    // take care of absolute path
    if (StringUtils.startsWith(targetPattern, "/")) {
        return targetPattern + "/" + artifactFile.getName();
    }

    // take care of relative paths with patterns.
    StringBuilder itemPathBuilder = new StringBuilder();

    String[] targetTokens = targetPattern.split("/");

    boolean addedRelativeParent = false;
    for (int i = 0; i < targetTokens.length; i++) {

        boolean lastToken = (i == (targetTokens.length - 1));

        String targetToken = targetTokens[i];

        if ("**".equals(targetToken)) {
            if (!lastToken) {
                String relativeParentPath = FilenameUtils.getPathNoEndSeparator(relativePath);
                itemPathBuilder.append(relativeParentPath);
                addedRelativeParent = true;
            } else {
                itemPathBuilder.append(relativePath);
            }
        } else if (targetToken.startsWith("*.")) {
            String newFileName = FilenameUtils.removeExtension(FilenameUtils.getName(relativePath))
                    + targetToken.substring(1);
            itemPathBuilder.append(newFileName);
        } else if ("*".equals(targetToken)) {
            itemPathBuilder.append(FilenameUtils.getName(relativePath));
        } else {
            if (StringUtils.isNotBlank(targetToken)) {
                itemPathBuilder.append(targetToken);
            }
            if (lastToken) {
                if (itemPathBuilder.length() > 0) {
                    itemPathBuilder.append("/");
                }
                if (addedRelativeParent) {
                    itemPathBuilder.append(FilenameUtils.getName(relativePath));
                } else {
                    itemPathBuilder.append(relativePath);
                }
            }
        }

        if (!lastToken) {
            itemPathBuilder.append("/");
        }
    }
    return itemPathBuilder.toString();
}

From source file:org.jooby.assets.LessStrSource.java

public LessStrSource(final String content, final String name) {
    super(content, name);
    this.path = spath(FilenameUtils.getPathNoEndSeparator(name));
}

From source file:org.mycore.common.content.MCRContent.java

private String getFilenameFromSystemId() {
    String fileName = systemId;//www  .  ja  va 2 s . com
    String path = null;
    try {
        path = new URL(systemId).getPath();
    } catch (MalformedURLException e) {
        LogManager.getLogger(getClass()).debug("Could not get file name from URL.", e);
        try {
            path = new URI(systemId).getPath();
        } catch (URISyntaxException e2) {
            LogManager.getLogger(getClass()).debug("Could not get file name from URI.", e2);
        }
    }
    if (path != null) {
        fileName = path;
    }
    if (fileName.endsWith("/")) {
        fileName = FilenameUtils.getPathNoEndSeparator(fileName); //removes final '/';
    }
    return FilenameUtils.getName(fileName);
}

From source file:org.mycore.common.content.MCRURLContent.java

public MCRURLContent(URL url) {
    super();//from   ww w.  jav  a  2 s .  c o m
    this.url = url;
    this.setSystemId(url.toString());
    String fileName = url.getPath();
    if (fileName.endsWith("/")) {
        fileName = FilenameUtils.getPathNoEndSeparator(fileName); //removes final '/';
    }
    setName(FilenameUtils.getName(fileName));
}

From source file:org.opencastproject.workflow.handler.ResumableWorkflowOperationHandlerBase.java

/**
 * Registers the resource identified by <code>resourcePath</code> as the ui to be displayed during hold.
 * //from   w w  w.  j a v  a2  s.  c om
 * @param resourcePath
 *          the path to the resource
 * @return the URL that was created when registering the resource
 */
protected String registerHoldStateUserInterface(final String resourcePath) {
    String alias = "/workflow/hold/" + getClass().getName().toLowerCase();
    if (resourcePath == null)
        throw new IllegalArgumentException("Classpath must not be null");
    String path = FilenameUtils.getPathNoEndSeparator(resourcePath);
    String welcomeFile = FilenameUtils.getName(resourcePath);
    staticResource = new StaticResource(getClass().getClassLoader(), path, alias, welcomeFile);
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put("contextId", RestConstants.HTTP_CONTEXT_ID);
    props.put("alias", alias);
    staticResourceRegistration = componentContext.getBundleContext().registerService(Servlet.class.getName(),
            staticResource, props);
    return staticResource.getDefaultUrl();
}

From source file:org.pentaho.cdf.render.CdfHtmlRenderer.java

public void execute(OutputStream out, IBasicFile dashboardTemplateFile, String style,
        String dashboardsMessagesBaseFilename, HashMap<String, String> parameterMap, String user,
        int inactiveInterval, boolean isRequire, boolean loadTheme) throws Exception {

    String intro = ""; //$NON-NLS-1$
    String footer = ""; //$NON-NLS-1$

    IReadAccess systemAccess = getPluginSystemReader(null);
    style = StringUtils.isEmpty(style) ? "" : "-" + style;

    final String dashboardTemplate = "template-dashboard" + style + ".html"; //$NON-NLS-1$

    ArrayList<String> i18nTagsList = new ArrayList<String>();
    final String requireDashboardTemplate = "template-dashboard" + style + "-require.html";
    IBasicFile templateResourceFile = null;
    IReadAccess pluginRepoAccess = getPluginRepositoryReader("templates/");

    if (isRequire && pluginRepoAccess.fileExists(requireDashboardTemplate)) {
        templateResourceFile = pluginRepoAccess.fetchFile(requireDashboardTemplate);
    } else if (isRequire && systemAccess.fileExists(requireDashboardTemplate)) {
        templateResourceFile = systemAccess.fetchFile(requireDashboardTemplate);
    } else if (pluginRepoAccess.fileExists(dashboardTemplate)) {
        templateResourceFile = pluginRepoAccess.fetchFile(dashboardTemplate);
    } else if (systemAccess.fileExists(dashboardTemplate)) {
        // then try in system
        templateResourceFile = systemAccess.fetchFile(dashboardTemplate);
    }//  w  w  w. ja v  a  2s .  c o  m

    String templateContent;
    if (templateResourceFile != null) { //if a file was obtained correctly
        templateContent = getContentString(templateResourceFile.getContents());
    } else { //if not get a default one
        logger.error(
                "Template " + dashboardTemplate + " not available on cdf/templates, loading fallback instead");
        templateContent = getContentString(systemAccess.fetchFile("template-dashboard.html").getContents());
    }

    if (!isRequire) {
        // Process i18n on dashboard outer template
        templateContent = updateUserLanguageKey(templateContent);
        templateContent = processi18nTags(templateContent, i18nTagsList);
        // Process i18n on dashboard outer template - end
    }

    ITemplater templater = getTemplater();

    intro = templater.getTemplateSection(templateContent, Section.HEADER);
    footer = templater.getTemplateSection(templateContent, Section.FOOTER);

    final String dashboardContent = getDashboardContent(dashboardTemplateFile.getContents(), i18nTagsList);

    // Merge dashboard related message file with global message file and save it in the dashboard cache
    String path = StringUtils.defaultIfEmpty(
            FilenameUtils.getPathNoEndSeparator(dashboardTemplateFile.getPath()), getPluginRepositoryDir());
    path = !path.startsWith(String.valueOf(RepositoryHelper.SEPARATOR)) ? RepositoryHelper.SEPARATOR + path
            : path;

    if (!isRequire) {
        intro = getMessageBundlesHelper(path).replaceParameters(intro, i18nTagsList);
    }

    /*
     * Add cdf libraries
     */
    // final Date startDate = new Date();
    final int headIndex = intro.indexOf("<head>");
    final int length = intro.length();
    // final Hashtable addedFiles = new Hashtable();

    out.write(intro.substring(0, headIndex + 6).getBytes(CharsetHelper.getEncoding()));
    if (!isRequire) { // Concat libraries to html head content
        getHeadersInternal(dashboardContent, parameterMap, out);
    } else { // add the webcontext dependency checking if webcontext should load pentaho active theme
        getWebContextHeader(out, loadTheme);
    }
    out.write(intro.substring(headIndex + 6, length).getBytes(CharsetHelper.getEncoding()));

    if (!isRequire) {
        // Add context
        try {
            generateContext(out, parameterMap, inactiveInterval);
        } catch (Exception e) {
            logger.error("Error generating cdf context.", e);
        }
        // Add storage
        try {
            generateStorage(out, user);
        } catch (Exception e) {
            logger.error("Error in cdf storage.", e);
        }
    } else {
        out.write(
                MessageFormat
                        .format(CdfConstants.INLINE_SCRIPT,
                                "requireCfg.config = requireCfg.config || {};\n"
                                        + "requireCfg.config['cdf/dashboard/Dashboard'] = "
                                        + getConfiguration(path, parameterMap, inactiveInterval) + ";\n"
                                        + "requirejs.config(requireCfg);")
                        .getBytes(CharsetHelper.getEncoding()));
    }

    out.write("<div id=\"dashboardContent\">".getBytes(CharsetHelper.getEncoding()));

    out.write(dashboardContent.getBytes(CharsetHelper.getEncoding()));
    out.write("</div>".getBytes(CharsetHelper.getEncoding()));
    out.write(footer.getBytes(CharsetHelper.getEncoding()));
}

From source file:org.pentaho.platform.plugin.action.kettle.KettleComponent.java

/**
 * Execute the specified transformation in the chosen repository.
 *//*from   w  ww. java2s .co m*/
@SuppressWarnings("unchecked")
@Override
public boolean executeAction() {

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Kettle.DEBUG_START")); //$NON-NLS-1$
    }

    TransMeta transMeta = null;
    JobMeta jobMeta = null;

    // Build lists of parameters, variables and command line arguments

    Map<String, String> argumentMap = new HashMap<String, String>();
    Map<String, String> variableMap = new HashMap<String, String>();
    Map<String, String> parameterMap = new HashMap<String, String>();

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_CMD_ARG)) {
        argumentMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_VARIABLE)) {
        variableMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_PARAMETER)) {
        parameterMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    String[] arguments = null;

    // If no mappings are provided, assume all inputs are command line
    // arguments (This supports the legacy method)
    if (argumentMap.size() <= 0 && variableMap.size() <= 0 && parameterMap.size() <= 0) {
        // this use is now considered obsolete, as we prefer the
        // action-sequence inputs since they
        // now maintain order
        boolean running = true;
        int index = 1;
        ArrayList<String> argumentList = new ArrayList<String>();
        while (running) {
            if (isDefinedInput("parameter" + index)) { //$NON-NLS-1$
                String value = null;
                String inputName = getInputStringValue("parameter" + index); //$NON-NLS-1$
                // see if we have an input with this name
                if (isDefinedInput(inputName)) {
                    value = getInputStringValue(inputName);
                }
                argumentList.add(value);
            } else {
                running = false;
            }
            index++;
        }

        // this is the preferred way to provide inputs to the
        // KetteComponent, the order of inputs is now preserved
        Iterator<?> inputNamesIter = getInputNames().iterator();
        while (inputNamesIter.hasNext()) {
            String name = (String) inputNamesIter.next();
            argumentList.add(getInputStringValue(name));
        }

        arguments = (String[]) argumentList.toArray(new String[argumentList.size()]);
    } else {
        // Extract arguments from argumentMap (Throw an error if the
        // sequential ordering is broken)
        arguments = new String[argumentMap.size()];
        for (int i = 0; i < argumentMap.size(); i++) {
            arguments[i] = argumentMap.get(Integer.toString(i + 1)); // Mapping
            // is
            // 1
            // based
            // to
            // match
            // Kettle
            // UI
            if (arguments[i] == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0030_INVALID_ARGUMENT_MAPPING")); //$NON-NLS-1$
            }
        }
    }

    // initialize environment variables
    try {
        KettleSystemListener.environmentInit(getSession());
    } catch (KettleException ke) {
        error(ke.getMessage(), ke);
    }

    String solutionPath = "solution:";

    Repository repository = connectToRepository();
    boolean result = false;

    try {
        if (isDefinedInput(KettleComponent.DIRECTORY)) {
            String directoryName = getInputStringValue(KettleComponent.DIRECTORY);

            if (repository == null) {
                return false;
            }

            if (isDefinedInput(KettleComponent.TRANSFORMATION)) {
                String transformationName = getInputStringValue(KettleComponent.TRANSFORMATION);
                transMeta = loadTransformFromRepository(directoryName, transformationName, repository);
                if (transMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            transMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            transMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    transMeta.setArguments(arguments);
                } else {
                    return false;
                }
            } else if (isDefinedInput(KettleComponent.JOB)) {
                String jobName = getInputStringValue(KettleComponent.JOB);
                jobMeta = loadJobFromRepository(directoryName, jobName, repository);
                if (jobMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            jobMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            jobMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    jobMeta.setArguments(arguments);
                } else {
                    return false;
                }
            }
        } else if (isDefinedResource(KettleComponent.TRANSFORMFILE)) {
            IActionSequenceResource transformResource = getResource(KettleComponent.TRANSFORMFILE);
            String fileAddress = getActualFileName(transformResource);

            try {
                if (fileAddress != null) { // We have an actual loadable
                    // filesystem and file
                    transMeta = new TransMeta(fileAddress, repository, true);
                    transMeta.setFilename(fileAddress);
                } else if (repository != null && repository.isConnected()) {

                    fileAddress = transformResource.getAddress();
                    // load transformation resource from kettle/settings.xml configured repository
                    transMeta = loadTransformFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);
                } else {
                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.TRANSFORMFILE));
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    // create a tranformation from the document
                    transMeta = new TransMeta(doc.getFirstChild(), repository);
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.TRANSFORMFILE, fileAddress), e);
                return false;
            }

            /*
             * Unreachable code below... if (transMeta == null) {
             * error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", KettleComponent.TRANSFORMFILE,
             * fileAddress)); //$NON-NLS-1$ debug(getKettleLog(true)); return false; }
             */

            // Don't forget to set the parameters here as well...
            try {
                for (String key : parameterMap.keySet()) {
                    transMeta.setParameterValue(key, parameterMap.get(key));
                }
                for (String key : variableMap.keySet()) {
                    transMeta.setVariable(key, variableMap.get(key));
                }

            } catch (UnknownParamException e) {
                error(e.getMessage());
            }
            transMeta.setArguments(arguments);
            /*
             * We do not need to concatenate the solutionPath info as the fileAddress has the complete location of the file
             * from start to end. This is to resolve BISERVER-502.
             */
            transMeta.setFilename(fileAddress);

        } else if (isDefinedResource(KettleComponent.JOBFILE)) {
            String fileAddress = ""; //$NON-NLS-1$
            try {
                fileAddress = getResource(KettleComponent.JOBFILE).getAddress();

                if (repository != null && repository.isConnected()) {

                    solutionPath = StringUtils.EMPTY;

                    // load job resource from kettle/settings.xml configured repository
                    jobMeta = loadJobFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);

                } else {

                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.JOBFILE));
                    // String jobXmlStr =
                    // XmlW3CHelper.getContentFromSolutionResource(fileAddress);
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    if (doc == null) {
                        error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                                KettleComponent.JOBFILE, fileAddress));
                        debug(getKettleLog(true));
                        return false;
                    }
                    // create a job from the document
                    try {
                        repository = connectToRepository();
                        // if we get a valid repository its great, if not try it
                        // without

                        jobMeta = new JobMeta(solutionPath + fileAddress, repository);
                    } catch (Exception e) {
                        error(Messages.getInstance().getString("Kettle.ERROR_0023_NO_META"), e); //$NON-NLS-1$
                    } finally {
                        if (repository != null) {
                            if (ComponentBase.debug) {
                                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
                            }
                            repository.disconnect();
                        }
                    }
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress), e);
                return false;
            }
            if (jobMeta == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress));
                debug(getKettleLog(true));
                return false;
            } else {
                try {
                    for (String key : parameterMap.keySet()) {
                        jobMeta.setParameterValue(key, parameterMap.get(key));
                    }
                    for (String key : variableMap.keySet()) {
                        jobMeta.setVariable(key, variableMap.get(key));
                    }

                } catch (UnknownParamException e) {
                    error(e.getMessage());
                }
                jobMeta.setArguments(arguments);
                jobMeta.setFilename(solutionPath + fileAddress);
            }

        }

        // OK, we have the information, let's load and execute the
        // transformation or job

        if (transMeta != null) {
            result = executeTransformation(transMeta);
        }
        if (jobMeta != null) {
            result = executeJob(jobMeta, repository);
        }

    } finally {

        if (repository != null) {
            if (ComponentBase.debug) {
                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
            }
            try {
                repository.disconnect();
            } catch (Exception ignored) {
                //ignore
            }
        }

        if (transMeta != null) {
            try {
                cleanLogChannel(transMeta);
                transMeta.clear();
            } catch (Exception ignored) {
                //ignore
            }
            transMeta = null;
        }
        if (jobMeta != null) {
            try {
                cleanLogChannel(jobMeta);
                jobMeta.clear();
            } catch (Exception ignored) {
                //ignored
            }
            // Can't do anything about an exception here.
            jobMeta = null;
        }
    }

    if (isDefinedOutput(EXECUTION_LOG_OUTPUT)) {
        setOutputValue(EXECUTION_LOG_OUTPUT, executionLog);
    }

    if (isDefinedOutput(EXECUTION_STATUS_OUTPUT)) {
        setOutputValue(EXECUTION_STATUS_OUTPUT, executionStatus);
    }

    XMLHandlerCache.getInstance().clear();
    return result;

}

From source file:org.pentaho.platform.plugin.kettle.PdiContentGenerator.java

public void execute() throws Exception {

    String pdiPath = repositoryFile.getPath();
    // Test//  www.  j  ava 2 s.c o m
    pdiComponent.setDirectory(FilenameUtils.getPathNoEndSeparator(pdiPath));

    // see if we are running a transformation or job
    if (repositoryFile.getName().toLowerCase().endsWith(".ktr")) { //$NON-NLS-1$
        pdiComponent.setTransformation(FilenameUtils.getBaseName(pdiPath));
    } else if (repositoryFile.getName().toLowerCase().endsWith(".kjb")) { //$NON-NLS-1$
        pdiComponent.setJob(FilenameUtils.getBaseName(pdiPath));
    }
    IPentahoSession session = PentahoSessionHolder.getSession();
    long start = System.currentTimeMillis();
    try {
        AuditHelper.audit(session.getId(), session.getName(), pdiPath, getObjectName(),
                this.getClass().getName(), MessageTypes.INSTANCE_START, instanceId, "", 0, this); //$NON-NLS-1$
        // now execute
        pdiComponent.execute();
        AuditHelper.audit(session.getId(), session.getName(), pdiPath, getObjectName(),
                this.getClass().getName(), MessageTypes.INSTANCE_END, instanceId, "", //$NON-NLS-1$
                ((float) (System.currentTimeMillis() - start) / 1000), this);
    } catch (Exception ex) {
        AuditHelper.audit(session.getId(), session.getName(), pdiPath, getObjectName(),
                this.getClass().getName(), MessageTypes.INSTANCE_FAILED, instanceId, "",
                ((float) (System.currentTimeMillis() - start) / 1000), this); // $NON-NLS-1$
        logger.error(ex);
        clearOutputBuffer();
        throw ex;
    }

    // Verify if the transformation prepareExecution failed or if there is any error in execution, as this exception is logged
    // and not thrown back
    if (!pdiComponent.isExecutionSuccessful()) {
        clearOutputBuffer();
        String errorMessage = Messages.getInstance()
                .getErrorString("Kettle.ERROR_0011_TRANSFORMATION_PREPARATION_FAILED");
        AuditHelper.audit(session.getId(), session.getName(), pdiPath, getObjectName(),
                this.getClass().getName(), MessageTypes.INSTANCE_FAILED, instanceId, errorMessage,
                ((float) (System.currentTimeMillis() - start) / 1000), this); // $NON-NLS-1$

        outputStringBuilder = pdiComponent.isTransPrepareExecutionFailed() ? writeFailureMessage()
                : writeFinishedWithErrorsMessage();
        out.write(outputStringBuilder.toString().getBytes());

        return;
    }

    /**
     * Earlier after the execution is completed, code would display the content of LoggingBuffer. But the logs in the
     * LoggingBuffer is not limited to the specified transformation that is being executed and can contains the logging
     * for other transformations that are being executed by other users. To resolve this, the code is modified to
     * display the string "Action Successful" when transformation is executed successfully and display a generic error
     * page in case of exception. The detailed logging will continue to go to the log file
     */
    outputStringBuilder = writeFinishedMessage();
    out.write(outputStringBuilder.toString().getBytes());
}