List of usage examples for org.apache.commons.io FilenameUtils getPath
public static String getPath(String filename)
From source file:org.bdval.MakeSyntheticDataset.java
private void outputTasks(final String outputFilenamePrefix, final int numSamples, final IntSet positiveSampleIndices, final String outputFilename) throws IOException { final String tasksFilename = FilenameUtils.concat(outputDirectory, FilenameUtils.concat("tasks", outputFilename)); FileUtils.forceMkdir(new File(FilenameUtils.getPath(tasksFilename))); PrintWriter tasksWriter = null; try {// w ww .j av a 2s. c om tasksWriter = new PrintWriter(tasksFilename); tasksWriter.println(String.format("%s\tnegative\tpositive\t%d\t%d", outputFilenamePrefix, numSamples - positiveSampleIndices.size(), positiveSampleIndices.size())); } finally { IOUtils.closeQuietly(tasksWriter); } }
From source file:org.bdval.MakeSyntheticDataset.java
private void outputCids(final IntSet positiveSampleIndices, final String outputFilenamePrefix, final IntList sampleIndices) throws IOException { final String cidsFilename = FilenameUtils.concat(outputDirectory, FilenameUtils.concat("cids", outputFilenamePrefix + ".cids")); FileUtils.forceMkdir(new File(FilenameUtils.getPath(cidsFilename))); PrintWriter cidsWriter = null; try {/*from w w w . j av a 2 s. com*/ cidsWriter = new PrintWriter(cidsFilename); for (final int sampleIndex : sampleIndices) { cidsWriter.print(positiveSampleIndices.contains(sampleIndex) ? "positive" : "negative"); cidsWriter.print("\t"); cidsWriter.print(sampleId(sampleIndex, positiveSampleIndices)); cidsWriter.println(); } } finally { IOUtils.closeQuietly(cidsWriter); } }
From source file:org.codice.ddf.spatial.admin.module.service.Geocoding.java
@Override public boolean updateGeoIndexWithUrl(String url, String createIndex) { progress = 0;/* w w w . j av a 2 s .com*/ String countryCode = FilenameUtils.getBaseName(url); url = FilenameUtils.getPath(url); LOGGER.debug("Downloading : {}{}.zip", url, countryCode); LOGGER.debug("Create Index : {}", createIndex); geoEntryExtractor.setUrl(url); return updateIndex(countryCode, createIndex.equals("true")); }
From source file:org.commonwl.view.researchobject.ROBundleFactory.java
/** * Creates a new Workflow Research Object Bundle from Git details * and saves it to a file/* ww w.jav a 2 s. com*/ * @param workflow The workflow to generate a RO bundle for * @throws IOException Any API errors which may have occurred */ @Async public void createWorkflowRO(Workflow workflow) throws IOException, InterruptedException { logger.info("Creating Research Object Bundle"); // Get the whole containing folder, not just the workflow itself GitDetails githubInfo = workflow.getRetrievedFrom(); GitDetails roDetails = new GitDetails(githubInfo.getRepoUrl(), githubInfo.getBranch(), FilenameUtils.getPath(githubInfo.getPath())); // Create a new Research Object Bundle Bundle bundle = roBundleService.createBundle(workflow, roDetails); // Save the bundle to the storage location in properties Path bundleLocation = roBundleService.saveToFile(bundle); // Add RO Bundle to associated workflow model workflow.setRoBundlePath(bundleLocation.toString()); workflowRepository.save(workflow); logger.info("Finished saving Research Object Bundle"); }
From source file:org.commonwl.view.researchobject.ROBundleService.java
/** * Creates a new research object bundle for a workflow from a Git repository * @param workflow The workflow to create the research object for * @return The constructed bundle/*w w w . j a v a2 s .c om*/ */ public Bundle createBundle(Workflow workflow, GitDetails gitInfo) throws IOException { // Create a new RO bundle Bundle bundle = Bundles.createBundle(); Manifest manifest = bundle.getManifest(); // Simplified attribution for RO bundle try { manifest.setId(new URI(workflow.getPermalink())); // Tool attribution in createdBy manifest.setCreatedBy(appAgent); // Retrieval Info // TODO: Make this importedBy/On/From manifest.setRetrievedBy(appAgent); manifest.setRetrievedOn(manifest.getCreatedOn()); manifest.setRetrievedFrom(new URI(workflow.getPermalink(Format.ro))); // Make a directory in the RO bundle to store the files Path bundleRoot = bundle.getRoot(); Path bundlePath = bundleRoot.resolve("workflow"); Files.createDirectory(bundlePath); // Add the files from the repo to this workflow Set<HashableAgent> authors = new HashSet<>(); boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl()); try { Git gitRepo = gitService.getRepository(workflow.getRetrievedFrom(), safeToAccess); Path relativePath = Paths.get(FilenameUtils.getPath(gitInfo.getPath())); Path gitPath = gitRepo.getRepository().getWorkTree().toPath().resolve(relativePath); addFilesToBundle(gitInfo, bundle, bundlePath, gitRepo, gitPath, authors, workflow); } finally { gitSemaphore.release(gitInfo.getRepoUrl()); } // Add combined authors manifest.setAuthoredBy(new ArrayList<>(authors)); // Add visualisation images File png = graphVizService.getGraph(workflow.getID() + ".png", workflow.getVisualisationDot(), "png"); Files.copy(png.toPath(), bundleRoot.resolve("visualisation.png")); PathMetadata pngAggr = bundle.getManifest().getAggregation(bundleRoot.resolve("visualisation.png")); pngAggr.setRetrievedFrom(new URI(workflow.getPermalink(Format.png))); File svg = graphVizService.getGraph(workflow.getID() + ".svg", workflow.getVisualisationDot(), "svg"); Files.copy(svg.toPath(), bundleRoot.resolve("visualisation.svg")); PathMetadata svgAggr = bundle.getManifest().getAggregation(bundleRoot.resolve("visualisation.svg")); svgAggr.setRetrievedFrom(new URI(workflow.getPermalink(Format.svg))); // Add annotation files GitDetails wfDetails = workflow.getRetrievedFrom(); // Get URL to run cwltool String rawUrl = wfDetails.getRawUrl(); String packedWorkflowID = wfDetails.getPackedId(); if (packedWorkflowID != null) { if (packedWorkflowID.charAt(0) != '#') { rawUrl += "#"; } rawUrl += packedWorkflowID; } // Run cwltool for annotations List<PathAnnotation> manifestAnnotations = new ArrayList<>(); try { addAggregation(bundle, manifestAnnotations, "merged.cwl", cwlTool.getPackedVersion(rawUrl)); } catch (CWLValidationException ex) { logger.error("Could not pack workflow when creating Research Object", ex.getMessage()); } String rdfUrl = workflow.getIdentifier(); if (rdfService.graphExists(rdfUrl)) { addAggregation(bundle, manifestAnnotations, "workflow.ttl", new String(rdfService.getModel(rdfUrl, "TURTLE"))); } bundle.getManifest().setAnnotations(manifestAnnotations); // Git2prov history List<Path> history = new ArrayList<>(); // FIXME: Below is a a hack to pretend the URI is a Path String git2prov = "http://git2prov.org/git2prov?giturl=" + gitInfo.getRepoUrl() + "&serialization=PROV-JSON"; Path git2ProvPath = bundle.getRoot().relativize(bundle.getRoot().resolve(git2prov)); history.add(git2ProvPath); bundle.getManifest().setHistory(history); } catch (URISyntaxException ex) { logger.error("Error creating URI for RO Bundle", ex); } catch (GitAPIException ex) { logger.error("Error getting repository to create RO Bundle", ex); } // Return the completed bundle return bundle; }
From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java
@Override public DavResource getCollection() { if (locator.isRootLocation()) { return null; }// w ww . ja va2 s. c o m final String parentResource = FilenameUtils.getPath(locator.getResourcePath()); final DavResourceLocator parentLocator = locator.getFactory().createResourceLocator(locator.getPrefix(), locator.getWorkspacePath(), parentResource); try { return getFactory().createResource(parentLocator, session); } catch (DavException e) { throw new IllegalStateException( "Unable to get parent resource with path " + parentLocator.getResourcePath(), e); } }
From source file:org.csc.phynixx.common.TmpDirectory.java
public File assertExitsFile(String filename) throws IOException { File parentDir = this.assertExitsDirectory(FilenameUtils.getPath(filename)); String name = FilenameUtils.getName(filename); String fullname = FilenameUtils.normalize(parentDir.getAbsolutePath() + File.separator + name); File file = new File(fullname); if (!file.createNewFile()) { file.delete();/* w w w . j a v a2s .c o m*/ file.createNewFile(); } return file; }
From source file:org.dita.dost.module.BranchFilterModule.java
private void processAttributes(final Element elem, final Branch filter) { if (filter.resourcePrefix.isPresent() || filter.resourceSuffix.isPresent()) { final String href = elem.getAttribute(ATTRIBUTE_NAME_HREF); final String copyTo = elem.getAttribute(ATTRIBUTE_NAME_COPY_TO); final String scope = elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if ((!href.isEmpty() || !copyTo.isEmpty()) && !scope.equals(ATTR_SCOPE_VALUE_EXTERNAL)) { final FileInfo hrefFileInfo = job.getFileInfo(currentFile.resolve(href)); final FileInfo copyToFileInfo = !copyTo.isEmpty() ? job.getFileInfo(currentFile.resolve(copyTo)) : null;/*w w w . j a v a 2s.c o m*/ final URI dstSource; dstSource = generateCopyTo((copyToFileInfo != null ? copyToFileInfo : hrefFileInfo).result, filter); final URI dstTemp = tempFileNameScheme.generateTempFileName(dstSource); final String dstPathFromMap = !copyTo.isEmpty() ? FilenameUtils.getPath(copyTo) : FilenameUtils.getPath(href); final FileInfo.Builder dstBuilder = new FileInfo.Builder(hrefFileInfo).result(dstSource) .uri(dstTemp); if (dstBuilder.build().format == null) { dstBuilder.format(ATTR_FORMAT_VALUE_DITA); } if (hrefFileInfo.src == null && href != null) { if (copyToFileInfo != null) { dstBuilder.src(copyToFileInfo.src); } } final FileInfo dstFileInfo = dstBuilder.build(); elem.setAttribute(BRANCH_COPY_TO, dstPathFromMap + FilenameUtils.getName(dstTemp.toString())); if (!copyTo.isEmpty()) { elem.removeAttribute(ATTRIBUTE_NAME_COPY_TO); } job.add(dstFileInfo); } } if (filter.keyscopePrefix.isPresent() || filter.keyscopeSuffix.isPresent()) { final StringBuilder buf = new StringBuilder(); final String keyscope = elem.getAttribute(ATTRIBUTE_NAME_KEYSCOPE); if (!keyscope.isEmpty()) { for (final String key : keyscope.trim().split("\\s+")) { filter.keyscopePrefix.ifPresent(buf::append); buf.append(key); filter.keyscopeSuffix.ifPresent(buf::append); buf.append(' '); } } else { filter.keyscopePrefix.ifPresent(buf::append); filter.keyscopeSuffix.ifPresent(buf::append); } elem.setAttribute(ATTRIBUTE_NAME_KEYSCOPE, buf.toString().trim()); } }
From source file:org.eclipse.smarthome.core.transform.AbstractFileTransformationService.java
/** * Returns the name of the localized transformation file * if it actually exists, keeps the original in the other case * * @param filename name of the requested transformation file * @return original or localized transformation file to use */// ww w .j ava 2s. co m protected String getLocalizedProposedFilename(String filename) { String extension = FilenameUtils.getExtension(filename); String prefix = FilenameUtils.getPath(filename); String result = filename; if (!prefix.isEmpty()) { watchSubDirectory(prefix); } // the filename may already contain locale information if (!filename.matches(".*_[a-z]{2}." + extension + "$")) { String basename = FilenameUtils.getBaseName(filename); String alternateName = prefix + basename + "_" + getLocale().getLanguage() + "." + extension; String alternatePath = getSourcePath() + alternateName; File f = new File(alternatePath); if (f.exists()) { result = alternateName; } } result = getSourcePath() + result; return result; }
From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentUninstaller.java
@Override public boolean uninstallComponent(Component component) throws ApsSystemException { ServletContext servletContext = ((ConfigurableWebApplicationContext) _applicationContext) .getServletContext();//from ww w. ja v a2s . co m ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader"); List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext .getAttribute("pluginsContextsList"); ClassPathXmlApplicationContext appCtx = null; if (ctxList != null) { for (ClassPathXmlApplicationContext ctx : ctxList) { if (component.getCode().equals(ctx.getDisplayName())) { appCtx = ctx; } } } String appRootPath = servletContext.getRealPath("/"); String backupDirPath = appRootPath + "componentinstaller" + File.separator + component.getArtifactId() + "-backup"; Map<File, File> resourcesMap = new HashMap<File, File>(); try { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { if (cl != null) { Thread.currentThread().setContextClassLoader(cl); } if (null == component || null == component.getUninstallerInfo()) { return false; } this.getDatabaseManager().createBackup();//backup database SystemInstallationReport report = super.extractReport(); ComponentUninstallerInfo ui = component.getUninstallerInfo(); //remove records from db String[] dataSourceNames = this.extractBeanNames(DataSource.class); for (int j = 0; j < dataSourceNames.length; j++) { String dataSourceName = dataSourceNames[j]; Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null; String script = (null != resource) ? this.readFile(resource) : null; if (null != script && script.trim().length() > 0) { DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName); String[] queries = QueryExtractor.extractDeleteQueries(script); TableDataUtils.executeQueries(dataSource, queries, true); } } this.executePostProcesses(ui.getPostProcesses()); //drop tables Map<String, List<String>> tableMapping = component.getTableMapping(); if (tableMapping != null) { for (int j = 0; j < dataSourceNames.length; j++) { String dataSourceName = dataSourceNames[j]; List<String> tableClasses = tableMapping.get(dataSourceName); if (null != tableClasses && tableClasses.size() > 0) { List<String> newList = new ArrayList<String>(); newList.addAll(tableClasses); Collections.reverse(newList); DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName); IDatabaseManager.DatabaseType type = this.getDatabaseManager() .getDatabaseType(dataSource); TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type); tableFactory.dropTables(newList); } } } //move resources (jar, files and folders) on temp folder List<String> resourcesPaths = ui.getResourcesPaths(); if (resourcesPaths != null) { for (String resourcePath : resourcesPaths) { try { String fullResourcePath = servletContext.getRealPath(resourcePath); File resFile = new File(fullResourcePath); String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath()); File newResFile = new File( backupDirPath + File.separator + relResPath + resFile.getName()); if (resFile.isDirectory()) { FileUtils.copyDirectory(resFile, newResFile); resourcesMap.put(resFile, newResFile); FileUtils.deleteDirectory(resFile); } else { FileUtils.copyFile(resFile, newResFile); resourcesMap.put(resFile, newResFile); FileUtils.forceDelete(resFile); } } catch (Exception e) { } } } //upgrade report ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true); cir.getDataSourceReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED); cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED); this.saveReport(report); //remove plugin's xmlapplicationcontext if present if (appCtx != null) { appCtx.close(); ctxList.remove(appCtx); } InitializerManager initializerManager = (InitializerManager) _applicationContext .getBean("InitializerManager"); initializerManager.reloadCurrentReport(); ComponentManager componentManager = (ComponentManager) _applicationContext .getBean("ComponentManager"); componentManager.refresh(); } catch (Exception e) { _logger.error("Unexpected error in component uninstallation process", e); throw new ApsSystemException("Unexpected error in component uninstallation process.", e); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); ApsWebApplicationUtils.executeSystemRefresh(servletContext); } } catch (Throwable t) { //restore files on temp folder try { for (Object object : resourcesMap.entrySet()) { File resFile = ((Map.Entry<File, File>) object).getKey(); File newResFile = ((Map.Entry<File, File>) object).getValue(); if (newResFile.isDirectory()) { FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile()); } else { FileUtils.copyFile(newResFile, resFile.getParentFile()); } } } catch (Exception e) { } _logger.error("Unexpected error in component uninstallation process", t); throw new ApsSystemException("Unexpected error in component uninstallation process.", t); } finally { //clean temp folder } return true; }