List of usage examples for java.nio.file Path toUri
URI toUri();
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.tasks.APIUsageFileUploadTask.java
@Override public void execute() { log.info("Running API Usage File Upload Task."); try {//from w w w . jav a 2s . c om configManager = ConfigManager.getConfigManager(); } catch (OnPremiseGatewayException e) { log.error("Error occurred while reading the configuration. Usage upload was cancelled.", e); return; } //[CARBON_HOME]/api-usage-data/ Path usageFileDirectory = Paths.get(CarbonUtils.getCarbonHome(), MicroGatewayAPIUsageConstants.API_USAGE_OUTPUT_DIRECTORY); //Rotate current file Path activeFilePath = Paths.get(usageFileDirectory.toString(), MicroGatewayAPIUsageConstants.API_USAGE_OUTPUT_FILE_NAME); try { if (Files.size(activeFilePath) > 0) { //Don't rotate if the current file is empty if (log.isDebugEnabled()) { log.debug("Rotating current file for uploading."); } UsageFileWriter.getInstance().rotateFile(activeFilePath.toString()); } } catch (UsagePublisherException | IOException e) { log.error("Error occurred while rotating the current file. Will only upload the previously " + "rotated files."); } File[] listOfFiles = new File(usageFileDirectory.toUri()).listFiles(); if (listOfFiles != null) { Arrays.sort(listOfFiles); for (File file : listOfFiles) { String fileName = file.getName(); //Only get the files which have been rotated if (fileName.endsWith(MicroGatewayAPIUsageConstants.ZIP_EXTENSION)) { try { boolean uploadStatus = uploadCompressedFile(file.toPath(), fileName); if (uploadStatus) { //Rename the file to mark as uploaded Path renamedPath = Paths.get( file.getAbsolutePath() + MicroGatewayAPIUsageConstants.UPLOADED_FILE_SUFFIX); Files.move(file.toPath(), renamedPath); } else { log.error("Usage file Upload failed. It will be retried in the next task run."); } } catch (IOException e) { log.error("Error occurred while moving the uploaded the File : " + fileName, e); } } } } }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void resolvePaths() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path list = DataBundles.getPort(inputs, "in1"); DataBundles.createList(list);/*w w w . j a va 2 s . c om*/ // 0 string value Path test0 = DataBundles.newListItem(list); DataBundles.setStringValue(test0, "test0"); // 1 http:// reference URI reference = URI.create("http://example.com/"); Path test1 = DataBundles.setReference(DataBundles.newListItem(list), reference); // 2 file:/// reference Path tmpFile = Files.createTempFile("test", ".txt"); URI fileRef = tmpFile.toUri(); assertEquals("file", fileRef.getScheme()); Path test2 = DataBundles.setReference(DataBundles.newListItem(list), fileRef); // 3 empty (null) // 4 error Path error4 = DataBundles.setError(DataBundles.getListItem(list, 4), "Example error", "1. Tried it\n2. Didn't work"); List<Path> resolved = (List<Path>) DataBundles.resolve(list, ResolveOptions.PATH); assertEquals(test0, resolved.get(0)); assertEquals(test1, resolved.get(1)); assertEquals(test2, resolved.get(2)); assertNull(resolved.get(3)); assertEquals(error4, resolved.get(4)); }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void resolveURIs() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path list = DataBundles.getPort(inputs, "in1"); DataBundles.createList(list);/*from w w w.j av a 2 s. co m*/ // 0 string value Path test0 = DataBundles.newListItem(list); DataBundles.setStringValue(test0, "test0"); // 1 http:// reference URI reference = URI.create("http://example.com/"); DataBundles.setReference(DataBundles.newListItem(list), reference); // 2 file:/// reference Path tmpFile = Files.createTempFile("test", ".txt"); URI fileRef = tmpFile.toUri(); assertEquals("file", fileRef.getScheme()); DataBundles.setReference(DataBundles.newListItem(list), fileRef); // 3 empty (null) // 4 error Path error4 = DataBundles.getListItem(list, 4); DataBundles.setError(error4, "Example error", "1. Tried it\n2. Didn't work"); List resolved = (List) DataBundles.resolve(list, ResolveOptions.URI); assertEquals(test0.toUri(), resolved.get(0)); assertEquals(reference, resolved.get(1)); assertEquals(fileRef, resolved.get(2)); assertNull(resolved.get(3)); // NOTE: Need to get the Path again due to different file extension assertTrue(resolved.get(4) instanceof ErrorDocument); //assertTrue(DataBundles.getListItem(list, 4).toUri(), resolved.get(4)); }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void resolveDefault() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path list = DataBundles.getPort(inputs, "in1"); DataBundles.createList(list);//from ww w . j a va 2 s .c o m // 0 string value Path test0 = DataBundles.newListItem(list); DataBundles.setStringValue(test0, "test0"); // 1 http:// reference URI reference = URI.create("http://example.com/"); Path test1 = DataBundles.setReference(DataBundles.newListItem(list), reference); // 2 file:/// reference Path tmpFile = Files.createTempFile("test", ".txt"); URI fileRef = tmpFile.toUri(); assertEquals("file", fileRef.getScheme()); Path test2 = DataBundles.setReference(DataBundles.newListItem(list), fileRef); // 3 empty (null) // 4 error Path error4 = DataBundles.setError(DataBundles.getListItem(list, 4), "Example error", "1. Tried it\n2. Didn't work"); List resolved = (List) DataBundles.resolve(list, ResolveOptions.DEFAULT); assertEquals(test0, resolved.get(0)); assertTrue(resolved.get(1) instanceof URL); assertEquals("http://example.com/", resolved.get(1).toString()); assertTrue(resolved.get(2) instanceof File); assertEquals(tmpFile.toFile(), resolved.get(2)); assertNull(resolved.get(3)); assertTrue(resolved.get(4) instanceof ErrorDocument); }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void resolveString() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path list = DataBundles.getPort(inputs, "in1"); DataBundles.createList(list);/* w ww. j a v a 2s . c om*/ // 0 string value DataBundles.setStringValue(DataBundles.newListItem(list), "test0"); // 1 http:// reference URI reference = URI.create("http://example.com/"); DataBundles.setReference(DataBundles.newListItem(list), reference); // 2 file:/// reference Path tmpFile = Files.createTempFile("test", ".txt"); URI fileRef = tmpFile.toUri(); assertEquals("file", fileRef.getScheme()); DataBundles.setReference(DataBundles.newListItem(list), fileRef); // 3 empty (null) // 4 error DataBundles.setError(DataBundles.getListItem(list, 4), "Example error", "1. Tried it\n2. Didn't work"); Object resolved = DataBundles.resolve(list, ResolveOptions.STRING); assertTrue("Didn't resolve to a list", resolved instanceof List); List resolvedList = (List) resolved; assertEquals("Unexpected list size", 5, resolvedList.size()); assertTrue(resolvedList.get(0) instanceof String); assertEquals("test0", resolvedList.get(0)); assertTrue(resolvedList.get(1) instanceof URL); assertEquals(reference, ((URL) resolvedList.get(1)).toURI()); assertTrue(resolvedList.get(2) instanceof File); assertEquals(tmpFile.toFile(), resolvedList.get(2)); assertNull(resolvedList.get(3)); assertTrue(resolvedList.get(4) instanceof ErrorDocument); assertEquals("Example error", ((ErrorDocument) resolvedList.get(4)).getMessage()); }
From source file:org.apache.openaz.xacml.std.pap.StdPDPGroup.java
private void readPolicyProperties(Path directory, Properties properties) { ////www. j a v a 2 s . c o m // There are 2 property values that hold policies, root and referenced // String[] lists = new String[2]; lists[0] = properties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); lists[1] = properties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); // // Iterate each policy list // boolean isRoot = true; for (String list : lists) { // // Was there actually a property? // if (list == null || list.length() == 0) { isRoot = false; continue; } // // Parse it out // Iterable<String> policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list); // // Was there actually a list // if (policyList == null) { isRoot = false; continue; } for (String id : policyList) { // // Construct the policy filename // Path policyPath = Paths.get(directory.toString(), id); // // Create the Policy Object // StdPDPPolicy policy; try { policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties); } catch (IOException e) { logger.error("Failed to create policy object", e); policy = null; } // // Is it valid? // if (policy != null && policy.isValid()) { this.policies.add(policy); this.status.addLoadedPolicy(policy); } else { this.status.addFailedPolicy(policy); this.status.setStatus(Status.LOAD_ERRORS); } // force all policies to have a name if (policy.getName() == null) { policy.setName(policy.getId()); } } isRoot = false; } }
From source file:org.apache.archiva.admin.mock.ArchivaIndexManagerMock.java
private IndexingContext createManagedContext(ManagedRepository repository) throws IOException { IndexingContext context;/*w w w.j ava 2 s.c om*/ // take care first about repository location as can be relative Path repositoryDirectory = repository.getLocalPath(); if (!Files.exists(repositoryDirectory)) { try { Files.createDirectories(repositoryDirectory); } catch (IOException e) { log.error("Could not create directory {}", repositoryDirectory); } } Path indexDirectory = null; if (repository.supportsFeature(IndexCreationFeature.class)) { indexDirectory = getIndexPath(repository); String indexUrl = repositoryDirectory.toUri().toURL().toExternalForm(); try { context = getIndexingContext(repository, repository.getId(), repositoryDirectory, indexDirectory, indexUrl); context.setSearchable(repository.isScanned()); } catch (IndexFormatTooOldException e) { // existing index with an old lucene format so we need to delete it!!! // delete it first then recreate it. log.warn("the index of repository {} is too old we have to delete and recreate it", // repository.getId()); org.apache.archiva.common.utils.FileUtils.deleteDirectory(indexDirectory); context = getIndexingContext(repository, repository.getId(), repositoryDirectory, indexDirectory, indexUrl); context.setSearchable(repository.isScanned()); } return context; } else { throw new IOException("No repository index defined"); } }
From source file:eu.esdihumboldt.hale.common.core.io.project.impl.ArchiveProjectWriter.java
/** * Update the resources and copy them into the target directory * /*w w w . ja v a 2 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:ru.histone.staticrender.StaticRender.java
public void renderSite(final Path srcDir, final Path dstDir) { log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString()); Path contentDir = srcDir.resolve("content/"); final Path layoutDir = srcDir.resolve("layouts/"); FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() { @Override//w w w . java 2 s . co m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) { ArrayNode ast = null; try { ast = histone.parseTemplateToAST(new FileReader(file.toFile())); } catch (HistoneException e) { throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e); } final String fileName = file.getFileName().toString(); String layoutId = fileName.substring(0, fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1); layouts.put(layoutId, ast); if (log.isDebugEnabled()) { log.debug("Layout found id='{}', file={}", layoutId, file); } else { log.info("Layout found id='{}'", layoutId); } } else { final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri())); final Path resolvedFile = dstDir.resolve(relativeFileName); if (!resolvedFile.getParent().toFile().exists()) { Files.createDirectories(resolvedFile.getParent()); } Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING, LinkOption.NOFOLLOW_LINKS); } return FileVisitResult.CONTINUE; } }; FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Scanner scanner = new Scanner(file, "UTF-8"); scanner.useDelimiter("-----"); String meta = null; StringBuilder content = new StringBuilder(); if (!scanner.hasNext()) { throw new RuntimeException("Wrong format #1:" + file.toString()); } if (scanner.hasNext()) { meta = scanner.next(); } if (scanner.hasNext()) { content.append(scanner.next()); scanner.useDelimiter("\n"); } while (scanner.hasNext()) { final String next = scanner.next(); content.append(next); if (scanner.hasNext()) { content.append("\n"); } } Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta); String layoutId = metaYaml.get("layout"); if (!layouts.containsKey(layoutId)) { throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId)); } final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri())); final Path resolvedFile = dstDir.resolve(relativeFileName); if (!resolvedFile.getParent().toFile().exists()) { Files.createDirectories(resolvedFile.getParent()); } Writer output = new FileWriter(resolvedFile.toFile()); ObjectNode context = jackson.createObjectNode(); ObjectNode metaNode = jackson.createObjectNode(); context.put("content", content.toString()); context.put("meta", metaNode); for (String key : metaYaml.keySet()) { if (!key.equalsIgnoreCase("content")) { metaNode.put(key, metaYaml.get(key)); } } try { histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output); output.flush(); } catch (HistoneException e) { throw new RuntimeException("Error evaluating content: " + e.getMessage(), e); } finally { output.close(); } return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(layoutDir, layoutVisitor); Files.walkFileTree(contentDir, contentVisitor); } catch (Exception e) { throw new RuntimeException("Error during site render", e); } }