List of usage examples for java.io File getAbsoluteFile
public File getAbsoluteFile()
From source file:com.streamsets.datacollector.io.DataStore.java
public DataStore(File file) { Utils.checkNotNull(file, "file"); File absFile = file.getAbsoluteFile(); this.file = absFile.toPath(); fileTmp = new File(absFile.getAbsolutePath() + "-tmp").toPath(); fileNew = new File(absFile.getAbsolutePath() + "-new").toPath(); fileOld = new File(absFile.getAbsolutePath() + "-old").toPath(); LOG.trace("Create DataStore for '{}'", file); }
From source file:esiptestbed.mudrod.metadata.pre.ApiHarvester.java
/** * harvestMetadatafromWeb: Harvest metadata from PO.DAAC web service. *///from w w w .j a v a 2 s. co m private void harvestMetadatafromWeb() { int startIndex = 0; int doc_length = 0; JsonParser parser = new JsonParser(); do { String searchAPI = "https://podaac.jpl.nasa.gov/api/dataset?startIndex=" + Integer.toString(startIndex) + "&entries=10&sortField=Dataset-AllTimePopularity&sortOrder=asc&id=&value=&search="; HttpRequest http = new HttpRequest(); String response = http.getRequest(searchAPI); JsonElement json = parser.parse(response); JsonObject responseObject = json.getAsJsonObject(); JsonArray docs = responseObject.getAsJsonObject("response").getAsJsonArray("docs"); doc_length = docs.size(); File file = new File(props.getProperty(MudrodConstants.RAW_METADATA_PATH)); if (!file.exists()) { if (file.mkdir()) { LOG.info("Directory is created!"); } else { LOG.error("Failed to create directory!"); } } for (int i = 0; i < doc_length; i++) { JsonElement item = docs.get(i); int docId = startIndex + i; File itemfile = new File( props.getProperty(MudrodConstants.RAW_METADATA_PATH) + "/" + docId + ".json"); try (FileWriter fw = new FileWriter(itemfile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw);) { itemfile.createNewFile(); bw.write(item.toString()); } catch (IOException e) { LOG.error("Error writing metadata to local file!", e); } } startIndex += 10; try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error("Error entering Elasticsearch Mappings!", e); Thread.currentThread().interrupt(); } } while (doc_length != 0); }
From source file:io.cloudslang.lang.tools.build.validation.StaticValidatorImpl.java
private void validateNamespace(File slangFile, Executable executable, Queue<RuntimeException> exceptions) { // Validate that the namespace is not empty String namespace = executable.getNamespace(); addExceptionIfEmptyString(namespace, "Error validating Slang file: \'" + slangFile.getAbsoluteFile() + "\'. Namespace of slang source: \'" + executable.getName() + "\' cannot be empty.", exceptions);//from w ww .j a v a 2s . co m // Validate that the namespace matches the path of the file String executableNamespacePath = namespace.replace('.', File.separatorChar); String namespaceErrorMessage = "Error validating Slang file: \'" + slangFile.getAbsoluteFile() + "\'. Namespace of slang source: " + executable.getName() + " is wrong.\nIt is currently \'" + namespace + "\', but it should match the file path: \'" + slangFile.getPath() + "\'"; String filePathWithoutFileName = slangFile.getParent(); addExceptionIfTrue(endsWithIgnoreCase(filePathWithoutFileName, executableNamespacePath), namespaceErrorMessage, exceptions); // Validate that the namespace is composed only of abc letters, _ or - Matcher matcher = PATTERN.matcher(namespace); addExceptionIfTrue(matcher.matches(), "Namespace: " + namespace + " is invalid. It can contain only " + "alphanumeric characters, underscore or hyphen", exceptions); }
From source file:gov.nasa.jpl.mudrod.metadata.pre.ApiHarvester.java
/** * harvestMetadatafromWeb: Harvest metadata from PO.DAAC web service. *///from ww w . ja v a 2s .c o m private void harvestMetadatafromWeb() { LOG.info("Metadata download started."); int startIndex = 0; int doc_length = 0; JsonParser parser = new JsonParser(); do { String searchAPI = "https://podaac.jpl.nasa.gov/api/dataset?startIndex=" + Integer.toString(startIndex) + "&entries=10&sortField=Dataset-AllTimePopularity&sortOrder=asc&id=&value=&search="; HttpRequest http = new HttpRequest(); String response = http.getRequest(searchAPI); JsonElement json = parser.parse(response); JsonObject responseObject = json.getAsJsonObject(); JsonArray docs = responseObject.getAsJsonObject("response").getAsJsonArray("docs"); doc_length = docs.size(); File file = new File(props.getProperty(MudrodConstants.RAW_METADATA_PATH)); if (!file.exists()) { if (file.mkdir()) { LOG.info("Directory is created!"); } else { LOG.error("Failed to create directory!"); } } for (int i = 0; i < doc_length; i++) { JsonElement item = docs.get(i); int docId = startIndex + i; File itemfile = new File( props.getProperty(MudrodConstants.RAW_METADATA_PATH) + "/" + docId + ".json"); try (FileWriter fw = new FileWriter(itemfile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw);) { itemfile.createNewFile(); bw.write(item.toString()); } catch (IOException e) { LOG.error("Error writing metadata to local file!", e); } } startIndex += 10; try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error("Error entering Elasticsearch Mappings!", e); Thread.currentThread().interrupt(); } } while (doc_length != 0); LOG.info("Metadata downloading finished"); }
From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java
private static void initClasspath() { List<String> classpathSimpleTmp = new ArrayList<String>(); List<String> classpathUnpackedTmp = new ArrayList<String>(); try {/* w w w .ja v a 2s . co m*/ List<File> classpathElements = new FastClasspathScanner().getUniqueClasspathElements(); final File classpathDir = Files.createTempDirectory("jbd_classpath_").toFile(); Runtime.getRuntime().addShutdownHook(new FileRemover(classpathDir)); List<String> pathsSimple = new ArrayList<String>(); List<String> pathsUnpacked = new ArrayList<String>(); for (File curElement : classpathElements) { String rootLevelElement = curElement.getAbsoluteFile().toURI().toURL().toExternalForm(); pathsSimple.add(rootLevelElement); pathsUnpacked.add(rootLevelElement); if (curElement.isFile() && curElement.getPath().endsWith(".jar")) { try (ZipFile jar = new ZipFile(curElement)) { Enumeration<? extends ZipEntry> entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith(".jar")) { try (InputStream in = jar.getInputStream(entry)) { File childJar = new File(classpathDir, Util.randomFileName() + ".jar"); Files.copy(in, childJar.toPath()); pathsUnpacked.add(childJar.getAbsoluteFile().toURI().toURL().toExternalForm()); childJar.deleteOnExit(); } } } } } } classpathSimpleTmp = createClasspathJar(classpathDir, "classpath-simple.jar", pathsSimple); classpathUnpackedTmp = createClasspathJar(classpathDir, "classpath-unpacked.jar", pathsUnpacked); } catch (Throwable t) { Util.handleException(t); } classpathSimpleArgs = Collections.unmodifiableList(classpathSimpleTmp); classpathUnpackedArgs = Collections.unmodifiableList(classpathUnpackedTmp); }
From source file:com.limegroup.gnutella.licenses.PublishedCCLicenseTest.java
/** * Tests that the verification RDF validates * against a RELAX-NG Schema/*from w w w. jav a 2 s . com*/ */ public void testVerifyRDFValidates() throws Exception { String rdfEmbeddedComment = PublishedCCLicense.getRDFRepresentation("TIMMAY", "TIMMAY SLEEPAY", "2005", "Timmay Drink Espresso", "urn:sha1:TIMMAYESPRESSOH32VV4A2LJUDNLPAJ6", CCConstants.ATTRIBUTION_SHARE_NON_COMMERCIAL); // first extract the RDF out of the html comment StringReader reader = new StringReader(rdfEmbeddedComment); HTMLEditorKit.ParserCallback callback = new CommentExtractor(); getHTMLEditorKitParser().parse(reader, callback, true); synchronized (rdfLock) { // wait for parser to finish while (rdf == null) { try { rdfLock.wait(); } catch (InterruptedException e) { } } } // now let's parse the RDF and validate it against the schema // set up ManekiNeko parser SAXParser parser = new SAXParser(); parser.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { LOG.error("error in sax", exception); } public void fatalError(SAXParseException exception) throws SAXException { LOG.fatal("error in sax", exception); throw exception; } public void warning(SAXParseException exception) throws SAXException { LOG.warn("error in sax", exception); } }); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://xml.org/sax/features/validation", true); // bug in MinekiNeko prevents use of compact schema. use regular schema instead // parser.setFeature("http://cyberneko.org/xml/features/relaxng/compact-syntax", true); File f = TestUtils.getResourceFile("com/limegroup/gnutella/licenses/ccverificationrdf-schema.rng"); assertTrue(f.exists()); // must have rng to validate. parser.setProperty("http://cyberneko.org/xml/properties/relaxng/schema-location", f.getAbsoluteFile().toURI()); parser.parse(new InputSource(new StringReader(rdf))); }
From source file:net.sf.firemox.tools.MToolKit.java
/** * Return the File associated to the given fileName. * //from w w w.j a v a 2s .co m * @param fileName * the file name path to search. * @param mustExist * <code>true</code> if the resource to search must exists, * <code>false</code> either * @return the File associated to the given fileName. */ public static File getFile(String fileName, boolean mustExist) { final File simpleFile = new File(fileName); if (simpleFile.exists()) { return simpleFile.getAbsoluteFile(); } String file = fileName; if (file.startsWith("/")) { file = file.substring(1); } final File f = new File(getRootDir() + file); if (!f.exists() && mustExist) { return null; } return f; }
From source file:io.cloudslang.lang.tools.build.verifier.SlangContentVerifier.java
public PreCompileResult createModelsAndValidate(String directoryPath, boolean shouldValidateDescription, boolean shouldValidateCheckstyle) { Validate.notEmpty(directoryPath, "You must specify a path"); Validate.isTrue(new File(directoryPath).isDirectory(), "Directory path argument \'" + directoryPath + "\' does not lead to a directory"); Map<String, Executable> slangModels = new HashMap<>(); Collection<File> slangFiles = slangCompilationService.listSlangFiles(new File(directoryPath), true); loggingService.logEvent(Level.INFO, "Start compiling all slang files under: " + directoryPath); loggingService.logEvent(Level.INFO, slangFiles.size() + " .sl files were found"); loggingService.logEvent(Level.INFO, ""); Queue<RuntimeException> exceptions = new ArrayDeque<>(); String errorMessagePrefixMetadata = ""; for (File slangFile : slangFiles) { Executable sourceModel = null; try {/*from w w w . j ava 2 s. c o m*/ errorMessagePrefixMetadata = "Failed to extract metadata for file: \'" + slangFile.getAbsoluteFile() + "\'.\n"; String errorMessagePrefixCompilation = "Failed to compile file: \'" + slangFile.getAbsoluteFile() + "\'.\n"; Validate.isTrue(slangFile.isFile(), "file path \'" + slangFile.getAbsolutePath() + "\' must lead to a file"); SlangSource slangSource = SlangSource.fromFile(slangFile); ExecutableModellingResult preCompileResult = slangCompiler.preCompileSource(slangSource); sourceModel = preCompileResult.getExecutable(); exceptions.addAll(prependPrefix(preCompileResult.getErrors(), errorMessagePrefixCompilation)); MetadataModellingResult metadataResult = metadataExtractor .extractMetadataModellingResult(slangSource, shouldValidateCheckstyle); Metadata sourceMetadata = metadataResult.getMetadata(); exceptions.addAll(prependPrefix(metadataResult.getErrors(), errorMessagePrefixMetadata)); if (sourceModel != null) { int size = exceptions.size(); staticValidator.validateSlangFile(slangFile, sourceModel, sourceMetadata, shouldValidateDescription, exceptions); if (size == exceptions.size()) { slangModels.put(getUniqueName(sourceModel), sourceModel); } } } catch (Exception e) { String errorMessage = errorMessagePrefixMetadata + e.getMessage(); loggingService.logEvent(Level.ERROR, errorMessage); exceptions.add(new RuntimeException(errorMessage, e)); if (e instanceof MetadataMissingException && sourceModel != null) { slangModels.put(getUniqueName(sourceModel), sourceModel); } } } if (slangFiles.size() != slangModels.size()) { exceptions.add(new RuntimeException("Some Slang files were not pre-compiled.\nFound: " + slangFiles.size() + " executable files in path: \'" + directoryPath + "\' But managed to create slang models for only: " + slangModels.size())); } PreCompileResult preCompileResult = new PreCompileResult(); preCompileResult.addExceptions(exceptions); preCompileResult.addResults(slangModels); return preCompileResult; }
From source file:inventory.pl.services.BackupService.java
public void restore(String source, String outputFolder) { byte[] buffer = new byte[1024]; try {//from w w w . j a v a2 s . c om //create output directory is not exists File folder = new File(outputFolder); if (!folder.exists()) { folder.mkdir(); } //get the zip file content SevenZFile sevenZFile = new SevenZFile(new File(source)); //get the zipped file list entry SevenZArchiveEntry ze = sevenZFile.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); System.out.println("file unzip : " + newFile.getAbsoluteFile()); //create all non exists folders //else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = sevenZFile.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = sevenZFile.getNextEntry(); } sevenZFile.close(); System.out.println("Done"); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:io.cloudslang.lang.tools.build.validation.StaticValidatorImpl.java
private void validateExecutableName(File slangFile, Executable executable, Queue<RuntimeException> exceptions) { // Validate executable name is the same as the file name String fileNameNoExtension = Extension.removeExtension(slangFile.getName()); String executableNameErrorMessage = "Error validating Slang file: \'" + slangFile.getAbsoluteFile() + "\'. Name of flow or operation: \'" + executable.getName() + "\' is not valid.\nIt should be identical to the file name: \'" + fileNameNoExtension + "\'"; addExceptionIfTrue(fileNameNoExtension.equals(executable.getName()), executableNameErrorMessage, exceptions);// www . j a va 2 s . co m }