List of usage examples for org.apache.commons.io FilenameUtils concat
public static String concat(String basePath, String fullFilenameToAdd)
From source file:net.sf.jvifm.model.FileModelManager.java
public boolean isDestFileExisted(String src, String dst) { File srcFile = new File(src); File dstFile = new File(dst); if (srcFile.isFile()) { if (dstFile.isFile() && dstFile.exists() && srcFile.getName().equals(dstFile.getName()) && !srcFile.getParent().equals(dstFile.getParent())) return true; if (dstFile.isDirectory()) { File tmp = new File(FilenameUtils.concat(dstFile.getPath(), srcFile.getName())); if (tmp.exists() && !srcFile.getParent().equals(dstFile.getPath())) return true; }//from w w w . j a v a 2 s . c o m return false; } if (srcFile.isDirectory()) { if (dstFile.isDirectory()) { File tmp = new File(FilenameUtils.concat(dstFile.getPath(), srcFile.getName())); if (tmp.exists() && !src.equals(dst)) return true; } } return false; }
From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java
/** * //from www.j a v a2 s .co m * Extract a directory in a JAR on the classpath to an output folder. * * Note: User's responsibility to ensure that the files are actually in a JAR. * * @param classInJar A class in the JAR file which is on the classpath * @param resourceDirectory Path to resource directory in JAR * @param outputDirectory Directory to write to * @return String containing the path to the outputDirectory * @throws IOException */ private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory, String outputDirectory) throws IOException { resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator; URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation(); JarFile jarFile = new JarFile(new File(jar.getFile())); byte[] buf = new byte[1024]; Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) { continue; } String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName()); //Create directories if they don't exist new File(FilenameUtils.getFullPath(outputFileName)).mkdirs(); //Write file FileOutputStream fileOutputStream = new FileOutputStream(outputFileName); int n; InputStream is = jarFile.getInputStream(jarEntry); while ((n = is.read(buf, 0, 1024)) > -1) { fileOutputStream.write(buf, 0, n); } is.close(); fileOutputStream.close(); } jarFile.close(); String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory); return fullPath; }
From source file:com.xiaomi.linden.core.TestMultiLindenCore.java
@Test public void testTimeDivision() throws Exception { String path = FilenameUtils.concat(INDEX_DIR, "time/"); lindenConfig.setIndexDirectory(path) .setMultiIndexDivisionType(LindenConfig.MultiIndexDivisionType.TIME_HOUR) .setLindenCoreMode(LindenConfig.LindenCoreMode.MULTI).setMultiIndexMaxLiveIndexNum(10); Deencapsulation.setField(DocNumLimitMultiIndexStrategy.class, "INDEX_CHECK_INTERVAL_MILLISECONDS", -10); lindenCore = new MultiLindenCoreImpl(lindenConfig); for (int i = 0; i < 400; ++i) { JSONObject json = new JSONObject(); json.put("type", "index"); JSONObject content = new JSONObject(); content.put("id", i); content.put("title", "test " + i); json.put("content", content); handleRequest(json.toJSONString()); }//from w w w. j a va 2 s . com lindenCore.commit(); lindenCore.refresh(); Assert.assertEquals(8, lindenCore.getServiceInfo().getIndexNamesSize()); Assert.assertEquals(400, lindenCore.getServiceInfo().getDocsNum()); String bql = "select * from linden source"; LindenSearchRequest request = bqlCompiler.compile(bql).getSearchRequest(); LindenResult result = lindenCore.search(request); Assert.assertEquals(400, result.getTotalHits()); for (int i = 0; i < 400; ++i) { JSONObject json = new JSONObject(); json.put("type", "index"); JSONObject content = new JSONObject(); content.put("id", i); content.put("title", "test " + (400 + i)); json.put("content", content); handleRequest(json.toJSONString()); } lindenCore.commit(); lindenCore.refresh(); result = lindenCore.search(request); Assert.assertEquals(500, result.getTotalHits()); Assert.assertEquals(10, lindenCore.getServiceInfo().getIndexNamesSize()); Assert.assertEquals(500, lindenCore.getServiceInfo().getDocsNum()); bql = "delete from linden where query is 'title:400 title:401'"; LindenDeleteRequest deleteRequest = bqlCompiler.compile(bql).getDeleteRequest(); lindenCore.delete(deleteRequest); lindenCore.commit(); lindenCore.refresh(); Assert.assertEquals(498, lindenCore.getServiceInfo().getDocsNum()); lindenCore.close(); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractLogoController.java
private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response, String cssdkFilesDirectory) { FileInputStream fileinputstream = null; String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (StringUtils.isNotBlank(cssdkFilesDirectory)) { rootImageDir = cssdkFilesDirectory; }//from w ww. j av a 2 s . co m if (rootImageDir != null && !rootImageDir.trim().equals("")) { try { if (imagePath != null && !imagePath.trim().equals("")) { String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath); fileinputstream = new FileInputStream(absoluteImagePath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("image/" + FilenameUtils.getExtension(imagePath)); // TODO:Set Cache headers for browser to force browser to cache to reduce load OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.debug("###File not found in retrieving logo " + imagePath); } catch (IOException e) { logger.debug("###IO Error in retrieving logo"); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", defaultImagePath); }
From source file:edu.cornell.med.icb.goby.counts.TestReadWriteCounts.java
@Test @SuppressWarnings("deprecation") // We are intentionally testing a deprecated method here public void testReadWrite3() throws IOException { final String basename = FilenameUtils.concat(BASE_TEST_DIR, "counts-103.bin"); final CountsWriterI writerI = new CountsWriter(new FileOutputStream(basename), 0); final Random random = new Random(); for (int i = 0; i < 30; i++) { // increased the count to 50,000 to reduce the chance that two successive random values will be equal (which // correctly and intentionally will trigger an assertion) final int count = random.nextInt(50000); final int length = random.nextInt(10) + 1; System.out.println("Appending count: " + count + " length: " + length); writerI.appendCount(count, length); }//from w w w. j a v a 2 s.c o m writerI.close(); final CountsReader reader = new CountsReader(new FileInputStream(basename)); int position = 0; while (reader.hasNextPosition()) { final int count = reader.nextCountAtPosition(); assertEquals(position, reader.getPosition()); System.out.println(String.format(" position= %d count= %d", position++, count)); } }
From source file:avantssar.aslanpp.testing.Tester.java
public static void doTest(TranslationReport rep, ITestTask task, File sourceBaseDir, File targetBaseDir, ASLanPPConnectorImpl translator, TesterCommandLineOptions options, PrintStream err) { String relativePath = FilenameUtils.normalize(task.getASLanPP().getAbsolutePath()) .substring(FilenameUtils.normalizeNoEndSeparator(sourceBaseDir.getAbsolutePath()).length() + 1); File aslanPPinput = new File( FilenameUtils.concat(FilenameUtils.normalize(targetBaseDir.getAbsolutePath()), relativePath)); try {/*from w w w .j av a2 s . c o m*/ FileUtils.copyFile(task.getASLanPP(), aslanPPinput, true); File aslanPPcheck1 = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.aslan++"); File aslanPPcheck1det = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.detailed.aslan++"); File aslanPPcheck1err = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.errors.aslan++"); File aslanPPcheck1warn = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.warnings.aslan++"); File aslanPPcheck2 = null; File aslanPPcheck2det = null; File aslanPPcheck2err = null; File aslanPPcheck2warn = null; File aslanFile = new File(FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".aslan"); File errorsFile = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".errors.txt"); File warningsFile = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".warnings.txt"); // Load the file and write it back to another file. // Then again load it back and write it to another file. // The files should have the same content. String fileName = aslanPPinput.getAbsolutePath(); String aslanppSpec = FileUtils.readFileToString(task.getASLanPP()); TranslatorOptions optPP = new TranslatorOptions(); optPP.setPrettyPrint(true); TranslatorOptions optPPdet = new TranslatorOptions(); optPPdet.setPreprocess(true); // EntityManager.getInstance().purge(); TranslatorOutput firstLoad = translator.translate(optPP, fileName, aslanppSpec); FileUtils.writeStringToFile(aslanPPcheck1, firstLoad.getSpecification()); FileUtils.writeLines(aslanPPcheck1err, firstLoad.getErrors()); aslanPPcheck1err = deleteIfZero(aslanPPcheck1err); FileUtils.writeLines(aslanPPcheck1warn, firstLoad.getWarnings()); aslanPPcheck1warn = deleteIfZero(aslanPPcheck1warn); // EntityManager.getInstance().purge(); TranslatorOutput firstLoadDet = translator.translate(optPPdet, fileName, aslanppSpec); // TODO should use translate_main, since result will be empty FileUtils.writeStringToFile(aslanPPcheck1det, firstLoadDet.getSpecification()); if (firstLoad.getSpecification() != null) { aslanPPcheck2 = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.aslan++"); aslanPPcheck2det = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.detailed.aslan++"); aslanPPcheck2err = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.errors.aslan++"); aslanPPcheck2warn = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.warnings.aslan++"); // EntityManager.getInstance().purge(); TranslatorOutput secondLoad = translator.translate(optPP, null, firstLoad.getSpecification()); FileUtils.writeStringToFile(aslanPPcheck2, secondLoad.getSpecification()); FileUtils.writeLines(aslanPPcheck2err, secondLoad.getErrors()); aslanPPcheck2err = deleteIfZero(aslanPPcheck2err); FileUtils.writeLines(aslanPPcheck2warn, secondLoad.getWarnings()); aslanPPcheck2warn = deleteIfZero(aslanPPcheck2warn); // EntityManager.getInstance().purge(); TranslatorOutput secondLoadDet = translator.translate(optPPdet, null, firstLoad.getSpecification()); FileUtils.writeStringToFile(aslanPPcheck2det, secondLoadDet.getSpecification()); } // EntityManager.getInstance().purge(); TranslatorOutput result = translator.translate(options, fileName, aslanppSpec); FileUtils.writeStringToFile(aslanFile, result.getSpecification()); FileUtils.writeLines(errorsFile, result.getErrors()); FileUtils.writeLines(warningsFile, result.getWarnings()); File expASLan = null; if (task.getExpectedASLan() != null) { expASLan = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".expected.aslan"); FileUtils.copyFile(task.getExpectedASLan(), expASLan, true); } TranslationInstance ti = rep.newInstance(aslanPPinput, deleteIfZero(aslanPPcheck1), deleteIfZero(aslanPPcheck1det), deleteIfZero(aslanPPcheck2), deleteIfZero(aslanPPcheck2det), result.getErrors().size(), deleteIfZero(errorsFile), result.getWarnings().size(), deleteIfZero(warningsFile), deleteIfZero(expASLan), deleteIfZero(aslanFile), task.getExpectedVerdict()); if (ti.hasTranslation()) { if (bm != null && bm.getBackendRunners().size() > 0) { for (final IBackendRunner runner : bm.getBackendRunners()) { try { List<String> pars = task.getBackendParameters(runner.getName()); pool.execute(new BackendTask(runner.spawn(), pars, aslanFile, ti)); } catch (BackendRunnerInstantiationException bex) { Debug.logger.error("Failed to spawn backend " + runner.getName() + ".", bex); } } } } } catch (Exception e) { System.out.println("Exception while testing file '" + task.getASLanPP().getAbsolutePath() + "': " + e.getMessage()); Debug.logger.error("Failed to test file '" + aslanPPinput + "'.", e); } }
From source file:edu.cornell.med.icb.goby.stats.TestStatsWriter.java
@Test public void testGenotypes() throws IOException { final String file = FilenameUtils.concat(BASE_TEST_DIR, "genotypes-1.vcf"); VCFWriter writer = new VCFWriter(new PrintWriter(new FileWriter(file))); int fieldC = writer.defineField("FORMAT", "GT", 1, ColumnType.String, "Genotype"); String samples[] = { "sample-id-1", "sample-id-2" }; writer.defineSamples(samples);//from ww w .j a va 2 s .co m writer.writeHeader(); writer.setReferenceAllele("A"); // Only CC ref should remain in output writer.setReferenceAllele("CC"); writer.addAlternateAllele("A"); writer.addAlternateAllele("N"); writer.addAlternateAllele("T"); writer.addAlternateAllele("C"); writer.setSampleValue(fieldC, 0, writer.codeGenotype("CC/T")); writer.setSampleValue(fieldC, 1, writer.codeGenotype("A/C/T")); writer.writeRecord(); writer.setReferenceAllele("A"); writer.addAlternateAllele("C"); writer.addAlternateAllele("T"); writer.setSampleValue(fieldC, 0, writer.codeGenotype("A/A")); writer.setSampleValue(fieldC, 1, writer.codeGenotype("A/C")); writer.writeRecord(); writer.close(); assertEquals(new File("test-data/stats-writer/expected-genotypes-1.vcf"), new File("test-results/stats-writer/genotypes-1.vcf")); }
From source file:m.w.sys.module.FileModule.java
@At("/downfile") @Ok("raw:stream") public void downfile(String fileName, String filePath, HttpServletResponse rep) { if (!Strings.isBlank(fileName) && !Strings.isBlank(filePath)) { if (filePath.startsWith(FileService.UPLOAD_URL)) { filePath = filePath.substring(FileService.UPLOAD_URL.length()); }/*from w ww. j av a 2s . c o m*/ File file = new File(FilenameUtils.concat(FileService.UPLOAD_ROOT_DIR, filePath)); if (file.exists()) { InputStream fileIn = Streams.fileIn(file); long fileSize = FileUtils.sizeOf(file); rep.setContentType("application/x-msdownload"); rep.setContentLength((int) fileSize); String outFileName = Names.encodeFileName(fileName); rep.setHeader("Content-Disposition", "attachment; filename=".concat(outFileName)); int blockSize = 4096; int totalRead = 0; int readBytes = 0; byte b[] = new byte[blockSize]; try { while ((long) totalRead < fileSize) { readBytes = fileIn.read(b, 0, blockSize); totalRead += readBytes; rep.getOutputStream().write(b, 0, readBytes); } fileIn.close(); } catch (Exception e) { // ??? } } } }
From source file:edu.cornell.med.icb.goby.alignments.TestReadWriteAlignments.java
@Test public void readWriteHeader103() throws IOException { final IndexedIdentifier queryIds = new IndexedIdentifier(); // NOTE: there is no id for entry 0, this is ok queryIds.put(new MutableString("query:1"), 1); queryIds.put(new MutableString("query:2"), 2); final IndexedIdentifier targetIds = new IndexedIdentifier(); targetIds.put(new MutableString("target:0"), 0); targetIds.put(new MutableString("target:1"), 1); final AlignmentWriter writer = new AlignmentWriterImpl(FilenameUtils.concat(BASE_TEST_DIR, "align-103")); assertNotNull("Query ids should not be null", queryIds.keySet()); writer.setQueryIdentifiers(queryIds); final int[] queryLengths = { 0, 34, 84 }; assertNotNull("Target ids should not be null", targetIds.keySet()); writer.setTargetIdentifiers(targetIds); final int[] targetLengths = { 0, 42 }; writer.setTargetLengths(targetLengths); writer.close();/*from ww w . j a va2 s.c o m*/ final AlignmentReaderImpl reader = new AlignmentReaderImpl( FilenameUtils.concat(BASE_TEST_DIR, "align-103")); reader.readHeader(); assertEquals("Number of queries do not match", 2, reader.getNumberOfQueries()); assertArrayEquals("Target lengths do not match", targetLengths, reader.getTargetLength()); assertEquals("Number of targets do not match", 2, reader.getNumberOfTargets()); }
From source file:com.nagarro.core.util.ws.impl.AddonAwareMessageSource.java
/** * Formats absolute file path using basePath to format acceptable by @link ReloadableResourceBundleMessageSource} * Basename property//from w w w.j ava2s . c om */ protected String formatPath(final String path, final String basePath) { int pos = path.lastIndexOf(basePath); //base path is not in the path -> shouldn't happen if (pos == -1) { return null; } final String pathFromBase = path.substring(pos); String fileName = FilenameUtils.getBaseName(pathFromBase); final String targetPath = FilenameUtils.getFullPath(pathFromBase); pos = fileName.indexOf("_"); if (pos != -1) { fileName = fileName.substring(0, pos); } return FilenameUtils.concat(targetPath, fileName); }