Java Code Examples for org.apache.commons.io.FileUtils
The following examples show how to use
org.apache.commons.io.FileUtils.
These examples are extracted from open source projects.
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 Project: webanno Author: webanno File: CasMergeSuiteTest.java License: Apache License 2.0 | 6 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 Project: jstarcraft-rns Author: HongZhaoHua File: ScriptTestCase.java License: 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 #3
Source Project: gatk Author: broadinstitute File: IOUtils.java License: 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 Project: sofa-tracer Author: sofastack File: DiskReporterImplTest.java License: 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 #5
Source Project: lucene-solr Author: apache File: PingRequestHandlerTest.java License: 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 #6
Source Project: selenium-grid-extensions Author: sterodium File: FileDeleteServletTest.java License: 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 #7
Source Project: oodt Author: apache File: VelocityConfigFileWriter.java License: 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 Project: minimesos Author: ContainerSolutions File: CommandInitTest.java License: 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 Project: lucene-solr Author: apache File: TestSolrConfigHandler.java License: 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 Project: Knowage-Server Author: KnowageLabs File: ManageDatasets.java License: 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 Project: desktop Author: stacksync File: RemoteLogs.java License: 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 #12
Source Project: herd Author: FINRAOS File: S3DaoTest.java License: 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 #13
Source Project: wisdom Author: wisdom-framework File: FileController.java License: 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 #14
Source Project: micro-integrator Author: wso2 File: SynapseAppDeployer.java License: 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 #15
Source Project: curl-logger Author: dzieciou File: UsingWithRestAssuredTest.java License: 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 #16
Source Project: walkmod-core Author: walkmod File: XMLConfigurationProviderTest.java License: 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 #17
Source Project: aws-ant-tasks Author: amazon-archives File: AssertFileEqualsTask.java License: 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 Project: synopsys-detect Author: blackducksoftware File: GenerateDocsTask.java License: 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 Project: synopsys-detect Author: blackducksoftware File: NugetInspectorInstaller.java License: 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 Project: gemfirexd-oss Author: gemxd File: ExtractorUtils.java License: Apache License 2.0 | 5 votes |
/*** File Manipulation Methods for tests***/ public static void cleanWorkingDirectory() { try { File workingDirectory = new File(System.getProperty("user.dir")); cleanFiles(workingDirectory, extensionFilter); File ddDir = new File(workingDirectory, "datadictionary"); if (ddDir.exists() && ddDir.isDirectory()) { FileUtils.deleteDirectory(ddDir); } } catch (Exception e) { GemFireXDDataExtractorImpl.logInfo("Error occured while cleaning the working directory", e); } }
Example #21
Source Project: jstorm Author: alibaba File: VersionedStore.java License: Apache License 2.0 | 5 votes |
public void deleteVersion(long version) throws IOException { File versionFile = new File(versionPath(version)); File tokenFile = new File(tokenPath(version)); if (tokenFile.exists()) { FileUtils.forceDelete(tokenFile); } if (versionFile.exists()) { FileUtils.forceDelete(versionFile); } }
Example #22
Source Project: I18nUpdateMod Author: CFPAOrg File: CmdUpload.java License: MIT License | 5 votes |
/** * 将准备上传的语言文件进行处理 * * @param modid 上传的模组资源 domain * @return 处理后的文件对象 * @throws IOException 读取文件可能发生的 IO 错误 */ @Nullable private File handleFile(String modid) throws IOException { // 英文,中文,临时文件 File rawChineseFile = new File(String.format(Minecraft.getMinecraft().mcDataDir.toString() + File.separator + "resourcepacks" + File.separator + "%s_tmp_resource_pack" + File.separator + "assets" + File.separator + "%s" + File.separator + "lang" + File.separator + "zh_cn.lang", modid, modid)); File rawEnglishFile = new File(String.format(Minecraft.getMinecraft().mcDataDir.toString() + File.separator + "resourcepacks" + File.separator + "%s_tmp_resource_pack" + File.separator + "assets" + File.separator + "%s" + File.separator + "lang" + File.separator + "en_us.lang", modid, modid)); File handleChineseFile = new File(String.format(Minecraft.getMinecraft().mcDataDir.toString() + File.separator + "resourcepacks" + File.separator + "%s_tmp_resource_pack" + File.separator + "assets" + File.separator + "%s" + File.separator + "lang" + File.separator + "zh_cn_tmp.lang", modid, modid)); // 文件存在,才进行处理 if (rawEnglishFile.exists() && rawChineseFile.exists()) { // 读取处理成 HashMap Map<String, String> zh_cn = I18nUtils.listToMap(FileUtils.readLines(rawChineseFile, StandardCharsets.UTF_8)); Map<String, String> en_us = I18nUtils.listToMap(FileUtils.readLines(rawEnglishFile, StandardCharsets.UTF_8)); // 未翻译处进行剔除 List<String> tmpFile = new ArrayList<>(); for (String key : zh_cn.keySet()) { if (en_us.get(key) != null && !en_us.get(key).equals(zh_cn.get(key))) { tmpFile.add(key + '=' + zh_cn.get(key)); } } // 文件写入 FileUtils.writeLines(handleChineseFile, "UTF-8", tmpFile, "\n", false); Minecraft.getMinecraft().player.sendMessage(new TextComponentTranslation("message.i18nmod.cmd_upload.handle_success")); return handleChineseFile; } else { return null; // 不存在返回 null } }
Example #23
Source Project: maven-replacer-plugin Author: beiliubei File: ReplacerMojoIntegrationTest.java License: MIT License | 5 votes |
@Test public void shouldReplaceContentsInFileWithDelimiteredToken() throws Exception { filenameAndPath = createTempFile("@" + TOKEN + "@ and ${" + TOKEN + "}"); mojo.setFile(filenameAndPath); mojo.setRegex(false); mojo.setToken(TOKEN); mojo.setValue(VALUE); mojo.setDelimiters(asList("@", "${*}")); mojo.execute(); String results = FileUtils.readFileToString(new File(filenameAndPath)); assertThat(results, equalTo(VALUE + " and " + VALUE)); verify(log).info("Replacement run on 1 file."); }
Example #24
Source Project: opentest Author: mcdcorp File: TestActor.java License: 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 #25
Source Project: carbon-identity-framework Author: wso2 File: UserStoreConfigComponent.java License: Apache License 2.0 | 5 votes |
/** * This method invoked when the bundle get activated, it touches the super-tenants user store * configuration with latest time stamp. This invokes undeploy and deploy method */ private void triggerDeployerForSuperTenantSecondaryUserStores() { String repositoryPath = CarbonUtils.getCarbonRepository(); int repoLength = repositoryPath.length(); /** * This operation is done to make sure if the getCarbonRepository method doesn't return a * file path with File.Separator at the end, this will add it * If repositoryPath is ,<CARBON_HOME>/repository/deployment this method will add * File.separator at the end. If not this will exit */ String fSeperator = repositoryPath.substring(repoLength - 1, repoLength); if (!fSeperator.equals(File.separator)) { repositoryPath += File.separator; } String superTenantUserStorePath = repositoryPath + "userstores" + File.separator; File folder = new File(superTenantUserStorePath); File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) { if (file != null) { String ext = FilenameUtils.getExtension(file.getAbsolutePath()); if (isValidExtension(ext)) { try { FileUtils.touch(new File(file.getAbsolutePath())); } catch (IOException e) { String errMsg = "Error occurred while trying to touch " + file.getName() + ". Passwords will continue to remain in plaintext"; log.error(errMsg, e); // continuing here since user stores are still functional // except the passwords are in plain text } } } } } }
Example #26
Source Project: rdf4j Author: eclipse File: LongMultithreadedTransactions.java License: 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 #27
Source Project: Recaf Author: Col-E File: FontSlider.java License: MIT License | 5 votes |
/** * Update's the font-size override sheet and reapplies styles to open windows. * @param controller Controller to update. */ public static void update(GuiController controller) { try { double size = controller.config().display().fontSize; String css = ".root { -fx-font-size: " + size + "px; }\n" + ".h1 { -fx-font-size: " + (size + 5) + "px; }\n" + ".h2 { -fx-font-size: " + (size + 3) + "px; }"; FileUtils.write(fontCssFile, css, StandardCharsets.UTF_8); controller.windows().reapplyStyles(); } catch(IOException ex) { ExceptionAlert.show(ex, "Failed to set font size"); } }
Example #28
Source Project: vertx-camel-bridge Author: vert-x3 File: OutboundEndpointTest.java License: Apache License 2.0 | 5 votes |
@Test public void testWithStreams() throws Exception { File root = new File("target/junk"); File file = new File(root, "foo.txt"); if (file.exists()) { file.delete(); } root.mkdirs(); Endpoint endpoint = camel.getEndpoint("stream:file?fileName=target/junk/foo.txt"); camel.addEndpoint("output", endpoint); bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel) .addOutboundMapping(fromVertx("test").toCamel("output"))); camel.start(); BridgeHelper.startBlocking(bridge); long date = System.currentTimeMillis(); vertx.eventBus().send("test", date); await().atMost(DEFAULT_TIMEOUT).until(() -> file.isFile() && FileUtils.readFileToString(file).length() > 0); String string = FileUtils.readFileToString(file); assertThat(string).contains(Long.toString(date)); long date2 = System.currentTimeMillis(); vertx.eventBus().send("test", date2); await().atMost(DEFAULT_TIMEOUT).until(() -> FileUtils.readFileToString(file).length() > string.length()); assertThat(FileUtils.readFileToString(file)).containsSequence(Long.toString(date), Long.toString(date2)); }
Example #29
Source Project: gocd Author: gocd File: GitCommandTest.java License: Apache License 2.0 | 5 votes |
@Test void shouldCleanIgnoredFilesIfToggleIsDisabled() throws IOException { InMemoryStreamConsumer output = inMemoryConsumer(); File gitIgnoreFile = new File(repoLocation, ".gitignore"); FileUtils.writeStringToFile(gitIgnoreFile, "*.foo", UTF_8); gitRepo.addFileAndPush(gitIgnoreFile, "added gitignore"); git.fetchAndResetToHead(output); File ignoredFile = new File(gitLocalRepoDir, "ignored.foo"); assertThat(ignoredFile.createNewFile()).isTrue(); git.fetchAndResetToHead(output); assertThat(ignoredFile.exists()).isFalse(); }
Example #30
Source Project: hadoop Author: naver File: AbstractZKRegistryTest.java License: Apache License 2.0 | 5 votes |
@BeforeClass public static void createZKServer() throws Exception { File zkDir = new File("target/zookeeper"); FileUtils.deleteDirectory(zkDir); assertTrue(zkDir.mkdirs()); zookeeper = new MicroZookeeperService("InMemoryZKService"); YarnConfiguration conf = new YarnConfiguration(); conf.set(MicroZookeeperServiceKeys.KEY_ZKSERVICE_DIR, zkDir.getAbsolutePath()); zookeeper.init(conf); zookeeper.start(); addToTeardown(zookeeper); }