List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private void addOriginSigsRels(String signatureZipEntryName, ZipOutputStream zipOutputStream) throws ParserConfigurationException, IOException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document originSignRelsDocument = documentBuilder.newDocument(); Element relationshipsElement = originSignRelsDocument .createElementNS("http://schemas.openxmlformats.org/package/2006/relationships", "Relationships"); relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://schemas.openxmlformats.org/package/2006/relationships"); originSignRelsDocument.appendChild(relationshipsElement); Element relationshipElement = originSignRelsDocument .createElementNS("http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); String relationshipId = "rel-" + UUID.randomUUID().toString(); relationshipElement.setAttribute("Id", relationshipId); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); String target = FilenameUtils.getName(signatureZipEntryName); LOG.debug("target: " + target); relationshipElement.setAttribute("Target", target); relationshipsElement.appendChild(relationshipElement); zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); }
From source file:languageTools.analyzer.mas.MASValidator.java
@Override public Void visitAgentFile(AgentFileContext ctx) { boolean problem = false; // Get agent file name String path = visitString(ctx.string()); File file = new File(path); if (!file.isAbsolute()) { // relative to path specified for MAS file file = new File(getPathRelativeToSourceFile(path)); }//from ww w . java2 s . com // Check file extension String ext = FilenameUtils.getExtension(path); if (Extension.getFileExtension(file) != Extension.GOAL) { problem = reportError(MASError.AGENTFILE_OTHER_EXTENSION, ctx.string(), ext); } else if (!file.isFile()) { problem = reportError(MASError.AGENTFILE_COULDNOT_FIND, ctx.string(), file.getPath()); } // Get (optional) parameters Map<String, String> parameters = new HashMap<String, String>(); for (AgentFileParContext parameter : ctx.agentFilePar()) { Map.Entry<String, String> keyValuePair = visitAgentFilePar(parameter); String key = keyValuePair.getKey(); if (parameters.containsKey(key)) { reportWarning(MASWarning.AGENTFILE_DUPLICATE_KEY, parameter, key); } else { parameters.put(key, keyValuePair.getValue()); } } // Construct agent symbol String agentName; if (parameters.containsKey("name")) { agentName = parameters.get("name"); } else { agentName = FilenameUtils.getBaseName(FilenameUtils.getName(path)); } // Add agent symbol to symbol table for later reference (if key does not // yet exist). if (!this.agentFiles.define(new MASSymbol(agentName, file, getSourceInfo(ctx)))) { problem = reportWarning(MASWarning.AGENTFILES_DUPLICATE_NAME, ctx.string(), agentName); } // Get KR language String interfaceName = parameters.get("language"); KRInterface krInterface = null; try { if (interfaceName == null) { // no parameter set, use default krInterface = KRFactory.getDefaultInterface(); } else { krInterface = KRFactory.getInterface(interfaceName); } } catch (KRInterfaceNotSupportedException | KRInitFailedException e) { reportError(MASError.KRINTERFACE_NOT_SUPPORTED, ctx.agentFilePar().get(0), interfaceName); } // Add agent file to MAS program (only if no problems were detected and // file does not yet exist). if (!problem && !getProgram().getAgentFiles().contains(file)) { getProgram().addAgentFile(file); getProgram().setKRInterface(file, krInterface); } return null; // Java says must return something even when Void }
From source file:com.opendesign.controller.ProjectController.java
/** * ?? ? //ww w. j a va2 s.com * * @param projectVO * @param request * @return * @throws Exception */ @RequestMapping(value = "/updateProject.ajax") public ModelAndView ajaxUpdateProject(@ModelAttribute("project") ProjectVO projectVO, MultipartHttpServletRequest request) throws Exception { Map<String, Object> resultMap = new HashMap<String, Object>(); UserVO loginUser = CmnUtil.getLoginUser(request); if (loginUser == null || !StringUtil.isNotEmpty(loginUser.getSeq())) { resultMap.put("result", "100"); return new JsonModelAndView(resultMap); } projectVO.setOwnerSeq(Integer.parseInt(loginUser.getSeq())); String fileUploadDbPath = CmnUtil.handleFileUpload(request, "fileUrlFile", FileUploadDomain.PROJECT); String oriFileName = CmnUtil.handleFileUploadGetOriFileName(request, "fileUrlFile"); if (StringUtil.isNotEmpty(fileUploadDbPath)) { /* * ?? Thumbnail * ?? ? ? ? Thumbnail */ String fileUploadDir = CmnUtil.getFileUploadDir(request, FileUploadDomain.PROJECT); String fileName = File.separator + FilenameUtils.getName(fileUploadDbPath); ThumbnailManager.saveThumbDesignWorkMedium(fileUploadDir + fileName); ThumbnailManager.saveThumbProjectWorkMedium(fileUploadDir + fileName); projectVO.setFileUrl(fileUploadDbPath); projectVO.setFileName(oriFileName); } String currentDate = Day.getCurrentTimestamp().substring(0, 12); projectVO.setUpdateTime(currentDate); String[] categoryCodes = request.getParameterValues("categoryCodes"); String[] emails = request.getParameterValues("emails"); int projectSeq = service.updateProject(projectVO, categoryCodes, emails); resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS); return new JsonModelAndView(resultMap); }
From source file:eu.esdihumboldt.hale.common.core.io.project.impl.ArchiveProjectWriter.java
/** * Update the resources and copy them into the target directory * /*from w w w . j a v a2 s. c o m*/ * @param targetDirectory target directory * @param includeWebResources whether to include web resources in the copy * @param progress the progress indicator * @param reporter the reporter to use for the execution report * @throws IOException if an I/O operation fails */ protected void updateResources(File targetDirectory, boolean includeWebResources, ProgressIndicator progress, IOReporter reporter) throws IOException { progress.begin("Copy resources", ProgressIndicator.UNKNOWN); try { List<IOConfiguration> resources = getProject().getResources(); // every resource needs his own directory int count = 1; // true if excluded files should be skipped; false is default boolean excludeDataFiles = getParameter(EXLUDE_DATA_FILES).as(Boolean.class, false); // resource locations mapped to new resource path Map<URI, String> handledResources = new HashMap<>(); Iterator<IOConfiguration> iter = resources.iterator(); while (iter.hasNext()) { IOConfiguration resource = iter.next(); // check if ActionId is equal to // eu.esdihumboldt.hale.common.instance.io.InstanceIO.ACTION_LOAD_SOURCE_DATA // import not possible due to cycle errors if (excludeDataFiles && resource.getActionId().equals("eu.esdihumboldt.hale.io.instance.read.source")) { // delete reference in project file iter.remove(); continue; } // get resource path Map<String, Value> providerConfig = resource.getProviderConfiguration(); String path = providerConfig.get(ImportProvider.PARAM_SOURCE).toString(); URI pathUri; try { pathUri = new URI(path); } catch (URISyntaxException e1) { reporter.error(new IOMessageImpl("Skipped resource because of invalid URI: " + path, e1)); continue; } if (!pathUri.isAbsolute()) { if (getPreviousTarget() != null) { pathUri = getPreviousTarget().resolve(pathUri); } else { log.warn("Could not resolve relative path " + pathUri.toString()); } } // check if path was already handled if (handledResources.containsKey(pathUri)) { providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(handledResources.get(pathUri))); // skip copying the resource continue; } String scheme = pathUri.getScheme(); LocatableInputSupplier<? extends InputStream> input = null; if (scheme != null) { if (scheme.equals("http") || scheme.equals("https")) { // web resource if (includeWebResources) { input = new DefaultInputSupplier(pathUri); } else { // web resource that should not be included this // time // but the resolved URI should be stored // nevertheless // otherwise the URI may be invalid if it was // relative providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(pathUri.toASCIIString())); continue; } } else if (scheme.equals("file") || scheme.equals("platform") || scheme.equals("bundle") || scheme.equals("jar")) { // files need always to be included // platform resources (or other internal resources) // should be included as well input = new DefaultInputSupplier(pathUri); } else { // other type of URI, e.g. JDBC // not to be included providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(pathUri.toASCIIString())); continue; } } else { // now can't open that, can we? reporter.error(new IOMessageImpl( "Skipped resource because it cannot be loaded from " + pathUri.toString(), null)); continue; } progress.setCurrentTask("Copying resource at " + path); // every resource file is copied into an own resource // directory in the target directory String resourceFolder = "resource" + count; File newDirectory = new File(targetDirectory, resourceFolder); try { newDirectory.mkdir(); } catch (SecurityException e) { throw new IOException("Can not create directory " + newDirectory.toString(), e); } // Extract the file name from pathUri.getPath(). // This will produce a non-URL-encoded file name to be used in // the File(File parent, String child) constructor below String fileName = FilenameUtils.getName(pathUri.getPath().toString()); if (path.isEmpty()) { fileName = "file"; } File newFile = new File(newDirectory, fileName); Path target = newFile.toPath(); // retrieve the resource advisor Value ct = providerConfig.get(ImportProvider.PARAM_CONTENT_TYPE); IContentType contentType = null; if (ct != null) { contentType = HalePlatform.getContentTypeManager().getContentType(ct.as(String.class)); } ResourceAdvisor ra = ResourceAdvisorExtension.getInstance().getAdvisor(contentType); // copy the resource progress.setCurrentTask("Copying resource at " + path); // Extract the URL-encoded file name of the copied resource and // build the new relative resource path String resourceName = FilenameUtils.getName(target.toUri().toString()); String newPath = resourceFolder + "/" + resourceName; boolean skipCopy = getParameter(EXCLUDE_CACHED_RESOURCES).as(Boolean.class, false) && !resource.getCache().isEmpty(); if (!skipCopy) { ra.copyResource(input, target, contentType, includeWebResources, reporter); // store new path for resource handledResources.put(pathUri, newPath); } // update the provider configuration providerConfig.put(ImportProvider.PARAM_SOURCE, Value.of(newPath)); count++; } } finally { progress.end(); } }
From source file:ddf.catalog.resource.impl.URLResourceReader.java
private ResourceResponse retrieveHttpProduct(URI resourceURI, String productName, String bytesToSkip, Map<String, Serializable> properties) throws ResourceNotFoundException { try {/* w w w. ja va 2 s .co m*/ LOGGER.debug("Opening connection to: {}", resourceURI.toString()); WebClient client = getWebClient(resourceURI.toString()); Object subjectObj = properties.get(SecurityConstants.SECURITY_SUBJECT); if (subjectObj != null) { Subject subject = (Subject) subjectObj; LOGGER.debug("Setting Subject on webclient: {}", subject); RestSecurity.setSubjectOnClient(subject, client); } Response response = client.get(); MultivaluedMap<String, Object> headers = response.getHeaders(); List<Object> cdHeaders = headers.get(HttpHeaders.CONTENT_DISPOSITION); if (cdHeaders != null && !cdHeaders.isEmpty()) { String contentHeader = (String) cdHeaders.get(0); productName = StringUtils.defaultIfBlank(handleContentDispositionHeader(contentHeader), productName); } String mimeType = getMimeType(resourceURI, productName); Response clientResponse = client.get(); InputStream is = null; Object entityObj = clientResponse.getEntity(); if (entityObj instanceof InputStream) { is = (InputStream) entityObj; if (Response.Status.OK.getStatusCode() != clientResponse.getStatus()) { String error = null; try { if (is != null) { error = IOUtils.toString(is); } } catch (IOException ioe) { LOGGER.debug("Could not convert error message to a string for output.", ioe); } String errorMsg = "Received error code while retrieving resource (status " + clientResponse.getStatus() + "): " + error; LOGGER.warn(errorMsg); throw new ResourceNotFoundException(errorMsg); } } else { throw new ResourceNotFoundException("Received null response while retrieving resource."); } skipBytes(is, bytesToSkip); return new ResourceResponseImpl( new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName))); } catch (MimeTypeResolutionException | IOException | WebApplicationException e) { LOGGER.error("Error retrieving resource", e); throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e); } }
From source file:com.ephesoft.gxt.batchinstance.server.CopyTroubleshootingArtifacts.java
/** * This method copies the exported batch class to the download folder. * /*from w w w.j av a 2 s .c o m*/ * @param batchSchemaService {@link BatchSchemaService} instance of batch schema service * @param imageMagickBaseFolderParam {@link String} the parameter value of checkbox for image magick base folder * @param isSearchSampleNameParam {@link String} the parameter value of checkbox for lucene search classification * @param batchClass {@link BatchClass} the batch class of batch instance * @param tempFolderLocation {@link String} the temporary folder location * @throws IOException if an exception occurs while creating the serialized file. */ private void createExportedBatchClassFolder(final BatchSchemaService batchSchemaService, final String imageMagickBaseFolderParam, final String isSearchSampleNameParam, final BatchClass batchClass, final String tempFolderLocation) throws IOException { File copiedFolder = new File(tempFolderLocation); if (copiedFolder.exists()) { copiedFolder.delete(); } copiedFolder.mkdirs(); BatchClassUtil.copyModules(batchClass); BatchClassUtil.copyDocumentTypes(batchClass); BatchClassUtil.copyScannerConfig(batchClass); BatchClassUtil.exportEmailConfiguration(batchClass); BatchClassUtil.exportUserGroups(batchClass); BatchClassUtil.exportBatchClassField(batchClass); BatchClassUtil.exportCMISConfiguration(batchClass); File serializedExportFile = new File(EphesoftStringUtil.concatenate(tempFolderLocation, File.separator, batchClass.getIdentifier(), SERIALIZATION_EXT)); try { SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile)); File originalFolder = new File(EphesoftStringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator, batchClass.getIdentifier())); if (originalFolder.isDirectory()) { final String[] folderList = originalFolder.list(); Arrays.sort(folderList); for (int i = 0; i < folderList.length; i++) { if (folderList[i].endsWith(SERIALIZATION_EXT)) { // skip previous ser file since new is created. } else if (FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName()) || FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getTestTableFolderName()) || FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getFileboundPluginMappingFolderName())) { // Skip this folder continue; } else if (FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName()) && !EphesoftStringUtil.isNullOrEmpty(imageMagickBaseFolderParam)) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } else if (FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getSearchSampleName()) && !EphesoftStringUtil.isNullOrEmpty(isSearchSampleNameParam)) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } else if (!(FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName()) || FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } } } } catch (FileNotFoundException e) { // Unable to read serializable file LOGGER.error(EphesoftStringUtil.concatenate("Error occurred while creating the serializable file. ", e.getMessage()), e); foldersNotCopied.append(EphesoftStringUtil.concatenate(BATCH_CLASS_FOLDER, SEMI_COLON)); } catch (IOException e) { // Unable to create the temporary export file(s)/folder(s) LOGGER.error(EphesoftStringUtil.concatenate("Error occurred while creating the serializable file.", e.getMessage()), e); } }
From source file:com.legstar.cixs.gen.AbstractTestTemplate.java
/** * Check a result against a reference.//from w w w . ja v a 2 s . c o m * <p/> * Here result is a folder as well as a reference. In check mode, all files * are compared. In creation mode, all reference files are created as copies * from the results. * * @param refFolder the reference folder (containing reference files) * @param resultFolder the result folder (containing generated files) * @param extension the files extension to process * @throws Exception if something fails */ @SuppressWarnings("unchecked") public void check(final File refFolder, final File resultFolder, final String extension) throws Exception { if (isCreateReferences()) { Collection<File> resultFiles = FileUtils.listFiles(resultFolder, new String[] { extension }, false); for (File resultFile : resultFiles) { FileUtils.copyFileToDirectory(resultFile, refFolder); } } else { Collection<File> referenceFiles = FileUtils.listFiles(refFolder, new String[] { extension }, false); for (File referenceFile : referenceFiles) { File resultFile = new File(resultFolder, FilenameUtils.getName(referenceFile.getPath())); check(referenceFile, resultFile); } } }
From source file:com.taobao.android.utils.ZipUtils.java
/** * zip?/*from w ww . jav a 2s . co m*/ * * @param zipFile * @param path * @param destFolder * @throws IOException */ public static File extractZipFileToFolder(File zipFile, String path, File destFolder) { ZipFile zip; File destFile = null; try { zip = new ZipFile(zipFile); ZipArchiveEntry zipArchiveEntry = zip.getEntry(path); if (null != zipArchiveEntry) { String name = zipArchiveEntry.getName(); name = FilenameUtils.getName(name); destFile = new File(destFolder, name); destFolder.mkdirs(); destFile.createNewFile(); InputStream is = zip.getInputStream(zipArchiveEntry); FileOutputStream fos = new FileOutputStream(destFile); int length = 0; byte[] b = new byte[1024]; while ((length = is.read(b, 0, 1024)) != -1) { fos.write(b, 0, length); } is.close(); fos.close(); } if (null != zip) ZipFile.closeQuietly(zip); } catch (IOException e) { e.printStackTrace(); } return destFile; }
From source file:edu.ku.brc.specify.tasks.subpane.images.CollectionDataFetcher.java
/** * @param rs// w w w . j a v a 2 s . c o m * @param tableId * @return * @throws SQLException */ private List<Triple<String, String, Object>> readDataIntoMap(final ResultSet rs, final int tableId) throws SQLException { List<BubbleDisplayInfo> displayInfos = bciHash.get(tableId); List<Triple<String, String, Object>> dataList = new ArrayList<Triple<String, String, Object>>(); if (rs != null) { if (rs.next()) { ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i < rsmd.getColumnCount(); i++) { BubbleDisplayInfo bdi = displayInfos.get(i - 1); Object val = rs.getObject(i); if (bdi.getColTblId() == Attachment.getClassTableId() && bdi.getColumnName().equals("OrigFilename")) { val = FilenameUtils.getName(val.toString()); } if (bdi.getFormatter() != null) { val = bdi.getFormatter().formatToUI(val); } else if (val instanceof Calendar) { val = scrDateFormat.format((Calendar) val); } else if (val instanceof Date) { val = scrDateFormat.format((Date) val); } else if (val instanceof BigDecimal) { val = StringUtils.stripEnd(val.toString(), "0"); } else if (bdi.getFieldInfo().getPickListName() != null) { PickListIFace pl = PickListDBAdapterFactory.getInstance() .getPickList(bdi.getFieldInfo().getPickListName()); if (pl != null) { for (PickListItemIFace pli : pl.getItems()) { if (pli.getValue() != null && pli.getValue().equals(val)) { val = pli.getTitle(); break; } } } } String title = getColumnTitle(bdi, tableId) + ": "; dataList.add(new Triple<String, String, Object>(bdi.getFieldInfo().getColumn(), title, val)); } //System.out.println(rs.getObject(rsmd.getColumnCount())); dataList.add(new Triple<String, String, Object>("Id", "Id", rs.getObject(rsmd.getColumnCount()))); } rs.close(); } return dataList; }
From source file:it.geosolutions.geobatch.flow.event.consumer.file.FileBasedEventConsumer.java
/*************************************************************************** * Main Thread cycle./*from www .j a v a 2s . co m*/ * * <LI>Create needed dirs</LI> <LI>Optionally backup files</LI> <LI>Move * files into a job-specific working dir</LI> <LI>Run the actions</LI> */ public Queue<FileSystemEvent> call() throws Exception { this.canceled = false; boolean jobResultSuccessful = false; Throwable exceptionOccurred = null; getListenerForwarder().setTask("Configuring"); getListenerForwarder().started(); try { // create live working dir getListenerForwarder().progressing(10, "Managing events"); // // Management of current working directory // // if we work on the input directory, we do not move around // anything, unless we want to // perform a backup if (configuration.isPerformBackup() || !configuration.isPreserveInput()) { if (!flowInstanceTempDir.exists() && !flowInstanceTempDir.mkdirs()) { throw new IllegalStateException("Could not create consumer backup directory!"); } } // set the consumer running context // don't know how this running context will be used in a FileBased* hiererchy, anyway let's force the use of proper methods. setRunningContext("DONT_USE_AS_FILEPATH_" + flowInstanceTempDir.getAbsolutePath()); // create backup dir. Creation is deferred until first usage getListenerForwarder().progressing(20, "Creating backup dir"); final File backupDirectory = new File(flowInstanceTempDir, "backup"); if (configuration.isPerformBackup()) { if (!backupDirectory.exists() && !backupDirectory.mkdirs()) { throw new IllegalStateException("Could not create consumer backup directory!"); } } // // Cycling on all the input events // Queue<FileSystemEvent> fileEventList = new LinkedList<FileSystemEvent>(); int numProcessedFiles = 0; for (FileSystemEvent event : this.eventsQueue) { if (LOGGER.isInfoEnabled()) { LOGGER.info( "[" + Thread.currentThread().getName() + "]: new element retrieved from the MailBox."); } // get info for the input file event final File sourceDataFile = event.getSource(); final String fileBareName; if ((sourceDataFile != null) && sourceDataFile.exists()) { fileBareName = FilenameUtils.getName(sourceDataFile.toString()); getListenerForwarder().progressing(30 + (10f / this.eventsQueue.size() * numProcessedFiles++), "Preprocessing event " + fileBareName); // // copy input file/dir to current working directory // if (IOUtils.acquireLock(this, sourceDataFile)) { // // Backing up inputs? // if (this.configuration.isPerformBackup()) { // Backing up files and delete sources. getListenerForwarder().progressing( 30 + (10f / this.eventsQueue.size() * numProcessedFiles++), "Creating backup files"); // In case we do not work on the input as is, we // move it to our // current working directory final File destDataFile = new File(backupDirectory, fileBareName); if (sourceDataFile.isDirectory()) { FileUtils.copyDirectory(sourceDataFile, destDataFile); } else { FileUtils.copyFile(sourceDataFile, destDataFile); } } // // Working on input events directly without moving to // working dir? // if (!configuration.isPreserveInput()) { // In case we do not work on the input as is, we // move it to our current working directory final File destDataFile = new File(flowInstanceTempDir, fileBareName); if (sourceDataFile.isDirectory()) { FileUtils.moveDirectory(sourceDataFile, destDataFile); } else { FileUtils.moveFile(sourceDataFile, destDataFile); } // adjust event sources since we moved the files // locally fileEventList.offer(new FileSystemEvent(destDataFile, event.getEventType())); } else { // we are going to work directly on the input files fileEventList.offer(event); } if (LOGGER.isInfoEnabled()) { LOGGER.info( "[" + Thread.currentThread().getName() + "]: accepted file " + sourceDataFile); } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error(new StringBuilder("[").append(Thread.currentThread().getName()) .append("]: could not lock file ").append(sourceDataFile).toString()); } /* * TODO: lock not acquired: what else? */ } } // event.getSource()!=null && sourceDataFile.exists() else { /* * event.getSource()==null || !sourceDataFile.exists() this * could be an empty file representing a POLLING event */ fileEventList.offer(event); } } // // // TODO if no further processing is necessary or can be // done due to some error, set eventConsumerStatus to Finished or // Failure. (etj: ???) // // if (LOGGER.isInfoEnabled()) { LOGGER.info("[" + Thread.currentThread().getName() + "]: new element processed."); } // // Finally, run the Actions on the files getListenerForwarder().progressing(50, "Running actions"); try { // apply actions into the actual context (currentRunDirectory) fileEventList = this.applyActions(fileEventList); this.setStatus(EventConsumerStatus.COMPLETED); jobResultSuccessful = true; } catch (ActionException ae) { this.setStatus(EventConsumerStatus.FAILED); throw ae; } return fileEventList; } catch (ActionException e) { String msg = "[" + Thread.currentThread().getName() + "] Error during " + e.getType().getSimpleName() + " execution: " + e.getLocalizedMessage(); if (LOGGER.isDebugEnabled()) { LOGGER.error(msg, e); } else { LOGGER.error(msg); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("[" + Thread.currentThread().getName() + "] could not move file " + " due to the following IO error: " + e.getLocalizedMessage(), e); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (InterruptedException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("[" + Thread.currentThread().getName() + "] could not move file " + " due to an InterruptedException: " + e.getLocalizedMessage(), e); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (RuntimeException e) { exceptionOccurred = e; throw e; } finally { getListenerForwarder().progressing(100, "Completed"); if (LOGGER.isInfoEnabled()) { LOGGER.info(Thread.currentThread().getName() + " DONE!"); } // this.dispose(); if (jobResultSuccessful && (exceptionOccurred == null)) { getListenerForwarder().completed(); } else { getListenerForwarder().failed(exceptionOccurred); } } return null; }