org.apache.commons.io.FileUtils Java Examples
The following examples show how to use
org.apache.commons.io.FileUtils.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CasMergeSuiteTest.java From webanno with Apache License 2.0 | 8 votes |
private void writeAndAssertEquals(JCas curatorCas) throws Exception { String targetFolder = "target/test-output/" + testContext.getClassName() + "/" + referenceFolder.getName(); DocumentMetaData dmd = DocumentMetaData.get(curatorCas); dmd.setDocumentId("curator"); runPipeline(curatorCas, createEngineDescription(WebannoTsv3XWriter.class, WebannoTsv3XWriter.PARAM_TARGET_LOCATION, targetFolder, WebannoTsv3XWriter.PARAM_OVERWRITE, true)); File referenceFile = new File(referenceFolder, "curator.tsv"); assumeTrue("No reference data available for this test.", referenceFile.exists()); File actualFile = new File(targetFolder, "curator.tsv"); String reference = FileUtils.readFileToString(referenceFile, "UTF-8"); String actual = FileUtils.readFileToString(actualFile, "UTF-8"); assertEquals(reference, actual); }
Example #2
Source File: FileDeleteServletTest.java From selenium-grid-extensions with Apache License 2.0 | 6 votes |
@Test public void getShouldDeleteFile() throws IOException { File fileTobeDeleted = File.createTempFile("testDeleteFile", ".txt"); FileUtils.write(fileTobeDeleted, "file_to_be_deleted_content", StandardCharsets.UTF_8); CloseableHttpClient httpClient = HttpClients.createDefault(); String encode = Base64.getUrlEncoder().encodeToString(fileTobeDeleted.getAbsolutePath().getBytes(StandardCharsets.UTF_8)); HttpGet httpGet = new HttpGet("/FileDeleteServlet/" + encode); CloseableHttpResponse execute = httpClient.execute(serverHost, httpGet); //check file got deleted //Assert.assertFalse(fileTobeDeleted.getAbsolutePath()+" File should have been deleted ",fileTobeDeleted.exists()); assertThat(fileTobeDeleted+" File should have been deleted . It should not exist at this point",fileTobeDeleted.exists(), is(false)); }
Example #3
Source File: IOUtils.java From gatk with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Writes the an embedded resource to a file. * File is not scheduled for deletion and must be cleaned up by the caller. * @param resource Embedded resource. * @param file File path to write. */ @SuppressWarnings("deprecation") public static void writeResource(Resource resource, File file) { String path = resource.getPath(); InputStream inputStream = resource.getResourceContentsAsStream(); OutputStream outputStream = null; try { outputStream = FileUtils.openOutputStream(file); org.apache.commons.io.IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new GATKException(String.format("Unable to copy resource '%s' to '%s'", path, file), e); } finally { org.apache.commons.io.IOUtils.closeQuietly(inputStream); org.apache.commons.io.IOUtils.closeQuietly(outputStream); } }
Example #4
Source File: PingRequestHandlerTest.java From lucene-solr with Apache License 2.0 | 6 votes |
@Before @SuppressWarnings({"unchecked"}) public void before() throws IOException { // by default, use relative file in dataDir healthcheckFile = new File(initAndGetDataDir(), fileName); String fileNameParam = fileName; // sometimes randomly use an absolute File path instead if (random().nextBoolean()) { fileNameParam = healthcheckFile.getAbsolutePath(); } if (healthcheckFile.exists()) FileUtils.forceDelete(healthcheckFile); handler = new PingRequestHandler(); @SuppressWarnings({"rawtypes"}) NamedList initParams = new NamedList(); initParams.add(PingRequestHandler.HEALTHCHECK_FILE_PARAM, fileNameParam); handler.init(initParams); handler.inform(h.getCore()); }
Example #5
Source File: DiskReporterImplTest.java From sofa-tracer with Apache License 2.0 | 6 votes |
/** * Method: initDigestFile() * fix Concurrent */ @Test public void testFixInitDigestFile() throws Exception { //should be only one item log SelfLog.warn("SelfLog init success!!!"); int nThreads = 30; ExecutorService executor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); for (int i = 0; i < nThreads; i++) { Runnable worker = new WorkerInitThread(this.clientReporter, "" + i); executor.execute(worker); } Thread.sleep(3 * 1000); // When there is no control for concurrent initialization, report span will get an error; // when the repair method is initialized,other threads need to wait for initialization to complete. List<String> contents = FileUtils.readLines(tracerSelfLog()); assertTrue("Actual concurrent init file size = " + contents.size(), contents.size() == 1); }
Example #6
Source File: ScriptTestCase.java From jstarcraft-rns with Apache License 2.0 | 6 votes |
/** * 使用Lua脚本与JStarCraft框架交互 * * <pre> * Java 11执行单元测试会抛<b>Unable to make {member} accessible: module {A} does not '{operation} {package}' to {B}</b>异常 * 是由于Java 9模块化导致 * 需要使用JVM参数:--add-exports java.base/jdk.internal.loader=ALL-UNNAMED * </pre> * * @throws Exception */ @Test public void testLua() throws Exception { // 获取Lua脚本 File file = new File(ScriptTestCase.class.getResource("Model.lua").toURI()); String script = FileUtils.readFileToString(file, StringUtility.CHARSET); // 设置Lua脚本使用到的Java类 ScriptContext context = new ScriptContext(); context.useClasses(Properties.class, Assert.class); context.useClass("Configurator", MapConfigurator.class); context.useClasses("com.jstarcraft.ai.evaluate"); context.useClasses("com.jstarcraft.rns.task"); context.useClasses("com.jstarcraft.rns.model.benchmark"); // 设置Lua脚本使用到的Java变量 ScriptScope scope = new ScriptScope(); scope.createAttribute("loader", loader); // 执行Lua脚本 ScriptExpression expression = new LuaExpression(context, scope, script); LuaTable data = expression.doWith(LuaTable.class); Assert.assertEquals(0.005825241F, data.get("precision").tofloat(), 0F); Assert.assertEquals(0.011579763F, data.get("recall").tofloat(), 0F); Assert.assertEquals(1.2708743F, data.get("mae").tofloat(), 0F); Assert.assertEquals(2.425075F, data.get("mse").tofloat(), 0F); }
Example #7
Source File: VelocityConfigFileWriter.java From oodt with Apache License 2.0 | 6 votes |
@Override public File generateFile(String filePath, Metadata metadata, Logger logger, Object... args) throws IOException { File configFile = new File(filePath); VelocityMetadata velocityMetadata = new VelocityMetadata(metadata); // Velocity requires you to set a path of where to look for // templates. This path defaults to . if not set. int slashIndex = ((String) args[0]).lastIndexOf('/'); String templatePath = ((String) args[0]).substring(0, slashIndex); Velocity.setProperty("file.resource.loader.path", templatePath); // Initialize Velocity and set context up Velocity.init(); VelocityContext context = new VelocityContext(); context.put("metadata", velocityMetadata); context.put("env", System.getenv()); // Load template from templatePath String templateName = ((String) args[0]).substring(slashIndex); Template template = Velocity.getTemplate(templateName); // Fill out template and write to file StringWriter sw = new StringWriter(); template.merge(context, sw); FileUtils.writeStringToFile(configFile, sw.toString()); return configFile; }
Example #8
Source File: CommandInitTest.java From minimesos with Apache License 2.0 | 6 votes |
@Test(expected = MinimesosException.class) public void testExecute_existingMiniMesosFile() throws IOException { String oldHostDir = System.getProperty(MesosCluster.MINIMESOS_HOST_DIR_PROPERTY); File dir = File.createTempFile("mimimesos-test", "dir"); assertTrue("Failed to delete temp file", dir.delete()); assertTrue("Failed to create temp directory", dir.mkdir()); System.setProperty(MesosCluster.MINIMESOS_HOST_DIR_PROPERTY, dir.getAbsolutePath()); File minimesosFile = new File(dir, ClusterConfig.DEFAULT_CONFIG_FILE); Files.write(Paths.get(minimesosFile.getAbsolutePath()), "minimesos { }".getBytes()); try { commandInit.execute(); } finally { if (oldHostDir == null) { System.getProperties().remove(MesosCluster.MINIMESOS_HOST_DIR_PROPERTY); } else { System.setProperty(MesosCluster.MINIMESOS_HOST_DIR_PROPERTY, oldHostDir); } FileUtils.forceDelete(dir); } }
Example #9
Source File: TestSolrConfigHandler.java From lucene-solr with Apache License 2.0 | 6 votes |
@Before public void before() throws Exception { tmpSolrHome = createTempDir().toFile(); tmpConfDir = new File(tmpSolrHome, confDir); FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile()); final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>(); final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class); solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi"); extraServlets.put(solrRestApi, "/schema/*"); // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...' System.setProperty("managed.schema.mutable", "true"); System.setProperty("enable.update.log", "false"); createJettyAndHarness(tmpSolrHome.getAbsolutePath(), "solrconfig-managed-schema.xml", "schema-rest.xml", "/solr", true, extraServlets); if (random().nextBoolean()) { log.info("These tests are run with V2 API"); restTestHarness.setServerProvider(() -> jetty.getBaseUrl().toString() + "/____v2/cores/" + DEFAULT_TEST_CORENAME); } }
Example #10
Source File: ManageDatasets.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void renameAndMoveDatasetFile(String originalFileName, String newFileName, String resourcePath, String fileType) { String filePath = resourcePath + File.separatorChar + "dataset" + File.separatorChar + "files" + File.separatorChar + "temp" + File.separatorChar; String fileNewPath = resourcePath + File.separatorChar + "dataset" + File.separatorChar + "files" + File.separatorChar; File originalDatasetFile = new File(filePath + originalFileName); File newDatasetFile = new File(fileNewPath + newFileName + "." + fileType.toLowerCase()); if (originalDatasetFile.exists()) { /* * This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is * created if it does not exist. If the destination file exists, then this method will overwrite it. */ try { FileUtils.copyFile(originalDatasetFile, newDatasetFile); // Then delete temp file originalDatasetFile.delete(); } catch (IOException e) { logger.debug("Cannot move dataset File"); throw new SpagoBIRuntimeException("Cannot move dataset File", e); } } }
Example #11
Source File: S3DaoTest.java From herd with Apache License 2.0 | 6 votes |
/** * Cleans up the local temp directory and S3 test path that we are using. */ @After public void cleanEnv() throws IOException { // Clean up the local directory. FileUtils.deleteDirectory(localTempPath.toFile()); // Delete test files from S3 storage. Since test S3 key prefix represents a directory, we add a trailing '/' character to it. for (S3FileTransferRequestParamsDto params : Arrays.asList(s3DaoTestHelper.getTestS3FileTransferRequestParamsDto(), S3FileTransferRequestParamsDto.builder().withS3BucketName(storageDaoTestHelper.getS3LoadingDockBucketName()) .withS3KeyPrefix(TEST_S3_KEY_PREFIX + "/").build(), S3FileTransferRequestParamsDto.builder().withS3BucketName(storageDaoTestHelper.getS3ExternalBucketName()).withS3KeyPrefix(TEST_S3_KEY_PREFIX + "/") .build())) { if (!s3Dao.listDirectory(params).isEmpty()) { s3Dao.deleteDirectory(params); } } s3Operations.rollback(); }
Example #12
Source File: FileController.java From wisdom with Apache License 2.0 | 6 votes |
@Route(method = HttpMethod.POST, uri = "/file") public Result upload(final @FormParameter("upload") FileItem file) throws IOException { if (file == null) { flash("error", "true"); flash("message", "No uploaded file"); return badRequest(index()); } // This should be asynchronous. return async(new Callable<Result>() { @Override public Result call() throws Exception { File out = new File(root, file.name()); if (out.exists()) { out.delete(); } FileUtils.moveFile(file.toFile(), out); flash("success", "true"); flash("message", "File " + file.name() + " uploaded (" + out.length() + " bytes)"); return index(); } }); }
Example #13
Source File: SynapseAppDeployer.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Handle main and fault sequence un-deployment. * Since main.xml and fault.xml is already in filesystem, we only can update those. * NO direct deployer call * * @param artifact Sequence Artifact * @param axisConfig AxisConfiguration of the current tenant * @return whether main or fault sequence is handled * @throws IOException */ private boolean handleMainFaultSeqUndeployment(Artifact artifact, AxisConfiguration axisConfig) throws IOException { boolean isMainOrFault = false; String fileName = artifact.getFiles().get(0).getName(); if (fileName.matches(MAIN_SEQ_REGEX) || fileName.matches(SynapseAppDeployerConstants.MAIN_SEQ_FILE)) { isMainOrFault = true; String mainXMLPath = getMainXmlPath(axisConfig); FileUtils.deleteQuietly(new File(mainXMLPath)); FileUtils.writeStringToFile(new File(mainXMLPath), MAIN_XML); } else if (fileName.matches(FAULT_SEQ_REGEX) || fileName.matches(SynapseAppDeployerConstants.FAULT_SEQ_FILE)) { isMainOrFault = true; String faultXMLPath = getFaultXmlPath(axisConfig); FileUtils.deleteQuietly(new File(faultXMLPath)); FileUtils.writeStringToFile(new File(faultXMLPath), FAULT_XML); } return isMainOrFault; }
Example #14
Source File: UsingWithRestAssuredTest.java From curl-logger with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void shouldPrintFileAsBinary() throws IOException { Consumer<String> curlConsumer = mock(Consumer.class); File tempFile = tempFolder.createFile().toFile(); FileUtils.writeStringToFile(tempFile, "{ 'message' : 'hello world'}", Charset.defaultCharset()); //@formatter:off given() .baseUri(MOCK_BASE_URI) .port(MOCK_PORT) .config(getRestAssuredConfig(curlConsumer)) .body(tempFile) .when().post("/"); //@formatter:on verify(curlConsumer).accept( "curl 'http://localhost:" + MOCK_PORT + "/' -H 'Accept: */*' -H 'Content-Type: text/plain; charset=ISO-8859-1' --data-binary $'{ \\'message\\' : \\'hello world\\'}' --compressed -k -v"); }
Example #15
Source File: XMLConfigurationProviderTest.java From walkmod-core with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testAddExcludes() throws Exception { AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null, null, null, false); File aux = new File("src/test/resources/xmlincludes"); aux.mkdirs(); File xml = new File(aux, "walkmod.xml"); XMLConfigurationProvider prov = new XMLConfigurationProvider(xml.getPath(), false); try { prov.createConfig(); TransformationConfig transfCfg = command.buildTransformationCfg(); prov.addTransformationConfig("mychain", null, transfCfg, false, null, null); prov.setWriter("mychain", "eclipse-writer", null, false, null); prov.addExcludesToChain("mychain", Arrays.asList("foo"), false, true, false); String output = FileUtils.readFileToString(xml); System.out.println(output); Assert.assertTrue(output.contains("wildcard") && output.contains("foo")); } finally { FileUtils.deleteDirectory(aux); } }
Example #16
Source File: RemoteLogs.java From desktop with GNU General Public License v3.0 | 6 votes |
private void saveFailedLogs(File compressedLog, Exception generatedException) { File failedFilesDir = new File(failedLogsPath); if (!failedFilesDir.exists()){ failedFilesDir.mkdir(); } /*String exceptionName = generatedException.getClass().getName(); ExceptionsFilenameFilter filter = new ExceptionsFilenameFilter(exceptionName); int fileNum = failedFilesDir.list(filter).length + 1; String fileName = exceptionName + "_" + fileNum + ".gz";*/ int fileNum = failedFilesDir.list().length; String fileName = "log_" + fileNum + ".gz"; File failedLogFile = new File(failedLogsPath + File.separator + fileName); try { FileUtils.moveFile(compressedLog, failedLogFile); this.controller.addFailLog(generatedException, logFolder, fileName); } catch (Exception ex) { // TODO remove?? try again?? } }
Example #17
Source File: AssertFileEqualsTask.java From aws-ant-tasks with Apache License 2.0 | 6 votes |
public void execute() { checkParams(); File file1 = new File(firstFile); if (!file1.exists()) { throw new BuildException("The file " + firstFile + "does not exist"); } File file2 = new File(secondFile); if (!file2.exists()) { throw new BuildException("The file " + secondFile + "does not exist"); } try { if (!FileUtils.contentEquals(file1, file2)) { throw new BuildException( "The two input files are not equal in content"); } } catch (IOException e) { throw new BuildException( "IOException while trying to compare content of files: " + e.getMessage()); } }
Example #18
Source File: GenerateDocsTask.java From synopsys-detect with Apache License 2.0 | 6 votes |
@TaskAction public void generateDocs() throws IOException, TemplateException, IntegrationException { final Project project = getProject(); final File file = new File("synopsys-detect-" + project.getVersion() + "-help.json"); final Reader reader = new FileReader(file); final HelpJsonData helpJson = new Gson().fromJson(reader, HelpJsonData.class); final File outputDir = project.file("docs/generated"); final File troubleshootingDir = new File(outputDir, "advanced/troubleshooting"); FileUtils.deleteDirectory(outputDir); troubleshootingDir.mkdirs(); final TemplateProvider templateProvider = new TemplateProvider(project.file("docs/templates"), project.getVersion().toString()); createFromFreemarker(templateProvider, troubleshootingDir, "exit-codes", new ExitCodePage(helpJson.getExitCodes())); handleDetectors(templateProvider, outputDir, helpJson); handleProperties(templateProvider, outputDir, helpJson); handleContent(outputDir, templateProvider); }
Example #19
Source File: NugetInspectorInstaller.java From synopsys-detect with Apache License 2.0 | 6 votes |
private File installFromSource(final File dest, final String source) throws IntegrationException, IOException { logger.debug("Resolved the nuget inspector url: " + source); final String nupkgName = artifactResolver.parseFileName(source); logger.debug("Parsed artifact name: " + nupkgName); final String inspectorFolderName = nupkgName.replace(".nupkg", ""); final File inspectorFolder = new File(dest, inspectorFolderName); if (!inspectorFolder.exists()) { logger.debug("Downloading nuget inspector."); final File nupkgFile = new File(dest, nupkgName); artifactResolver.downloadArtifact(nupkgFile, source); logger.debug("Extracting nuget inspector."); DetectZipUtil.unzip(nupkgFile, inspectorFolder, Charset.defaultCharset()); FileUtils.deleteQuietly(nupkgFile); } else { logger.debug("Inspector is already downloaded, folder exists."); } return inspectorFolder; }
Example #20
Source File: Md5UtilsTest.java From ibm-cos-sdk-java with Apache License 2.0 | 5 votes |
@Test public void testFile() throws Exception { File f = File.createTempFile("Md5UtilsTest-", "txt"); f.deleteOnExit(); FileUtils.writeStringToFile(f, "Testing MD5"); byte[] md5 = Md5Utils.computeMD5Hash(f); assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5))); String b64 = Md5Utils.md5AsBase64(f); assertEquals("C09QO463cUzhJAJAaJXPaA==", b64); }
Example #21
Source File: LongMultithreadedTransactions.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@After public void after() { try { FileUtils.deleteDirectory(file); } catch (IOException e) { throw new RuntimeException(e); } }
Example #22
Source File: TestActor.java From opentest with MIT License | 5 votes |
/** * Logs the names, versions and commit SHAs of relevant JAR files. */ private void logJarVersions() { Collection<File> jarFiles = null; List<JarFile> jars = new LinkedList<>(); JarFile mainJar = JarUtil.getJarFile(TestActor.class); if (mainJar != null) { jars.add(mainJar); File mainJarFile = new File(mainJar.getName()); jarFiles = FileUtils.listFiles(mainJarFile.getParentFile(), new String[]{"jar"}, true); } else { jarFiles = FileUtils.listFiles(new File("."), new String[]{"jar"}, true); } if (jarFiles != null && jarFiles.size() > 0) { Logger.debug("Test actor JAR versions:"); for (File childFile : jarFiles) { if (childFile.getName().matches("dtest.+\\.jar|opentest.+\\.jar")) { try { JarFile jar = new JarFile(childFile); Logger.debug(String.format(" %s: %s %s", new File(jar.getName()).getName(), JarUtil.getManifestAttribute(jar, "Build-Time"), JarUtil.getManifestAttribute(jar, "Implementation-Version"))); } catch (IOException ex) { Logger.warning(String.format("Failed to determine version for JAR %s", childFile.getName())); } } } } }
Example #23
Source File: FileMergerTest.java From attic-apex-malhar with Apache License 2.0 | 5 votes |
@Test(expected = BlockNotFoundException.class) public void testMissingBlock() throws IOException, BlockNotFoundException { FileUtils.deleteQuietly(testFM.blockFiles[2]); testFM.underTest.tempOutFilePath = new Path(testFM.baseDir, testFM.fileMetaDataMock.getStitchedFileRelativePath() + '.' + System.currentTimeMillis() + FileStitcher.PART_FILE_EXTENTION); testFM.underTest.writeTempOutputFile(testFM.fileMetaDataMock); fail("Failed when one block missing."); }
Example #24
Source File: ApplicationMojo.java From vespa with Apache License 2.0 | 5 votes |
private void copyApplicationPackage(File applicationPackage, File applicationDestination) throws MojoExecutionException { if (applicationPackage.exists()) { try { FileUtils.copyDirectory(applicationPackage, applicationDestination); } catch (IOException e) { throw new MojoExecutionException("Failed copying applicationPackage", e); } } }
Example #25
Source File: VertxMojoTestBase.java From vertx-maven-plugin with Apache License 2.0 | 5 votes |
void filter(File input, Map<String, String> variables) throws IOException { assertThat(input).isFile(); String data = FileUtils.readFileToString(input, "UTF-8"); for (String token : variables.keySet()) { String value = String.valueOf(variables.get(token)); data = StringUtils.replace(data, token, value); } FileUtils.write(input, data, "UTF-8"); }
Example #26
Source File: GoConfigMigratorIntegrationTest.java From gocd with Apache License 2.0 | 5 votes |
@Test public void shouldFailIfJobsWithSameNameButDifferentCasesExistInConfig() throws Exception { FileUtils.writeStringToFile(configFile, ConfigFileFixture.JOBS_WITH_DIFFERNT_CASE, UTF_8); GoConfigHolder configHolder = goConfigMigrator.migrate(); Assertions.assertThat(configHolder).isNull(); PipelineConfig frameworkPipeline = goConfigService.getCurrentConfig().getPipelineConfigByName(new CaseInsensitiveString("framework")); assertThat(frameworkPipeline).isNull(); assertThat(exceptions.size()).isEqualTo(1); assertThat(exceptions.get(0).getMessage()).contains("You have defined multiple Jobs called 'Test'"); }
Example #27
Source File: JavaAstExtractorTest.java From tassal with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Before public void setUp() throws IOException { classContent = FileUtils.readFileToString(new File( JavaAstExtractorTest.class.getClassLoader() .getResource("SampleClass.txt").getFile())); methodContent = FileUtils.readFileToString(new File( JavaAstExtractorTest.class.getClassLoader() .getResource("SampleMethod.txt").getFile())); }
Example #28
Source File: TestBase.java From trex-stateless-gui with Apache License 2.0 | 5 votes |
@Override public void start(Stage stage) throws Exception { FileManager.createDirectoryIfNotExists(FileManager.getLocalFilePath()); FileUtils.cleanDirectory(new File(FileManager.getLocalFilePath())); FileManager.createDirectoryIfNotExists(FileManager.getProfilesFilePath()); TrexApp.setPrimaryStage(stage); app = new TrexApp(); app.start(stage); }
Example #29
Source File: QueryCommand.java From robot with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Given a command line, a dataset to query, and a list of queries, run the queries with any * options from the command line. * * @param line CommandLine with options * @param dataset Dataset to run queries on * @param queries List of queries * @throws IOException on issue reading or writing files */ private static void runQueries(CommandLine line, Dataset dataset, List<List<String>> queries) throws IOException { String format = CommandLineHelper.getOptionalValue(line, "format"); String outputDir = CommandLineHelper.getDefaultValue(line, "output-dir", ""); for (List<String> q : queries) { String queryPath = q.get(0); String outputPath = q.get(1); String query = FileUtils.readFileToString(new File(queryPath)); String formatName = format; if (formatName == null) { if (outputPath == null) { formatName = QueryOperation.getDefaultFormatName(query); } else { formatName = FilenameUtils.getExtension(outputPath); } } if (outputPath == null) { String fileName = FilenameUtils.getBaseName(queryPath) + "." + formatName; outputPath = new File(outputDir).toPath().resolve(fileName).toString(); } OutputStream output = new FileOutputStream(outputPath); QueryOperation.runSparqlQuery(dataset, query, formatName, output); } }
Example #30
Source File: Config.java From o2oa with GNU Affero General Public License v3.0 | 5 votes |
public static File dir_store_jars(Boolean force) throws Exception { File dir = new File(base(), DIR_STORE_JARS); if (force) { if ((!dir.exists()) || dir.isFile()) { FileUtils.forceMkdir(dir); } } return dir; }