Example usage for org.apache.commons.vfs FileObject close

List of usage examples for org.apache.commons.vfs FileObject close

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject close.

Prototype

public void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

Usage

From source file:org.pentaho.di.trans.steps.mail.Mail.java

private void setAttachedFilesList(Object[] r, LogChannelInterface log) throws Exception {
    String realSourceFileFoldername = null;
    String realSourceWildcard = null;
    FileObject sourcefile = null;
    FileObject file = null;/*from w  w  w  . j ava 2  s . co m*/

    ZipOutputStream zipOutputStream = null;
    File masterZipfile = null;

    if (meta.isZipFilenameDynamic()) {
        data.ZipFilename = data.previousRowMeta.getString(r, data.indexOfDynamicZipFilename);
    }

    try {

        if (meta.isDynamicFilename()) {
            // dynamic attached filenames
            if (data.indexOfSourceFilename > -1) {
                realSourceFileFoldername = data.previousRowMeta.getString(r, data.indexOfSourceFilename);
            }

            if (data.indexOfSourceWildcard > -1) {
                realSourceWildcard = data.previousRowMeta.getString(r, data.indexOfSourceWildcard);
            }

        } else {
            // static attached filenames
            realSourceFileFoldername = data.realSourceFileFoldername;
            realSourceWildcard = data.realSourceWildcard;
        }

        if (!Const.isEmpty(realSourceFileFoldername)) {
            sourcefile = KettleVFS.getFileObject(realSourceFileFoldername, getTransMeta());
            if (sourcefile.exists()) {
                long FileSize = 0;
                FileObject[] list = null;
                if (sourcefile.getType() == FileType.FILE) {
                    list = new FileObject[1];
                    list[0] = sourcefile;
                } else {
                    list = sourcefile
                            .findFiles(new TextFileSelector(sourcefile.toString(), realSourceWildcard));
                }
                if (list.length > 0) {

                    boolean zipFiles = meta.isZipFiles();
                    if (zipFiles && data.zipFileLimit == 0) {
                        masterZipfile = new File(
                                System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename);

                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
                    }

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

                        file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]), getTransMeta());

                        if (zipFiles) {

                            if (data.zipFileLimit == 0) {
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();
                            } else {
                                FileSize += file.getContent().getSize();
                            }
                        } else {
                            addAttachedFilePart(file);
                        }
                    } // end for
                    if (zipFiles) {
                        if (isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "Mail.Log.FileSize", "" + FileSize));
                        }
                        if (isDebug()) {
                            logDebug(BaseMessages.getString(PKG, "Mail.Log.LimitSize", "" + data.zipFileLimit));
                        }

                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit) {

                            masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                                    + data.ZipFilename);

                            zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

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

                                file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]), getTransMeta());

                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                            }

                        }
                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit || data.zipFileLimit == 0) {
                            file = KettleVFS.getFileObject(masterZipfile.getAbsolutePath(), getTransMeta());
                            addAttachedFilePart(file);
                        }
                    }
                }
            } else {
                logError(BaseMessages.getString(PKG, "Mail.Error.SourceFileFolderNotExists",
                        realSourceFileFoldername));
            }
        }
    } catch (Exception e) {
        logError(e.getMessage());
    } finally {
        if (sourcefile != null) {
            try {
                sourcefile.close();
            } catch (Exception e) {
                // Ignore errors
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
                // Ignore errors
            }
        }

        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
                zipOutputStream.close();
            } catch (IOException e) {
                logError("Unable to close attachement zip file archive : " + e.toString());
            }
        }
    }

}

From source file:org.pentaho.di.trans.steps.orabulkloader.OraBulkLoader.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (OraBulkLoaderMeta) smi;//from  w  w  w .j a va 2 s  .  c o m
    data = (OraBulkLoaderData) sdi;

    super.dispose(smi, sdi);

    // close output stream (may terminate running sqlldr)
    if (output != null) {
        // Close the output
        try {
            output.close();
        } catch (IOException e) {
            logError("Error while closing output", e);
        }

        output = null;
    }
    // running sqlldr process must be terminated
    if (sqlldrProcess != null) {
        try {
            int exitVal = sqlldrProcess.waitFor();
            sqlldrProcess = null;
            logBasic(BaseMessages.getString(PKG, "OraBulkLoader.Log.ExitValueSqlldr", "" + exitVal));
        } catch (InterruptedException e) {
            /* process should be destroyed */
            e.printStackTrace();
            if (sqlldrProcess != null) {
                sqlldrProcess.destroy();
            }
        }
    }

    if (!preview && meta.isEraseFiles()) {
        // Erase the created cfg/dat files if requested. We don't erase
        // the rest of the files because it would be "stupid" to erase them
        // right after creation. If you don't want them, don't fill them in.
        FileObject fileObject = null;

        String method = meta.getLoadMethod();
        // OraBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(method) ||
        if (OraBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            if (meta.getControlFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage(), ex);
                }
            }
        }

        if (OraBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            // In concurrent mode the data is written to the control file.
            if (meta.getDataFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()),
                            getTransMeta());
                    fileObject.delete();
                    fileObject.close();
                } catch (Exception ex) {
                    logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage(), ex);
                }
            }
        }

        if (OraBulkLoaderMeta.METHOD_MANUAL.equals(method)) {
            logBasic("Deletion of files is not compatible with \'manual load method\'");
        }
    }
}

From source file:org.pentaho.di.trans.steps.processfiles.ProcessFiles.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (ProcessFilesMeta) smi;//from w  ww  .j av a2 s .  com
    data = (ProcessFilesData) sdi;

    Object[] r = getRow(); // Get row from input rowset & set row busy!
    if (r == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }
    if (first) {
        first = false;
        // Check is source filename field is provided
        if (Const.isEmpty(meta.getDynamicSourceFileNameField())) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFilenameFieldMissing"));
        }
        // Check is target filename field is provided
        if (meta.getOperationType() != ProcessFilesMeta.OPERATION_TYPE_DELETE
                && Const.isEmpty(meta.getDynamicTargetFileNameField())) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "ProcessFiles.Error.TargetFilenameFieldMissing"));
        }

        // cache the position of the source filename field
        if (data.indexOfSourceFilename < 0) {
            data.indexOfSourceFilename = getInputRowMeta().indexOfValue(meta.getDynamicSourceFileNameField());
            if (data.indexOfSourceFilename < 0) {
                // The field is unreachable !
                throw new KettleException(BaseMessages.getString(PKG,
                        "ProcessFiles.Exception.CouldnotFindField", meta.getDynamicSourceFileNameField()));
            }
        }
        // cache the position of the source filename field
        if (meta.getOperationType() != ProcessFilesMeta.OPERATION_TYPE_DELETE
                && data.indexOfTargetFilename < 0) {
            data.indexOfTargetFilename = getInputRowMeta().indexOfValue(meta.getDynamicTargetFileNameField());
            if (data.indexOfTargetFilename < 0) {
                // The field is unreachable !
                throw new KettleException(BaseMessages.getString(PKG,
                        "ProcessFiles.Exception.CouldnotFindField", meta.getDynamicTargetFileNameField()));
            }
        }

        if (meta.simulate) {
            if (log.isBasic()) {
                logBasic(BaseMessages.getString(PKG, "ProcessFiles.Log.SimulationModeON"));
            }
        }
    } // End If first
    try {
        // get source filename
        String sourceFilename = getInputRowMeta().getString(r, data.indexOfSourceFilename);

        if (Const.isEmpty(sourceFilename)) {
            logError(BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileEmpty"));
            throw new KettleException(BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileEmpty"));
        }
        data.sourceFile = KettleVFS.getFileObject(sourceFilename, getTransMeta());

        if (!data.sourceFile.exists()) {
            logError(BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileNotExist", sourceFilename));
            throw new KettleException(
                    BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileNotExist", sourceFilename));
        }
        if (data.sourceFile.getType() != FileType.FILE) {
            logError(BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileNotFile", sourceFilename));
            throw new KettleException(
                    BaseMessages.getString(PKG, "ProcessFiles.Error.SourceFileNotFile", sourceFilename));
        }
        String targetFilename = null;
        if (meta.getOperationType() != ProcessFilesMeta.OPERATION_TYPE_DELETE) {
            // get value for target filename
            targetFilename = getInputRowMeta().getString(r, data.indexOfTargetFilename);

            if (Const.isEmpty(targetFilename)) {
                logError(BaseMessages.getString(PKG, "ProcessFiles.Error.TargetFileEmpty"));
                throw new KettleException(BaseMessages.getString(PKG, "ProcessFiles.Error.TargetFileEmpty"));
            }
            data.targetFile = KettleVFS.getFileObject(targetFilename, getTransMeta());
            if (data.targetFile.exists()) {
                if (log.isDetailed()) {
                    logDetailed(
                            BaseMessages.getString(PKG, "ProcessFiles.Log.TargetFileExists", targetFilename));
                }
                // check if target is really a file otherwise it could overwrite a complete folder by copy or move operations
                if (data.targetFile.getType() != FileType.FILE) {
                    logError(BaseMessages.getString(PKG, "ProcessFiles.Error.TargetFileNotFile",
                            targetFilename));
                    throw new KettleException(BaseMessages.getString(PKG,
                            "ProcessFiles.Error.TargetFileNotFile", targetFilename));
                }

            } else {
                // let's check parent folder
                FileObject parentFolder = data.targetFile.getParent();
                if (!parentFolder.exists()) {
                    if (!meta.isCreateParentFolder()) {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "ProcessFiles.Error.TargetParentFolderNotExists", parentFolder.toString()));
                    } else {
                        parentFolder.createFolder();
                    }
                }
                if (parentFolder != null) {
                    parentFolder.close();
                }
            }
        }

        switch (meta.getOperationType()) {
        case ProcessFilesMeta.OPERATION_TYPE_COPY:
            if (((meta.isOverwriteTargetFile() && data.targetFile.exists()) || !data.targetFile.exists())
                    && !meta.simulate) {
                data.targetFile.copyFrom(data.sourceFile, new TextOneToOneFileSelector());
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.SourceFileCopied", sourceFilename,
                            targetFilename));
                }
            } else {
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.TargetNotOverwritten",
                            sourceFilename, targetFilename));
                }
            }
            break;
        case ProcessFilesMeta.OPERATION_TYPE_MOVE:
            if (((meta.isOverwriteTargetFile() && data.targetFile.exists()) || !data.targetFile.exists())
                    && !meta.simulate) {
                data.sourceFile.moveTo(KettleVFS.getFileObject(targetFilename, getTransMeta()));
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.SourceFileMoved", sourceFilename,
                            targetFilename));
                }
            } else {
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.TargetNotOverwritten",
                            sourceFilename, targetFilename));
                }
            }
            break;
        case ProcessFilesMeta.OPERATION_TYPE_DELETE:
            if (!meta.simulate) {
                if (!data.sourceFile.delete()) {
                    throw new KettleException(BaseMessages.getString(PKG, "ProcessFiles.Error.CanNotDeleteFile",
                            data.sourceFile.toString()));
                }
            }
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.SourceFileDeleted", sourceFilename));
            }
            break;
        default:

            break;
        }

        // add filename to result filenames?
        if (meta.isaddTargetFileNametoResult()
                && meta.getOperationType() != ProcessFilesMeta.OPERATION_TYPE_DELETE
                && data.sourceFile.getType() == FileType.FILE) {
            // Add this to the result file names...
            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, data.targetFile,
                    getTransMeta().getName(), getStepname());
            resultFile.setComment(BaseMessages.getString(PKG, "ProcessFiles.Log.FileAddedResult"));
            addResultFile(resultFile);

            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "ProcessFiles.Log.FilenameAddResult",
                        data.sourceFile.toString()));
            }
        }

        putRow(getInputRowMeta(), r); // copy row to possible alternate rowset(s).

        if (checkFeedback(getLinesRead())) {
            if (log.isBasic()) {
                logBasic(BaseMessages.getString(PKG, "ProcessFiles.LineNumber") + getLinesRead());
            }
        }
    } catch (Exception e) {
        boolean sendToErrorRow = false;
        String errorMessage = null;

        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        } else {
            logError(BaseMessages.getString(PKG, "ProcessFiles.ErrorInStepRunning") + e.getMessage());
            setErrors(1);
            stopAll();
            setOutputDone(); // signal end to receiver(s)
            return false;
        }
        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), r, 1, errorMessage, null, "ProcessFiles001");
        }
    }

    return true;
}

From source file:org.pentaho.di.trans.steps.propertyoutput.PropertyOutput.java

private void createParentFolder() throws KettleException {
    if (meta.isCreateParentFolder()) {
        FileObject parentfolder = null;
        try {/*from w  w w .  j  a  va2  s  .c om*/
            // Do we need to create parent folder ?

            // Check for parent folder
            // Get parent folder
            parentfolder = data.file.getParent();
            if (!parentfolder.exists()) {
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "PropertyOutput.Log.ParentFolderExists",
                            parentfolder.getName().toString()));
                }
                parentfolder.createFolder();
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "PropertyOutput.Log.CanNotCreateParentFolder",
                            parentfolder.getName().toString()));
                }
            }
        } catch (Exception e) {
            logError(BaseMessages.getString(PKG, "PropertyOutput.Log.CanNotCreateParentFolder",
                    parentfolder.getName().toString()));
            throw new KettleException(BaseMessages.getString(PKG, "PropertyOutput.Log.CanNotCreateParentFolder",
                    parentfolder.getName().toString()));

        } finally {
            if (parentfolder != null) {
                try {
                    parentfolder.close();
                } catch (Exception ex) { /* Ignore */
                }
            }
        }
    }
}

From source file:org.pentaho.di.trans.steps.rssoutput.RssOutput.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (RssOutputMeta) smi;/*from   w  w  w. j  a  v a 2 s .  com*/
    data = (RssOutputData) sdi;

    Object[] r = getRow(); // this also waits for a previous step to be finished.

    if (r == null) { // no more input to be expected...

        if (!first) {
            if (!meta.isCustomRss()) {
                // No more input..so write and close the file.
                WriteToFile(data.channeltitlevalue, data.channellinkvalue, data.channeldescriptionvalue,
                        data.channelpubdatevalue, data.channelcopyrightvalue, data.channelimagelinkvalue,
                        data.channelimagedescriptionvalue, data.channelimagelinkvalue,
                        data.channelimageurlvalue, data.channellanguagevalue, data.channelauthorvalue);
            } else {

                // Write to document
                OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
                // Set encoding ...
                if (Const.isEmpty(meta.getEncoding())) {
                    format.setEncoding("iso-8859-1");
                } else {
                    format.setEncoding(meta.getEncoding());
                }

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter(new File(data.filename)), format);
                    writer.write(data.document);
                    writer.close();
                } catch (Exception e) {
                    // Ignore errors
                } finally {
                    data.document = null;
                }

            }
        }
        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.inputRowMeta = getInputRowMeta();
        data.outputRowMeta = data.inputRowMeta.clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);
        // Let's check for filename...

        if (meta.isFilenameInField()) {
            if (Const.isEmpty(meta.getFileNameField())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameFieldMissing"));
                setErrors(1);
                stopAll();
                return false;
            }

            // get filename field index
            data.indexOfFieldfilename = data.inputRowMeta.indexOfValue(meta.getFileNameField());
            if (data.indexOfFieldfilename < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getFileNameField()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getFileNameField()));
            }

        } else {
            data.filename = buildFilename();
        }

        // Check if filename is empty..
        if (Const.isEmpty(data.filename)) {
            logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty"));
            throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty"));
        }

        // Do we need to create parent folder ?
        if (meta.isCreateParentFolder()) {
            // Check for parent folder
            FileObject parentfolder = null;
            try {
                // Get parent folder
                parentfolder = KettleVFS.getFileObject(data.filename, getTransMeta()).getParent();
                if (!parentfolder.exists()) {
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.ParentFolderExists",
                                parentfolder.getName().toString()));
                    }
                    parentfolder.createFolder();
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                                parentfolder.getName().toString()));
                    }
                }
            } catch (Exception e) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                        parentfolder.getName().toString()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                        parentfolder.getName().toString()));

            } finally {
                if (parentfolder != null) {
                    try {
                        parentfolder.close();
                    } catch (Exception ex) { /* Ignore */
                    }
                }
            }
        }

        if (!meta.isCustomRss()) {
            // Let's check for mandatory fields ...
            if (Const.isEmpty(meta.getChannelTitle())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelTitleMissing"));
                setErrors(1);
                stopAll();
                return false;
            }
            if (Const.isEmpty(meta.getChannelDescription())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelDescription"));
                setErrors(1);
                stopAll();
                return false;
            }
            if (Const.isEmpty(meta.getChannelLink())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelLink"));
                setErrors(1);
                stopAll();
                return false;
            }

            // Let's take the index of channel title field ...
            data.indexOfFieldchanneltitle = data.inputRowMeta.indexOfValue(meta.getChannelTitle());
            if (data.indexOfFieldchanneltitle < 0) {
                // The field is unreachable !
                logError(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle()));
                throw new KettleException(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle()));
            }
            data.channeltitlevalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneltitle);

            // Let's take the index of channel description field ...
            data.indexOfFieldchanneldescription = data.inputRowMeta.indexOfValue(meta.getChannelDescription());
            if (data.indexOfFieldchanneldescription < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getChannelDescription()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getChannelDescription()));
            }

            data.channeldescriptionvalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneldescription);

            // Let's take the index of channel link field ...
            data.indexOfFieldchannellink = data.inputRowMeta.indexOfValue(meta.getChannelLink());
            if (data.indexOfFieldchannellink < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink()));
                throw new KettleException(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink()));
            }

            data.channellinkvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellink);

            if (!Const.isEmpty(meta.getItemTitle())) {
                // Let's take the index of item title field ...
                data.indexOfFielditemtitle = data.inputRowMeta.indexOfValue(meta.getItemTitle());
                if (data.indexOfFielditemtitle < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemTitle()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemTitle()));
                }
            }

            if (!Const.isEmpty(meta.getItemDescription())) {
                // Let's take the index of item description field ...
                data.indexOfFielditemdescription = data.inputRowMeta.indexOfValue(meta.getItemDescription());
                if (data.indexOfFielditemdescription < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemDescription()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemDescription()));
                }
            }
            if (meta.AddGeoRSS()) {
                if (Const.isEmpty(meta.getGeoPointLong())) {
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLatEmpty"));
                }
                if (Const.isEmpty(meta.getGeoPointLong())) {
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLongEmpty"));
                }

                // Let's take the index of item geopointX field ...
                data.indexOfFielditempointx = data.inputRowMeta.indexOfValue(meta.getGeoPointLat());
                if (data.indexOfFielditempointx < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLat()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLat()));
                }
                // Let's take the index of item geopointY field ...
                data.indexOfFielditempointy = data.inputRowMeta.indexOfValue(meta.getGeoPointLong());
                if (data.indexOfFielditempointy < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLong()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLong()));
                }
            }

            // It's time to check non empty fields !
            // Channel PubDate field ...
            if (!Const.isEmpty(meta.getChannelPubDate())) {
                data.indexOfFieldchannelpubdate = data.inputRowMeta.indexOfValue(meta.getChannelPubDate());
                if (data.indexOfFieldchannelpubdate < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelPubDate()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelPubDate()));
                }

                data.channelpubdatevalue = data.inputRowMeta.getDate(r, data.indexOfFieldchannelpubdate);
            }
            // Channel Language field ...
            if (!Const.isEmpty(meta.getChannelLanguage())) {
                data.indexOfFieldchannellanguage = data.inputRowMeta.indexOfValue(meta.getChannelLanguage());
                if (data.indexOfFieldchannellanguage < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelLanguage()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelLanguage()));
                }

                data.channellanguagevalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellanguage);
            }

            // Channel Copyright field ...
            if (!Const.isEmpty(meta.getChannelCopyright())) {
                data.indexOfFieldchannelcopyright = data.inputRowMeta.indexOfValue(meta.getChannelCopyright());
                if (data.indexOfFieldchannelcopyright < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelCopyright()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelCopyright()));
                }

                data.channelcopyrightvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelcopyright);
            }

            // Channel Author field ...
            if (!Const.isEmpty(meta.getChannelAuthor())) {
                data.indexOfFieldchannelauthor = data.inputRowMeta.indexOfValue(meta.getChannelAuthor());
                if (data.indexOfFieldchannelauthor < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelAuthor()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelAuthor()));
                }

                data.channelauthorvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelauthor);
            }

            // Channel Image field ...
            if (meta.AddImage()) {
                // Channel image title
                if (!Const.isEmpty(meta.getChannelImageTitle())) {
                    data.indexOfFieldchannelimagetitle = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageTitle());
                    if (data.indexOfFieldchannelimagetitle < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageTitle()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageTitle()));
                    }

                    data.channelimagetitlevalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagetitle);
                }

                // Channel link title
                if (!Const.isEmpty(meta.getChannelImageLink())) {
                    data.indexOfFieldchannelimagelink = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageLink());
                    if (data.indexOfFieldchannelimagelink < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageLink()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageLink()));
                    }

                    data.channelimagelinkvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagelink);
                }

                // Channel url title
                if (!Const.isEmpty(meta.getChannelImageUrl())) {
                    data.indexOfFieldchannelimageurl = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageUrl());
                    if (data.indexOfFieldchannelimageurl < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageUrl()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageUrl()));
                    }

                    data.channelimageurlvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimageurl);
                }

                // Channel description title
                if (!Const.isEmpty(meta.getChannelImageDescription())) {
                    data.indexOfFieldchannelimagedescription = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageDescription());
                    if (data.indexOfFieldchannelimagedescription < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageDescription()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageDescription()));
                    }

                    data.channelimagedescriptionvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagedescription);
                }

            }

            // Item link field ...
            if (!Const.isEmpty(meta.getItemLink())) {
                data.indexOfFielditemlink = data.inputRowMeta.indexOfValue(meta.getItemLink());
                if (data.indexOfFielditemlink < 0) {
                    // The field is unreachable !
                    logError(
                            BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink()));
                    throw new KettleException(
                            BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink()));
                }

            }

            // Item pubdate field ...
            if (!Const.isEmpty(meta.getItemPubDate())) {
                data.indexOfFielditempubdate = data.inputRowMeta.indexOfValue(meta.getItemPubDate());
                if (data.indexOfFielditempubdate < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemPubDate()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemPubDate()));
                }
            }

            // Item author field ...
            if (!Const.isEmpty(meta.getItemAuthor())) {
                data.indexOfFielditemauthor = data.inputRowMeta.indexOfValue(meta.getItemAuthor());
                if (data.indexOfFielditemauthor < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemAuthor()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemAuthor()));
                }
            }
        } else {
            // Custom RSS
            // Check Custom channel fields
            data.customchannels = new int[meta.getChannelCustomFields().length];
            for (int i = 0; i < meta.getChannelCustomFields().length; i++) {
                data.customchannels[i] = data.inputRowMeta.indexOfValue(meta.getChannelCustomFields()[i]);
                if (data.customchannels[i] < 0) { // couldn't find field!

                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "RssOutput.Exception.FieldRequired", meta.getChannelCustomFields()[i]));
                }
            }
            // Check Custom channel fields
            data.customitems = new int[meta.getItemCustomFields().length];
            for (int i = 0; i < meta.getItemCustomFields().length; i++) {
                data.customitems[i] = data.inputRowMeta.indexOfValue(meta.getItemCustomFields()[i]);
                if (data.customitems[i] < 0) { // couldn't find field!

                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "RssOutput.Exception.FieldRequired", meta.getItemCustomFields()[i]));
                }
            }
            // Prepare Output RSS Custom document
            data.document = DocumentHelper.createDocument();
            data.rssElement = data.document.addElement("rss");
            data.rssElement.addAttribute("version", "2.0");
            // add namespaces here ...
            for (int i = 0; i < meta.getNameSpaces().length; i++) {
                data.rssElement.addNamespace(environmentSubstitute(meta.getNameSpacesTitle()[i]),
                        environmentSubstitute(meta.getNameSpaces()[i]));
            }

            // Add channel
            data.channel = data.rssElement.addElement("channel");

            // Set channel Only the first time ...
            for (int i = 0; i < data.customchannels.length; i++) {
                String channelname = environmentSubstitute(meta.getChannelCustomTags()[i]);
                String channelvalue = data.inputRowMeta.getString(r, data.customchannels[i]);

                if (log.isDetailed()) {
                    logDetailed("outputting channel value <" + channelname + ">" + channelvalue + "<"
                            + channelname + "/>");
                }

                // add Channel
                Element channeltag = data.channel.addElement(channelname);
                channeltag.setText(channelvalue);

            }
        }
    } // end test first time

    // Let's get value for each item...
    if (!meta.isCustomRss()) {
        String itemtitlevalue = null;
        String itemauthorvalue = null;
        String itemlinkvalue = null;
        Date itemdatevalue = null;
        String itemdescvalue = null;
        String itemgeopointx = null;
        String itemgeopointy = null;

        if (data.indexOfFielditemtitle > -1) {
            itemtitlevalue = data.inputRowMeta.getString(r, data.indexOfFielditemtitle);
        }
        if (data.indexOfFielditemauthor > -1) {
            itemauthorvalue = data.inputRowMeta.getString(r, data.indexOfFielditemauthor);
        }
        if (data.indexOfFielditemlink > -1) {
            itemlinkvalue = data.inputRowMeta.getString(r, data.indexOfFielditemlink);
        }
        if (data.indexOfFielditempubdate > -1) {
            itemdatevalue = data.inputRowMeta.getDate(r, data.indexOfFielditempubdate);
        }
        if (data.indexOfFielditemdescription > -1) {
            itemdescvalue = data.inputRowMeta.getString(r, data.indexOfFielditemdescription);
        }
        if (data.indexOfFielditempointx > -1) {
            itemgeopointx = data.inputRowMeta.getString(r, data.indexOfFielditempointx);
        }
        if (data.indexOfFielditempointy > -1) {
            itemgeopointy = data.inputRowMeta.getString(r, data.indexOfFielditempointy);
        }

        // Now add entry ..
        if (!createEntry(itemauthorvalue, itemtitlevalue, itemlinkvalue, itemdatevalue, itemdescvalue,
                itemgeopointx, itemgeopointy)) {
            throw new KettleException("Error adding item to feed");
        }
    } else {

        // Set item tag at each row received
        if (meta.isDisplayItem()) {
            data.itemtag = data.channel.addElement("item");
        }
        for (int i = 0; i < data.customitems.length; i++) {
            // get item value and name
            String itemname = environmentSubstitute(meta.getItemCustomTags()[i]);
            String itemvalue = data.inputRowMeta.getString(r, data.customitems[i]);

            if (log.isDetailed()) {
                logDetailed("outputting item value <" + itemname + ">" + itemvalue + "<" + itemname + "/>");
            }

            // add Item
            if (meta.isDisplayItem()) {
                Element itemtagsub = data.itemtag.addElement(itemname);
                itemtagsub.setText(itemvalue);
            } else {
                // display item at channel level
                Element temp = data.channel.addElement(itemname);
                temp.setText(itemvalue);
            }
        }
    }

    try {
        putRow(data.outputRowMeta, r); // in case we want it to go further...
        incrementLinesOutput();

        if (checkFeedback(getLinesOutput())) {
            if (log.isDebug()) {
                logDebug(BaseMessages.getString(PKG, "RssOutput.Log.Linenr", "" + getLinesOutput()));
            }
        }

    } catch (KettleStepException e) {
        logError(BaseMessages.getString(PKG, "RssOutputMeta.Log.ErrorInStep") + e.getMessage());
        setErrors(1);
        stopAll();
        setOutputDone(); // signal end to receiver(s)
        return false;
    }

    return true;
}

From source file:org.pentaho.di.trans.steps.rssoutput.RssOutputMeta.java

private String getFilename(VariableSpace space) throws KettleStepException {
    FileObject file = null;
    try {//from   ww  w . j  a  v a2 s.  c  o m
        file = KettleVFS.getFileObject(space.environmentSubstitute(getFileName()));
        return KettleVFS.getFilename(file);
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "RssOutput.Meta.ErrorGettingFile", getFileName()), e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) { /* Ignore */
            }
        }
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void deleteFile(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    try {/* w  w  w.  j  a v a 2 s . c o  m*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            // Object act = actualObject.get("_step_", actualObject);
            // ScriptValuesMod act = (ScriptValuesMod)Context.toType(scm_delete, ScriptValuesMod.class);

            FileObject fileObject = null;

            try {
                fileObject = KettleVFS.getFileObject((String) ArgList[0]);
                if (fileObject.exists()) {
                    if (fileObject.getType() == FileType.FILE) {
                        if (!fileObject.delete()) {
                            new RuntimeException("We can not delete file [" + (String) ArgList[0] + "]!");
                        }
                    }

                } else {
                    new RuntimeException("file [" + (String) ArgList[0] + "] can not be found!");
                }
            } catch (IOException e) {
                throw new RuntimeException("The function call deleteFile is not valid.");
            } finally {
                if (fileObject != null) {
                    try {
                        fileObject.close();
                    } catch (Exception e) {
                        // Ignore errors
                    }
                }
            }

        } else {
            throw new RuntimeException("The function call deleteFile is not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void createFolder(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    try {/*from w  ww .  j  a v a2 s  .  com*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            FileObject fileObject = null;

            try {
                fileObject = KettleVFS.getFileObject((String) ArgList[0]);
                if (!fileObject.exists()) {
                    fileObject.createFolder();
                } else {
                    new RuntimeException("folder [" + (String) ArgList[0] + "] already exist!");
                }
            } catch (IOException e) {
                throw new RuntimeException("The function call createFolder is not valid.");
            } finally {
                if (fileObject != null) {
                    try {
                        fileObject.close();
                    } catch (Exception e) {
                        // Ignore errors
                    }
                }
            }

        } else {
            throw new RuntimeException("The function call createFolder is not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static void copyFile(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    try {//from www  .  j a  va 2  s  .  com
        if (ArgList.length == 3 && !isNull(ArgList[0]) && !isNull(ArgList[1]) && !isUndefined(ArgList[0])
                && !isUndefined(ArgList[1])) {
            FileObject fileSource = null, fileDestination = null;

            try {
                // Source file to copy
                fileSource = KettleVFS.getFileObject((String) ArgList[0]);
                // Destination filename
                fileDestination = KettleVFS.getFileObject((String) ArgList[1]);
                if (fileSource.exists()) {
                    // Source file exists...
                    if (fileSource.getType() == FileType.FILE) {
                        // Great..source is a file ...
                        boolean overwrite = false;
                        if (!ArgList[1].equals(null)) {
                            overwrite = (Boolean) ArgList[2];
                        }
                        boolean destinationExists = fileDestination.exists();
                        // Let's copy the file...
                        if ((destinationExists && overwrite) || !destinationExists) {
                            FileUtil.copyContent(fileSource, fileDestination);
                        }

                    }
                } else {
                    new RuntimeException("file to copy [" + (String) ArgList[0] + "] can not be found!");
                }
            } catch (IOException e) {
                throw new RuntimeException("The function call copyFile throw an error : " + e.toString());
            } finally {
                if (fileSource != null) {
                    try {
                        fileSource.close();
                    } catch (Exception e) {
                        // Ignore errors
                    }
                }
                if (fileDestination != null) {
                    try {
                        fileDestination.close();
                    } catch (Exception e) {
                        // Ignore errors
                    }
                }
            }

        } else {
            throw new RuntimeException("The function call copyFileis not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static double getFileSize(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    try {/*from  w ww. j  ava  2s .  c o m*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            if (ArgList[0].equals(null)) {
                return 0;
            }
            FileObject file = null;

            try {
                // Source file
                file = KettleVFS.getFileObject((String) ArgList[0]);
                long filesize = 0;
                if (file.exists()) {
                    if (file.getType().equals(FileType.FILE)) {
                        filesize = file.getContent().getSize();
                    } else {
                        new RuntimeException("[" + (String) ArgList[0] + "] is not a file!");
                    }
                } else {
                    new RuntimeException("file [" + (String) ArgList[0] + "] can not be found!");
                }
                return filesize;
            } catch (IOException e) {
                throw new RuntimeException("The function call getFileSize throw an error : " + e.toString());
            } finally {
                if (file != null) {
                    try {
                        file.close();
                    } catch (Exception e) {
                        // Ignore errors
                    }
                }
            }

        } else {
            throw new RuntimeException("The function call getFileSize is not valid.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}