List of usage examples for org.apache.commons.vfs2 FileObject delete
boolean delete() throws FileSystemException;
From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java
/** * Take specified action to either move or delete the processed file, depending on the outcome * @param entry the PollTableEntry for the file that has been processed * @param fileObject the FileObject representing the file to be moved or deleted *///from w w w . j av a2s . c o m private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject) throws AxisFault { String moveToDirectoryURI = null; try { switch (entry.getLastPollState()) { case PollTableEntry.SUCCSESSFUL: if (entry.getActionAfterProcess() == PollTableEntry.MOVE) { moveToDirectoryURI = entry.getMoveAfterProcess(); } break; case PollTableEntry.FAILED: if (entry.getActionAfterFailure() == PollTableEntry.MOVE) { moveToDirectoryURI = entry.getMoveAfterFailure(); } break; default: return; } if (moveToDirectoryURI != null) { FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI); String prefix; if (entry.getMoveTimestampFormat() != null) { prefix = entry.getMoveTimestampFormat().format(new Date()); } else { prefix = ""; } FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName()); if (log.isDebugEnabled()) { log.debug("Moving to file :" + dest.getName().getURI()); } try { fileObject.moveTo(dest); } catch (FileSystemException e) { handleException("Error moving file : " + fileObject + " to " + moveToDirectoryURI, e); } } else { try { if (log.isDebugEnabled()) { log.debug("Deleting file :" + fileObject); } fileObject.close(); if (!fileObject.delete()) { String msg = "Cannot delete file : " + fileObject; log.error(msg); throw new AxisFault(msg); } } catch (FileSystemException e) { log.error("Error deleting file : " + fileObject, e); } } } catch (FileSystemException e) { handleException("Error resolving directory to move after processing : " + moveToDirectoryURI, e); } }
From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java
@Test public void testCreateSuccessWithArgs() throws ClassNotFoundException, InvocationTargetException, InstantiationException, KettlePluginException, IllegalAccessException, KettleFileException, IOException { String testName = "testName"; String canonicalName = ValueMetaInteger.class.getCanonicalName(); FileObject myFile = KettleVFS.getFileObject("ram://testCreateSuccessWithArgs"); try (FileObject fileObject = myFile) { try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) { IOUtils.copy(//from w w w . ja v a 2 s.co m getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"), outputStream); } String packageName = ValueMetaInteger.class.getPackage().getName(); when(bundleWiring.findEntries("/" + packageName.replace(".", "/"), ValueMetaInteger.class.getSimpleName() + ".class", 0)) .thenReturn(Arrays.asList(fileObject.getURL())); when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() { @Override public Class<?> answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader()) .loadClass((String) arguments[0], (boolean) arguments[1]); } }); when(pluginClassloaderGetter.getPluginClassloader(LifecyclePluginType.class.getCanonicalName(), ShimBridgingClassloader.HADOOP_SPOON_PLUGIN)).thenReturn(parentClassLoader); // With name Object o = ShimBridgingClassloader.create(bundleContext, canonicalName, Arrays.<Object>asList(testName)); // Interface should be same class object assertTrue(o instanceof ValueMetaInterface); assertEquals(testName, ((ValueMetaInterface) o).getName()); // Shouldn't be true because it was loaded from diff classloader assertFalse(o instanceof ValueMetaInteger); // Null argument ArrayList<Object> arguments = new ArrayList<>(); arguments.add(null); o = ShimBridgingClassloader.create(bundleContext, canonicalName, arguments); // Interface should be same class object assertTrue(o instanceof ValueMetaInterface); assertNull(((ValueMetaInterface) o).getName()); // Shouldn't be true because it was loaded from diff classloader assertFalse(o instanceof ValueMetaInteger); // Null arg list o = ShimBridgingClassloader.create(bundleContext, canonicalName, null); // Interface should be same class object assertTrue(o instanceof ValueMetaInterface); assertNull(((ValueMetaInterface) o).getName()); // Shouldn't be true because it was loaded from diff classloader assertFalse(o instanceof ValueMetaInteger); // Empty arg list o = ShimBridgingClassloader.create(bundleContext, canonicalName, new ArrayList<Object>()); // Interface should be same class object assertTrue(o instanceof ValueMetaInterface); assertNull(((ValueMetaInterface) o).getName()); // Shouldn't be true because it was loaded from diff classloader assertFalse(o instanceof ValueMetaInteger); } finally { myFile.delete(); } }
From source file:org.aludratest.service.file.impl.AbstractFileAction.java
protected boolean checkWritable(FileObject file, boolean overwrite) { try {/*from www. j a v a2 s .co m*/ if (file.exists()) { if (overwrite) { file.delete(); } else { throw new FunctionalFailure("File expected to be absent: " + pathFromRoot(file)); } return true; } else { return false; } } catch (IOException e) { throw new TechnicalException("Error checking file", e); } }
From source file:org.aludratest.service.file.impl.FileActionImpl.java
private boolean checkWritable(FileObject file, boolean overwrite) { try {/*from ww w . j av a 2 s. c om*/ if (file.exists()) { if (overwrite) { file.delete(); } else { throw new FunctionalFailure("File expected to be absent: " + pathFromRoot(file)); } return true; } else { return false; } } catch (FileSystemException e) { throw new TechnicalException("Error checking file", e); } }
From source file:org.apache.hadoop.gateway.topology.file.FileTopologyProviderTest.java
@Test public void testGetTopologies() throws Exception { FileObject dir = createDir("ram:///test/dir"); createFile(dir, "one.xml", "org/apache/hadoop/gateway/topology/file/topology-one.xml", 1L); TestTopologyListener topoListener = new TestTopologyListener(); FileListenerDelegator fileListener = new FileListenerDelegator(); NoOpFileMonitor monitor = new NoOpFileMonitor(fileListener); FileTopologyProvider provider = new FileTopologyProvider(monitor, dir); provider.addTopologyChangeListener(topoListener); fileListener.delegate = provider;/*from w ww .jav a2s. c o m*/ // Unit test "hack" to force monitor to execute. provider.reloadTopologies(); Collection<Topology> topologies = provider.getTopologies(); assertThat(topologies, notNullValue()); assertThat(topologies.size(), is(1)); Topology topology = topologies.iterator().next(); assertThat(topology.getName(), is("one")); assertThat(topology.getTimestamp(), is(1L)); assertThat(topoListener.events.size(), is(1)); topoListener.events.clear(); // Add a file to the directory. FileObject two = createFile(dir, "two.xml", "org/apache/hadoop/gateway/topology/file/topology-two.xml", 1L); fileListener.fileCreated(new FileChangeEvent(two)); topologies = provider.getTopologies(); assertThat(topologies.size(), is(2)); Set<String> names = new HashSet<String>(Arrays.asList("one", "two")); Iterator<Topology> iterator = topologies.iterator(); topology = iterator.next(); assertThat(names, hasItem(topology.getName())); names.remove(topology.getName()); topology = iterator.next(); assertThat(names, hasItem(topology.getName())); names.remove(topology.getName()); assertThat(names.size(), is(0)); assertThat(topoListener.events.size(), is(1)); List<TopologyEvent> events = topoListener.events.get(0); assertThat(events.size(), is(1)); TopologyEvent event = events.get(0); assertThat(event.getType(), is(TopologyEvent.Type.CREATED)); assertThat(event.getTopology(), notNullValue()); // Update a file in the directory. two = createFile(dir, "two.xml", "org/apache/hadoop/gateway/topology/file/topology-three.xml", 2L); fileListener.fileChanged(new FileChangeEvent(two)); topologies = provider.getTopologies(); assertThat(topologies.size(), is(2)); names = new HashSet<String>(Arrays.asList("one", "two")); iterator = topologies.iterator(); topology = iterator.next(); assertThat(names, hasItem(topology.getName())); names.remove(topology.getName()); topology = iterator.next(); assertThat(names, hasItem(topology.getName())); names.remove(topology.getName()); assertThat(names.size(), is(0)); // Remove a file from the directory. two.delete(); fileListener.fileDeleted(new FileChangeEvent(two)); topologies = provider.getTopologies(); assertThat(topologies.size(), is(1)); topology = topologies.iterator().next(); assertThat(topology.getName(), is("one")); assertThat(topology.getTimestamp(), is(1L)); }
From source file:org.apache.olingo.fit.utils.FSManager.java
public final FileObject putInMemory(final InputStream is, final String path) throws IOException { LOG.info("Write in memory {}", path); final FileObject memObject = fsManager.resolveFile(MEM_PREFIX + path); if (memObject.exists()) { memObject.delete(); }/*from www. j a v a2 s. c o m*/ // create in-memory file memObject.createFile(); // read in-memory content final OutputStream os = memObject.getContent().getOutputStream(); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); return memObject; }
From source file:org.apache.olingo.fit.utils.FSManager.java
public void deleteFile(final String relativePath) { for (Accept accept : Accept.values()) { final String path = getAbsolutePath(relativePath, accept); LOG.info("Delete {}", path); try {/* www. ja v a2 s . c om*/ final FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path); if (fileObject.exists()) { fileObject.delete(); } } catch (IOException ignore) { // ignore exception } } }
From source file:org.apache.synapse.commons.vfs.VFSUtils.java
/** * Acquires a file item lock before processing the item, guaranteing that * the file is not processed while it is being uploaded and/or the item is * not processed by two listeners/* ww w .j a v a 2 s .com*/ * * @param fsManager * used to resolve the processing file * @param fo * representing the processing file item * @param fso * represents file system options used when resolving file from file system manager. * @return boolean true if the lock has been acquired or false if not */ public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo, VFSParamDTO paramDTO, FileSystemOptions fso) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); // Lock format random:hostname:hostip:time String strLockValue = String.valueOf(random.nextLong()); try { strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostName(); strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException ue) { if (log.isDebugEnabled()) { log.debug("Unable to get the Hostname or IP."); } } strLockValue += STR_SPLITER + (new Date()).getTime(); byte[] lockValue = strLockValue.getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fo.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } FileObject lockObject = fsManager.resolveFile(fullPath + ".lock", fso); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + maskURLPassword(fo.getName().getURI()) + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); if (paramDTO != null && paramDTO.isAutoLockRelease()) { releaseLock(lockValue, strLockValue, lockObject, paramDTO.isAutoLockReleaseSameNode(), paramDTO.getAutoLockReleaseInterval()); } } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.error( "Couldn't create the lock file before processing the file " + maskURLPassword(fullPath), e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file simultaneously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock", fso); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI()) + " before processing"); } return false; }
From source file:org.apache.synapse.commons.vfs.VFSUtils.java
/** * Release a file item lock acquired either by the VFS listener or a sender * * @param fsManager which is used to resolve the processed file * @param fo representing the processed file * @param fso represents file system options used when resolving file from file system manager. *///from ww w . j a v a2s . c om public static void releaseLock(FileSystemManager fsManager, FileObject fo, FileSystemOptions fso) { String fullPath = fo.getName().getURI(); try { int pos = fullPath.indexOf("?"); if (pos > -1) { fullPath = fullPath.substring(0, pos); } FileObject lockObject = fsManager.resolveFile(fullPath + ".lock", fso); if (lockObject.exists()) { lockObject.delete(); } } catch (FileSystemException e) { log.error("Couldn't release the lock for the file : " + maskURLPassword(fo.getName().getURI()) + " after processing"); } }
From source file:org.apache.synapse.commons.vfs.VFSUtils.java
public synchronized static void markFailRecord(FileSystemManager fsManager, FileObject fo) { // generate a random fail value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] failValue = (Long.toString((new Date()).getTime())).getBytes(); try {//from w w w .j ava 2 s .c o m String fullPath = fo.getName().getURI(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } FileObject failObject = fsManager.resolveFile(fullPath + ".fail"); if (!failObject.exists()) { failObject.createFile(); } // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties OutputStream stream = failObject.getContent().getOutputStream(); try { stream.write(failValue); stream.flush(); stream.close(); } catch (IOException e) { failObject.delete(); log.error("Couldn't create the fail file before processing the file " + maskURLPassword(fullPath), e); } finally { failObject.close(); } } catch (FileSystemException fse) { log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI()) + " before processing"); } }