Java Code Examples for org.apache.commons.vfs2.FileObject#close()

The following examples show how to use org.apache.commons.vfs2.FileObject#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZipFileObjectTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
 * process the initial input stream. If our internal reference counting is correct, the test passes.
 *
 * @throws IOException
 */
@Test
public void testReadingOneAfterClosingAnotherStream() throws IOException {
    final File newZipFile = createTempFile();
    final FileSystemManager manager = VFS.getManager();
    final FileObject zipFileObject1;
    final InputStream inputStream1;
    try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
        // leave resources open (note that internal counters are updated)
        zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
        inputStream1 = zipFileObject1.getContent().getInputStream();
        resolveReadAssert(zipFileObject, NESTED_FILE_2);
    }
    // The Zip file is "closed", but we read from the stream now, which currently fails.
    // Why aren't internal counters preventing the stream from closing?
    readAndAssert(zipFileObject1, inputStream1, "1");
    // clean up
    zipFileObject1.close();
    assertDelete(newZipFile);
}
 
Example 2
Source File: FileLockTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadClosedFileObject() throws Exception {
    final FileObject zipFileObjectRef;
    try (final FileObject zipFileObject = manager.resolveFile(zipFileUri)) {
        zipFileObjectRef = zipFileObject;
        try (final InputStream inputStream = zipFileObject.getContent().getInputStream()) {
            readAndAssert(inputStream);
        }
    }
    try (final InputStream inputStream = zipFileObjectRef.getContent().getInputStream()) {
        readAndAssert(inputStream);
    } finally {
        zipFileObjectRef.close();
    }
    assertDelete();
}
 
Example 3
Source File: ZipFileObjectTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
 * process the initial input stream.
 *
 * @throws IOException
 */
@Test
public void testReadingOneAfterClosingAnotherFile() throws IOException {
    final File newZipFile = createTempFile();
    final FileSystemManager manager = VFS.getManager();
    final FileObject zipFileObject1;
    final InputStream inputStream1;
    try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
        // leave resources open
        zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
        inputStream1 = zipFileObject1.getContent().getInputStream();
    }
    // The zip file is "closed", but we read from the stream now.
    readAndAssert(zipFileObject1, inputStream1, "1");
    // clean up
    zipFileObject1.close();
    assertDelete(newZipFile);
}
 
Example 4
Source File: FileExistsValidator.java    From hop with Apache License 2.0 5 votes vote down vote up
public boolean validate( ICheckResultSource source, String propertyName,
                         List<ICheckResult> remarks, ValidatorContext context ) {

  String filename = ValidatorUtils.getValueAsString( source, propertyName );
  IVariables variables = getVariableSpace( source, propertyName, remarks, context );
  boolean failIfDoesNotExist = getFailIfDoesNotExist( source, propertyName, remarks, context );

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

  String realFileName = variables.environmentSubstitute( filename );
  FileObject fileObject = null;
  try {
    fileObject = HopVfs.getFileObject( realFileName );
    if ( fileObject == null || ( fileObject != null && !fileObject.exists() && failIfDoesNotExist ) ) {
      ActionValidatorUtils.addFailureRemark(
        source, propertyName, VALIDATOR_NAME, remarks, ActionValidatorUtils.getLevelOnFail(
          context, VALIDATOR_NAME ) );
      return false;
    }
    try {
      fileObject.close(); // Just being paranoid
    } catch ( IOException ignored ) {
      // Ignore close errors
    }
  } catch ( Exception e ) {
    ActionValidatorUtils.addExceptionRemark( source, propertyName, VALIDATOR_NAME, remarks, e );
    return false;
  }
  return true;
}
 
Example 5
Source File: JobEntryCopyMoveResultFilenames.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private boolean CreateDestinationFolder( String foldername ) {
  FileObject folder = null;
  try {
    folder = KettleVFS.getFileObject( foldername, this );

    if ( !folder.exists() ) {
      logError( BaseMessages.getString( PKG, "JobEntryCopyMoveResultFilenames.Log.FolderNotExists", foldername ) );
      if ( isCreateDestinationFolder() ) {
        folder.createFolder();
      } else {
        return false;
      }
      if ( log.isBasic() ) {
        logBasic( BaseMessages.getString( PKG, "JobEntryCopyMoveResultFilenames.Log.FolderCreated", foldername ) );
      }
    } else {
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages
          .getString( PKG, "JobEntryCopyMoveResultFilenames.Log.FolderExists", foldername ) );
      }
    }
    return true;
  } catch ( Exception e ) {
    logError( BaseMessages.getString(
      PKG, "JobEntryCopyMoveResultFilenames.Log.CanNotCreatedFolder", foldername, e.toString() ) );

  } finally {
    if ( folder != null ) {
      try {
        folder.close();
        folder = null;
      } catch ( Exception ex ) { /* Ignore */
      }
    }
  }
  return false;
}
 
Example 6
Source File: ProviderRandomSetLengthTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a file
 */
public void testRandomSetLength() throws Exception {
    FileObject file = null;
    try {
        file = this.createScratchFolder().resolveFile("random_write.txt");
        file.createFile();
        final String fileString = file.toString();
        final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE);

        // Write long string
        ra.writeBytes(TEST_DATA);
        Assert.assertEquals(fileString, TEST_DATA.length(), ra.length());

        // Shrink to length 1
        ra.setLength(1);
        Assert.assertEquals(fileString, 1, ra.length());
        // now read 1
        ra.seek(0);
        Assert.assertEquals(fileString, TEST_DATA.charAt(0), ra.readByte());

        try {
            ra.readByte();
            Assert.fail("Expected " + Exception.class.getName());
        } catch (final IOException e) {
            // Expected
        }

        // Grow to length 2
        ra.setLength(2);
        Assert.assertEquals(fileString, 2, ra.length());
        // We have an undefined extra byte
        ra.seek(1);
        ra.readByte();

    } finally {
        if (file != null) {
            file.close();
        }
    }
}
 
Example 7
Source File: ActionCopyFiles.java    From hop with Apache License 2.0 5 votes vote down vote up
private boolean CreateDestinationFolder( FileObject filefolder ) {
  FileObject folder = null;
  try {
    if ( destination_is_a_file ) {
      folder = filefolder.getParent();
    } else {
      folder = filefolder;
    }

    if ( !folder.exists() ) {
      if ( create_destination_folder ) {
        if ( isDetailed() ) {
          logDetailed( "Folder  " + HopVfs.getFriendlyURI( folder ) + " does not exist !" );
        }
        folder.createFolder();
        if ( isDetailed() ) {
          logDetailed( "Folder parent was created." );
        }
      } else {
        logError( "Folder  " + HopVfs.getFriendlyURI( folder ) + " does not exist !" );
        return false;
      }
    }
    return true;
  } catch ( Exception e ) {
    logError( "Couldn't created parent folder " + HopVfs.getFriendlyURI( folder ), e );
  } finally {
    if ( folder != null ) {
      try {
        folder.close();
        folder = null;
      } catch ( Exception ex ) { /* Ignore */
      }
    }
  }
  return false;
}
 
Example 8
Source File: ActionZipFile.java    From hop with Apache License 2.0 5 votes vote down vote up
private boolean createParentFolder( String filename ) {
  // Check for parent folder
  FileObject parentfolder = null;

  boolean result = false;
  try {
    // Get parent folder
    parentfolder = HopVfs.getFileObject( filename ).getParent();

    if ( !parentfolder.exists() ) {
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString( PKG, "ActionZipFile.CanNotFindFolder", ""
          + parentfolder.getName() ) );
      }
      parentfolder.createFolder();
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString( PKG, "ActionZipFile.FolderCreated", "" + parentfolder.getName() ) );
      }
    } else {
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString( PKG, "ActionZipFile.FolderExists", "" + parentfolder.getName() ) );
      }
    }
    result = true;
  } catch ( Exception e ) {
    logError(
      BaseMessages.getString( PKG, "ActionZipFile.CanNotCreateFolder", "" + parentfolder.getName() ), e );
  } finally {
    if ( parentfolder != null ) {
      try {
        parentfolder.close();
      } catch ( Exception ex ) {
        // Ignore
      }
    }
  }
  return result;
}
 
Example 9
Source File: JsonOutput.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void createParentFolder( String filename ) throws KettleStepException {
  if ( !meta.isCreateParentFolder() ) {
    return;
  }
  // Check for parent folder
  FileObject parentfolder = null;
  try {
    // Get parent folder
    parentfolder = KettleVFS.getFileObject( filename, getTransMeta() ).getParent();
    if ( !parentfolder.exists() ) {
      if ( log.isDebug() ) {
        logDebug( BaseMessages.getString( PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName() ) );
      }
      parentfolder.createFolder();
      if ( log.isDebug() ) {
        logDebug( BaseMessages.getString( PKG, "JsonOutput.Log.ParentFolderCreated" ) );
      }
    }
  } catch ( Exception e ) {
    throw new KettleStepException( BaseMessages.getString(
      PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName() ) );
  } finally {
    if ( parentfolder != null ) {
      try {
        parentfolder.close();
      } catch ( Exception ex ) { /* Ignore */
      }
    }
  }
}
 
Example 10
Source File: PropertyOutput.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void createParentFolder() throws KettleException {
  if ( meta.isCreateParentFolder() ) {
    FileObject parentfolder = null;
    try {
      // 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 */
        }
      }
    }
  }
}
 
Example 11
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
    FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
    FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
    remote.copyFrom(local, Selectors.SELECT_SELF);
    local.close();
    remote.close();
}
 
Example 12
Source File: JobEntryCopyFiles.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private boolean CreateDestinationFolder( FileObject filefolder ) {
  FileObject folder = null;
  try {
    if ( destination_is_a_file ) {
      folder = filefolder.getParent();
    } else {
      folder = filefolder;
    }

    if ( !folder.exists() ) {
      if ( create_destination_folder ) {
        if ( isDetailed() ) {
          logDetailed( "Folder  " + KettleVFS.getFriendlyURI( folder ) + " does not exist !" );
        }
        folder.createFolder();
        if ( isDetailed() ) {
          logDetailed( "Folder parent was created." );
        }
      } else {
        logError( "Folder  " + KettleVFS.getFriendlyURI( folder ) + " does not exist !" );
        return false;
      }
    }
    return true;
  } catch ( Exception e ) {
    logError( "Couldn't created parent folder " + KettleVFS.getFriendlyURI( folder ), e );
  } finally {
    if ( folder != null ) {
      try {
        folder.close();
        folder = null;
      } catch ( Exception ex ) { /* Ignore */
      }
    }
  }
  return false;
}
 
Example 13
Source File: ActionUnZip.java    From hop with Apache License 2.0 4 votes vote down vote up
/**
 * Moving or deleting source file.
 */
private void doUnzipPostProcessing( FileObject sourceFileObject, FileObject movetodir, String realMovetodirectory ) throws FileSystemException {
  if ( afterunzip == 1 ) {
    // delete zip file
    boolean deleted = sourceFileObject.delete();
    if ( !deleted ) {
      updateErrors();
      logError( BaseMessages.getString( PKG, "JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString() ) );
    }
    // File deleted
    if ( log.isDebug() ) {
      logDebug( BaseMessages.getString( PKG, "JobUnZip.File_Deleted.Label", sourceFileObject.toString() ) );
    }
  } else if ( afterunzip == 2 ) {
    FileObject destFile = null;
    // Move File
    try {
      String destinationFilename = movetodir + Const.FILE_SEPARATOR + sourceFileObject.getName().getBaseName();
      destFile = HopVfs.getFileObject( destinationFilename );

      sourceFileObject.moveTo( destFile );

      // File moved
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString(
          PKG, "JobUnZip.Log.FileMovedTo", sourceFileObject.toString(), realMovetodirectory ) );
      }
    } catch ( Exception e ) {
      updateErrors();
      logError( BaseMessages.getString(
        PKG, "JobUnZip.Cant_Move_File.Label", sourceFileObject.toString(), realMovetodirectory, e
          .getMessage() ) );
    } finally {
      if ( destFile != null ) {
        try {
          destFile.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  }
}
 
Example 14
Source File: ActionFolderIsEmpty.java    From hop with Apache License 2.0 4 votes vote down vote up
public boolean includeFile( FileSelectInfo info ) throws ExpectedException {
  boolean returncode = false;
  FileObject file_name = null;
  boolean rethrow = false;
  try {
    if ( !info.getFile().toString().equals( root_folder ) ) {
      // Pass over the Base folder itself
      if ( ( info.getFile().getType() == FileType.FILE ) ) {
        if ( info.getFile().getParent().equals( info.getBaseFolder() ) ) {
          // We are in the Base folder
          if ( ( isSpecifyWildcard() && GetFileWildcard( info.getFile().getName().getBaseName() ) )
            || !isSpecifyWildcard() ) {
            if ( log.isDetailed() ) {
              log.logDetailed( "We found file : " + info.getFile().toString() );
            }
            filescount++;
          }
        } else {
          // We are not in the base Folder...ONLY if Use sub folders
          // We are in the Base folder
          if ( isIncludeSubFolders() ) {
            if ( ( isSpecifyWildcard() && GetFileWildcard( info.getFile().getName().getBaseName() ) )
              || !isSpecifyWildcard() ) {
              if ( log.isDetailed() ) {
                log.logDetailed( "We found file : " + info.getFile().toString() );
              }
              filescount++;
            }
          }
        }
      } else {
        folderscount++;
      }
    }
    if ( filescount > 0 ) {
      rethrow = true;
      throw new ExpectedException();
    }
    return true;

  } catch ( Exception e ) {
    if ( !rethrow ) {
      log.logError( BaseMessages.getString( PKG, "JobFolderIsEmpty.Error" ), BaseMessages.getString(
        PKG, "JobFolderIsEmpty.Error.Exception", info.getFile().toString(), e.getMessage() ) );
      returncode = false;
    } else {
      throw (ExpectedException) e;
    }
  } finally {
    if ( file_name != null ) {
      try {
        file_name.close();
        file_name = null;
      } catch ( IOException ex ) { /* Ignore */
      }
    }
  }
  return returncode;
}
 
Example 15
Source File: ActionGetPOP.java    From hop with Apache License 2.0 4 votes vote down vote up
String createOutputDirectory( int folderType ) throws HopException, FileSystemException, IllegalArgumentException {
  if ( ( folderType != ActionGetPOP.FOLDER_OUTPUT ) && ( folderType != ActionGetPOP.FOLDER_ATTACHMENTS ) ) {
    throw new IllegalArgumentException( "Invalid folderType argument" );
  }
  String folderName = "";
  switch ( folderType ) {
    case ActionGetPOP.FOLDER_OUTPUT:
      folderName = getRealOutputDirectory();
      break;
    case ActionGetPOP.FOLDER_ATTACHMENTS:
      if ( isSaveAttachment() && isDifferentFolderForAttachment() ) {
        folderName = getRealAttachmentFolder();
      } else {
        folderName = getRealOutputDirectory();
      }
      break;
  }
  if ( Utils.isEmpty( folderName ) ) {
    switch ( folderType ) {
      case ActionGetPOP.FOLDER_OUTPUT:
        throw new HopException( BaseMessages
          .getString( PKG, "JobGetMailsFromPOP.Error.OutputFolderEmpty" ) );
      case ActionGetPOP.FOLDER_ATTACHMENTS:
        throw new HopException( BaseMessages
          .getString( PKG, "JobGetMailsFromPOP.Error.AttachmentFolderEmpty" ) );
    }
  }
  FileObject folder = HopVfs.getFileObject( folderName );
  if ( folder.exists() ) {
    if ( folder.getType() != FileType.FOLDER ) {
      switch ( folderType ) {
        case ActionGetPOP.FOLDER_OUTPUT:
          throw new HopException( BaseMessages.getString(
            PKG, "JobGetMailsFromPOP.Error.NotAFolderNot", folderName ) );
        case ActionGetPOP.FOLDER_ATTACHMENTS:
          throw new HopException( BaseMessages.getString(
            PKG, "JobGetMailsFromPOP.Error.AttachmentFolderNotAFolder", folderName ) );
      }
    }
    if ( isDebug() ) {
      switch ( folderType ) {
        case ActionGetPOP.FOLDER_OUTPUT:
          logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.Log.OutputFolderExists", folderName ) );
          break;
        case ActionGetPOP.FOLDER_ATTACHMENTS:
          logDebug( BaseMessages.getString( PKG, "JobGetMailsFromPOP.Log.AttachmentFolderExists", folderName ) );
          break;
      }
    }
  } else {
    if ( isCreateLocalFolder() ) {
      folder.createFolder();
    } else {
      switch ( folderType ) {
        case ActionGetPOP.FOLDER_OUTPUT:
          throw new HopException( BaseMessages.getString(
            PKG, "JobGetMailsFromPOP.Error.OutputFolderNotExist", folderName ) );
        case ActionGetPOP.FOLDER_ATTACHMENTS:
          throw new HopException( BaseMessages.getString(
            PKG, "JobGetMailsFromPOP.Error.AttachmentFolderNotExist", folderName ) );
      }
    }
  }

  String returnValue = HopVfs.getFilename( folder );
  try {
    folder.close();
  } catch ( IOException ignore ) {
    //Ignore error, as the folder was created successfully
  }
  return returnValue;
}
 
Example 16
Source File: JobEntryCreateFolder.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );

  if ( foldername != null ) {
    //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
    if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
      parentJobMeta.getNamedClusterEmbedManager()
        .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
    }

    String realFoldername = getRealFoldername();
    FileObject folderObject = null;
    try {
      folderObject = KettleVFS.getFileObject( realFoldername, this );

      if ( folderObject.exists() ) {
        boolean isFolder = false;

        // Check if it's a folder
        if ( folderObject.getType() == FileType.FOLDER ) {
          isFolder = true;
        }

        if ( isFailOfFolderExists() ) {
          // Folder exists and fail flag is on.
          result.setResult( false );
          if ( isFolder ) {
            logError( "Folder [" + realFoldername + "] exists, failing." );
          } else {
            logError( "File [" + realFoldername + "] exists, failing." );
          }
        } else {
          // Folder already exists, no reason to try to create it
          result.setResult( true );
          if ( log.isDetailed() ) {
            logDetailed( "Folder [" + realFoldername + "] already exists, not recreating." );
          }
        }

      } else {
        // No Folder yet, create an empty Folder.
        folderObject.createFolder();
        if ( log.isDetailed() ) {
          logDetailed( "Folder [" + realFoldername + "] created!" );
        }
        result.setResult( true );
      }
    } catch ( Exception e ) {
      logError( "Could not create Folder [" + realFoldername + "]", e );
      result.setResult( false );
      result.setNrErrors( 1 );
    } finally {
      if ( folderObject != null ) {
        try {
          folderObject.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  } else {
    logError( "No Foldername is defined." );
  }

  return result;
}
 
Example 17
Source File: JobEntryCreateFile.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) throws KettleException {
  Result result = previousResult;
  result.setResult( false );

  if ( filename != null ) {
    //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
    if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
      parentJobMeta.getNamedClusterEmbedManager()
        .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
    }

    String realFilename = getRealFilename();
    FileObject fileObject = null;
    try {
      fileObject = KettleVFS.getFileObject( realFilename, this );

      if ( fileObject.exists() ) {
        if ( isFailIfFileExists() ) {
          // File exists and fail flag is on.
          result.setResult( false );
          logError( "File [" + realFilename + "] exists, failing." );
        } else {
          // File already exists, no reason to try to create it
          result.setResult( true );
          logBasic( "File [" + realFilename + "] already exists, not recreating." );
        }
        // add filename to result filenames if needed
        if ( isAddFilenameToResult() ) {
          addFilenameToResult( realFilename, result, parentJob );
        }
      } else {
        // No file yet, create an empty file.
        fileObject.createFile();
        logBasic( "File [" + realFilename + "] created!" );
        // add filename to result filenames if needed
        if ( isAddFilenameToResult() ) {
          addFilenameToResult( realFilename, result, parentJob );
        }
        result.setResult( true );
      }
    } catch ( IOException e ) {
      logError( "Could not create file [" + realFilename + "], exception: " + e.getMessage() );
      result.setResult( false );
      result.setNrErrors( 1 );
    } finally {
      if ( fileObject != null ) {
        try {
          fileObject.close();
          fileObject = null;
        } catch ( IOException ex ) {
          // Ignore
        }
      }
    }
  } else {
    logError( "No filename is defined." );
  }

  return result;
}
 
Example 18
Source File: ActionCopyMoveResultFilenamesI.java    From hop with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setNrErrors( 1 );
  result.setResult( false );

  boolean deleteFile = getAction().equals( "delete" );

  String realdestinationFolder = null;
  if ( !deleteFile ) {
    realdestinationFolder = environmentSubstitute( getDestinationFolder() );

    if ( !CreateDestinationFolder( realdestinationFolder ) ) {
      return result;
    }
  }
  if ( !Utils.isEmpty( wildcard ) ) {
    wildcardPattern = Pattern.compile( environmentSubstitute( wildcard ) );
  }
  if ( !Utils.isEmpty( wildcardexclude ) ) {
    wildcardExcludePattern = Pattern.compile( environmentSubstitute( wildcardexclude ) );
  }

  if ( previousResult != null ) {
    NrErrors = 0;
    limitFiles = Const.toInt( environmentSubstitute( getNrErrorsLessThan() ), 10 );
    NrErrors = 0;
    NrSuccess = 0;
    successConditionBroken = false;
    successConditionBrokenExit = false;

    FileObject file = null;

    try {
      int size = result.getResultFiles().size();
      if ( log.isBasic() ) {
        logBasic( BaseMessages.getString( PKG, "ActionCopyMoveResultFilenames.log.FilesFound", "" + size ) );
      }

      List<ResultFile> resultFiles = result.getResultFilesList();
      if ( resultFiles != null && resultFiles.size() > 0 ) {
        for ( Iterator<ResultFile> it = resultFiles.iterator(); it.hasNext() && !parentWorkflow.isStopped(); ) {
          if ( successConditionBroken ) {
            logError( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors ) );
            throw new Exception( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.Error.SuccessConditionbroken", "" + NrErrors ) );
          }

          ResultFile resultFile = it.next();
          file = resultFile.getFile();
          if ( file != null && file.exists() ) {
            if ( !specifywildcard
              || ( CheckFileWildcard( file.getName().getBaseName(), wildcardPattern, true )
              && !CheckFileWildcard( file.getName().getBaseName(), wildcardExcludePattern, false )
              && specifywildcard ) ) {
              // Copy or Move file
              if ( !processFile( file, realdestinationFolder, result, parentWorkflow, deleteFile ) ) {
                // Update Errors
                updateErrors();
              }
            }

          } else {
            logError( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.log.ErrorCanNotFindFile", file.toString() ) );
            // Update Errors
            updateErrors();
          }
        } // end for
      }
    } catch ( Exception e ) {
      logError( BaseMessages.getString( PKG, "ActionCopyMoveResultFilenames.Error", e.toString() ) );
    } finally {
      if ( file != null ) {
        try {
          file.close();
          file = null;
        } catch ( Exception ex ) { /* Ignore */
        }
      }
    }
  }
  // Success Condition
  result.setNrErrors( NrErrors );
  result.setNrLinesWritten( NrSuccess );
  if ( getSuccessStatus() ) {
    result.setResult( true );
  }

  return result;
}
 
Example 19
Source File: JobEntryFolderIsEmpty.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public boolean includeFile( FileSelectInfo info ) throws ExpectedException {
  boolean returncode = false;
  FileObject file_name = null;
  boolean rethrow = false;
  try {
    if ( !info.getFile().toString().equals( root_folder ) ) {
      // Pass over the Base folder itself
      if ( ( info.getFile().getType() == FileType.FILE ) ) {
        if ( info.getFile().getParent().equals( info.getBaseFolder() ) ) {
          // We are in the Base folder
          if ( ( isSpecifyWildcard() && GetFileWildcard( info.getFile().getName().getBaseName() ) )
            || !isSpecifyWildcard() ) {
            if ( log.isDetailed() ) {
              log.logDetailed( "We found file : " + info.getFile().toString() );
            }
            filescount++;
          }
        } else {
          // We are not in the base Folder...ONLY if Use sub folders
          // We are in the Base folder
          if ( isIncludeSubFolders() ) {
            if ( ( isSpecifyWildcard() && GetFileWildcard( info.getFile().getName().getBaseName() ) )
              || !isSpecifyWildcard() ) {
              if ( log.isDetailed() ) {
                log.logDetailed( "We found file : " + info.getFile().toString() );
              }
              filescount++;
            }
          }
        }
      } else {
        folderscount++;
      }
    }
    if ( filescount > 0 ) {
      rethrow = true;
      throw new ExpectedException();
    }
    return true;

  } catch ( Exception e ) {
    if ( !rethrow ) {
      log.logError( BaseMessages.getString( PKG, "JobFolderIsEmpty.Error" ), BaseMessages.getString(
        PKG, "JobFolderIsEmpty.Error.Exception", info.getFile().toString(), e.getMessage() ) );
      returncode = false;
    } else {
      throw (ExpectedException) e;
    }
  } finally {
    if ( file_name != null ) {
      try {
        file_name.close();
        file_name = null;
      } catch ( IOException ex ) { /* Ignore */
      }
    }
  }
  return returncode;
}
 
Example 20
Source File: TextFileInputTest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private static void deleteVfsFile( String path ) throws Exception {
  FileObject fileObject = TestUtils.getFileObject( path );
  fileObject.close();
  fileObject.delete();
}