List of usage examples for org.apache.commons.io FilenameUtils getExtension
public static String getExtension(String filename)
From source file:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java
public static void main(final String[] args) throws JSAPException, IOException { final JSAP jsap = new JSAP(); final FlaggedOption sequenceOption = new FlaggedOption("input"); sequenceOption.setRequired(true);//from w w w .j a v a 2 s.c om sequenceOption.setLongFlag("input"); sequenceOption.setShortFlag('i'); sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true)); sequenceOption.setHelp("The input file (in Fasta format) to convert"); jsap.registerParameter(sequenceOption); final FlaggedOption outputOption = new FlaggedOption("output"); outputOption.setRequired(false); outputOption.setLongFlag("output"); outputOption.setShortFlag('o'); outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true)); outputOption.setHelp("The output file to write to (default = stdout)"); jsap.registerParameter(outputOption); final FlaggedOption titleOption = new FlaggedOption("title"); titleOption.setRequired(false); titleOption.setLongFlag("title"); titleOption.setShortFlag('t'); titleOption.setHelp("Title for this conversion"); jsap.registerParameter(titleOption); final Switch verboseOption = new Switch("verbose"); verboseOption.setLongFlag("verbose"); verboseOption.setShortFlag('v'); verboseOption.setHelp("Verbose output"); jsap.registerParameter(verboseOption); final Switch helpOption = new Switch("help"); helpOption.setLongFlag("help"); helpOption.setShortFlag('h'); helpOption.setHelp("Print this message"); jsap.registerParameter(helpOption); jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage()); final JSAPResult result = jsap.parse(args); if (result.getBoolean("help")) { System.out.println(jsap.getHelp()); System.exit(0); } if (!result.success()) { final Iterator<String> errors = result.getErrorMessageIterator(); while (errors.hasNext()) { System.err.println(errors.next()); } System.err.println(jsap.getUsage()); System.exit(1); } final boolean verbose = result.getBoolean("verbose"); final File sequenceFile = result.getFile("input"); if (verbose) { System.out.println("Reading sequence from: " + sequenceFile); } // extract the title to use for the output header final String title; if (result.contains("title")) { title = result.getString("title"); } else { title = sequenceFile.getName(); } Reader inputReader = null; PrintWriter outputWriter = null; try { if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) { inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile))); } else { inputReader = new FileReader(sequenceFile); } final FastaParser fastaParser = new FastaParser(inputReader); final File outputFile = result.getFile("output"); final OutputStream outputStream; if (outputFile != null) { outputStream = FileUtils.openOutputStream(outputFile); if (verbose) { System.out.println("Writing sequence : " + outputFile); } } else { outputStream = System.out; } outputWriter = new PrintWriter(outputStream); // write the header portion of the output outputWriter.print("# "); outputWriter.print(new Date()); outputWriter.print(' '); outputWriter.print(ColorSpaceConverter.class.getName()); for (final String arg : args) { outputWriter.print(' '); outputWriter.print(arg); } outputWriter.println(); outputWriter.print("# Cwd: "); outputWriter.println(new File(".").getCanonicalPath()); outputWriter.print("# Title: "); outputWriter.println(title); // now parse the input sequence long sequenceCount = 0; final MutableString descriptionLine = new MutableString(); final MutableString sequence = new MutableString(); final MutableString colorSpaceSequence = new MutableString(); while (fastaParser.hasNext()) { fastaParser.next(descriptionLine, sequence); outputWriter.print('>'); outputWriter.println(descriptionLine); convert(sequence, colorSpaceSequence); CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence); sequenceCount++; if (verbose && sequenceCount % 10000 == 0) { System.out.println("Converted " + sequenceCount + " entries"); } } if (verbose) { System.out.println("Conversion complete!"); } } finally { IOUtils.closeQuietly(inputReader); IOUtils.closeQuietly(outputWriter); } }
From source file:eu.h2020.symbiote.model.RDFFormat.java
public static RDFFormat fromFilename(String filename) { String ext = FilenameUtils.getExtension(filename).toLowerCase(); switch (ext) { case "ttl": return RDFFormat.Turtle; case "nt": return RDFFormat.NTriples; case "rdf": case "xml": return RDFFormat.RDFXML; case "n3": return RDFFormat.N3; case "jsonld": return RDFFormat.JSONLD; default:/*w w w . j a v a 2 s . c o m*/ throw new IllegalArgumentException("unknown file extension '" + ext + "'"); } }
From source file:eumetsat.pn.common.util.MimeUtil.java
/** * Get Mime type from a Filename// www . j a v a 2 s . c om * * @param aFilename * @return Mime type as a String */ static final public String getMimeType(String aFilename) { String mime; if (aFilename == null) { throw new IllegalArgumentException("aFilename is null"); } String extension = FilenameUtils.getExtension(aFilename); if (extension.equalsIgnoreCase("css")) { mime = "text/css"; } else if (extension.equalsIgnoreCase("js")) { mime = "text/javascript"; } else if (extension.equalsIgnoreCase("ico")) { mime = "image/x-icon"; } else if (extension.equalsIgnoreCase(".svg")) { mime = "image/svg+xml"; } else { mime = "application/octet-stream"; } return mime; }
From source file:cn.guoyukun.spring.utils.ImagesUtils.java
/** * ?/*from w w w . j ava 2 s .co m*/ * * @param filename * @return */ public static boolean isImage(String filename) { if (filename == null || filename.trim().length() == 0) return false; return ArrayUtils.contains(IMAGES_SUFFIXES, FilenameUtils.getExtension(filename).toLowerCase()); }
From source file:io.cloudslang.lang.tools.build.SlangBuildMain.java
public static void main(String[] args) { loadUserProperties();//from w w w.j a va 2s .c o m configureLog4j(); ApplicationArgs appArgs = new ApplicationArgs(); parseArgs(args, appArgs); String projectPath = parseProjectPathArg(appArgs); final String contentPath = defaultIfEmpty(appArgs.getContentRoot(), projectPath + CONTENT_DIR); final String testsPath = defaultIfEmpty(appArgs.getTestRoot(), projectPath + TEST_DIR); List<String> testSuites = parseTestSuites(appArgs); boolean shouldPrintCoverageData = appArgs.shouldOutputCoverage(); boolean runTestsInParallel = appArgs.isParallel(); int threadCount = parseThreadCountArg(appArgs, runTestsInParallel); String testCaseTimeout = parseTestTimeout(appArgs); setProperty(TEST_CASE_TIMEOUT_IN_MINUTES_KEY, valueOf(testCaseTimeout)); final boolean shouldValidateDescription = appArgs.shouldValidateDescription(); final boolean shouldValidateCheckstyle = appArgs.shouldValidateCheckstyle(); String runConfigPath = FilenameUtils.normalize(appArgs.getRunConfigPath()); BuildMode buildMode = null; Set<String> changedFiles = null; try { String smartModePath = appArgs.getChangesOnlyConfigPath(); if (StringUtils.isEmpty(smartModePath)) { buildMode = BuildMode.BASIC; changedFiles = new HashSet<>(); printBuildModeInfo(buildMode); } else { buildMode = BuildMode.CHANGED; changedFiles = readChangedFilesFromSource(smartModePath); printBuildModeInfo(buildMode); } } catch (Exception ex) { log.error("Exception: " + ex.getMessage()); System.exit(1); } // Override with the values from the file if configured List<String> testSuitesParallel = new ArrayList<>(); List<String> testSuitesSequential = new ArrayList<>(); BulkRunMode bulkRunMode = runTestsInParallel ? ALL_PARALLEL : ALL_SEQUENTIAL; TestCaseRunMode unspecifiedTestSuiteRunMode = runTestsInParallel ? TestCaseRunMode.PARALLEL : TestCaseRunMode.SEQUENTIAL; if (get(runConfigPath).isAbsolute() && isRegularFile(get(runConfigPath), NOFOLLOW_LINKS) && equalsIgnoreCase(PROPERTIES_FILE_EXTENSION, FilenameUtils.getExtension(runConfigPath))) { Properties runConfigurationProperties = ArgumentProcessorUtils.getPropertiesFromFile(runConfigPath); shouldPrintCoverageData = getBooleanFromPropertiesWithDefault(TEST_COVERAGE, shouldPrintCoverageData, runConfigurationProperties); threadCount = getIntFromPropertiesWithDefaultAndRange(TEST_PARALLEL_THREAD_COUNT, Runtime.getRuntime().availableProcessors(), runConfigurationProperties, 1, MAX_THREADS_TEST_RUNNER + 1); testSuites = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_TO_RUN); testSuitesParallel = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_PARALLEL); testSuitesSequential = getTestSuitesForKey(runConfigurationProperties, TEST_SUITES_SEQUENTIAL); addErrorIfSameTestSuiteIsInBothParallelOrSequential(testSuitesParallel, testSuitesSequential); unspecifiedTestSuiteRunMode = getEnumInstanceFromPropertiesWithDefault(TEST_SUITES_RUN_UNSPECIFIED, unspecifiedTestSuiteRunMode, runConfigurationProperties); addWarningsForMisconfiguredTestSuites(unspecifiedTestSuiteRunMode, testSuites, testSuitesSequential, testSuitesParallel); bulkRunMode = POSSIBLY_MIXED; } else { // Warn when file is misconfigured, relative path, file does not exist or is not a properties file log.info(format(DID_NOT_DETECT_RUN_CONFIGURATION_PROPERTIES_FILE, runConfigPath)); } String testCaseReportLocation = getProperty(TEST_CASE_REPORT_LOCATION); if (StringUtils.isBlank(testCaseReportLocation)) { log.info("Test case report location property [" + TEST_CASE_REPORT_LOCATION + "] is not defined. Report will be skipped."); } // Setting thread count for visibility in ParallelTestCaseExecutorService setProperty(SLANG_TEST_RUNNER_THREAD_COUNT, valueOf(threadCount)); log.info(NEW_LINE + "------------------------------------------------------------"); log.info("Building project: " + projectPath); log.info("Content root is at: " + contentPath); log.info("Test root is at: " + testsPath); log.info("Active test suites are: " + getListForPrint(testSuites)); log.info("Parallel run mode is configured for test suites: " + getListForPrint(testSuitesParallel)); log.info("Sequential run mode is configured for test suites: " + getListForPrint(testSuitesSequential)); log.info("Default run mode '" + unspecifiedTestSuiteRunMode.name().toLowerCase() + "' is configured for test suites: " + getListForPrint( getDefaultRunModeTestSuites(testSuites, testSuitesParallel, testSuitesSequential))); log.info("Bulk run mode for tests: " + getBulkModeForPrint(bulkRunMode)); log.info("Print coverage data: " + valueOf(shouldPrintCoverageData)); log.info("Validate description: " + valueOf(shouldValidateDescription)); log.info("Validate checkstyle: " + valueOf(shouldValidateCheckstyle)); log.info("Thread count: " + threadCount); log.info("Test case timeout in minutes: " + (isEmpty(testCaseTimeout) ? valueOf(MAX_TIME_PER_TESTCASE_IN_MINUTES) : testCaseTimeout)); log.info(NEW_LINE + "Loading..."); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/testRunnerContext.xml"); context.registerShutdownHook(); SlangBuilder slangBuilder = context.getBean(SlangBuilder.class); LoggingService loggingService = context.getBean(LoggingServiceImpl.class); Slang slang = context.getBean(Slang.class); try { updateTestSuiteMappings(context.getBean(TestRunInfoService.class), testSuitesParallel, testSuitesSequential, testSuites, unspecifiedTestSuiteRunMode); registerEventHandlers(slang); List<RuntimeException> exceptions = new ArrayList<>(); SlangBuildResults buildResults = slangBuilder.buildSlangContent(projectPath, contentPath, testsPath, testSuites, shouldValidateDescription, shouldValidateCheckstyle, bulkRunMode, buildMode, changedFiles); exceptions.addAll(buildResults.getCompilationExceptions()); if (exceptions.size() > 0) { logErrors(exceptions, projectPath, loggingService); } IRunTestResults runTestsResults = buildResults.getRunTestsResults(); Map<String, TestRun> skippedTests = runTestsResults.getSkippedTests(); if (isNotEmpty(skippedTests)) { printSkippedTestsSummary(skippedTests, loggingService); } printPassedTests(runTestsResults, loggingService); if (shouldPrintCoverageData) { printTestCoverageData(runTestsResults, loggingService); } if (isNotEmpty(runTestsResults.getFailedTests())) { printBuildFailureSummary(projectPath, runTestsResults, loggingService); } else { printBuildSuccessSummary(contentPath, buildResults, runTestsResults, loggingService); } loggingService.waitForAllLogTasksToFinish(); generateTestCaseReport(context.getBean(SlangTestCaseRunReportGeneratorService.class), runTestsResults, testCaseReportLocation); System.exit(isNotEmpty(runTestsResults.getFailedTests()) ? 1 : 0); } catch (Throwable e) { logErrorsPrefix(loggingService); loggingService.logEvent(Level.ERROR, "Exception: " + e.getMessage()); logErrorsSuffix(projectPath, loggingService); loggingService.waitForAllLogTasksToFinish(); System.exit(1); } }
From source file:com.book.identification.FileType.java
public static FileType valueOf(File file) { String extension = FilenameUtils.getExtension(file.getName()); return FileType.valueOf(extension.toUpperCase()); }
From source file:com.kamike.misc.FsNameUtils.java
public static String getName(String prefix, String disk, String filename, String fid, String uid) { String name = FilenameUtils.getName(filename); Date date = new Date(System.currentTimeMillis()); String extension = FilenameUtils.getExtension(name); return getName(prefix, disk, getShortDate(date), name, fid, uid, extension); }
From source file:javacommon.excel.ExcelConstants.java
/** * ?Excel/*w w w .jav a 2 s .co m*/ * * @param filename * @return Excel 0 : 1997Excel(?xls);1 : 2007Excel(?xlsx) */ public static int getExcelType(String filename) { String extension = FilenameUtils.getExtension(filename); if (extension.equalsIgnoreCase("xls")) { return EXCEL_XLS_VERSION; } else if (extension.equalsIgnoreCase("xlsx")) { return EXCEL_XLSX_VERSION; } return EXCEL_XLS_VERSION; }
From source file:com.compomics.pride_asa_pipeline.core.repository.factory.FileParserFactory.java
public static FileParser getFileParser(File inputFile) throws IOException { currentInputFile = inputFile;/*w w w . j a v a2 s . c o m*/ FileParser parser = null; String extension = FilenameUtils.getExtension(inputFile.getAbsolutePath()).toLowerCase(); //TODO if extension =.gz ---> unzip ---> new extension if (extension.equalsIgnoreCase("zip")) { } else if (extension.equalsIgnoreCase("gz")) { } else if (extension.equalsIgnoreCase("rar")) { } else if (extension.equalsIgnoreCase("tar")) { } switch (extension.toLowerCase()) { case "mzid": LOGGER.info("Detected mzml file extension."); parser = new MzIdentMlParser(); break; case "xml": LOGGER.info("Detected xml file extension."); parser = new PrideXmlParser(); break; default: throw new IOException("Unsupported filetype for parameter-extraction : ." + extension); } return parser; }
From source file:com.daphne.es.maintain.staticresource.web.controller.utils.YuiCompressorUtils.java
/** * js/css ??.min.js/css/*from w w w . ja va 2 s . c om*/ * @param fileName * @return ?? */ public static String compress(final String fileName) { String minFileName = null; final String extension = FilenameUtils.getExtension(fileName); if ("js".equalsIgnoreCase(extension)) { minFileName = fileName.substring(0, fileName.length() - 3) + ".min.js"; } else if ("css".equals(extension)) { minFileName = fileName.substring(0, fileName.length() - 4) + ".min.css"; } else { throw new RuntimeException( "file type only is js/css, but was fileName:" + fileName + ", extension:" + extension); } Reader in = null; Writer out = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Constants.ENCODING)); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(minFileName), Constants.ENCODING)); if ("js".equals(extension)) { CustomErrorReporter errorReporter = new CustomErrorReporter(); JavaScriptCompressor compressor = new JavaScriptCompressor(in, errorReporter); compressor.compress(out, 10, true, false, false, false); if (errorReporter.hasError()) { throw new RuntimeException(errorReporter.getErrorMessage()); } } else if ("css".equals(extension)) { CssCompressor compressor = new CssCompressor(in); compressor.compress(out, 10); } } catch (Exception e) { //?js/css try { FileUtils.copyFile(new File(fileName), new File(minFileName)); } catch (IOException ioException) { throw new RuntimeException("compress error:" + ioException.getMessage(), ioException); } throw new RuntimeException("compress error:" + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } if (FileUtils.sizeOf(new File(minFileName)) == 0) { try { FileUtils.copyFile(new File(fileName), new File(minFileName)); } catch (IOException ioException) { throw new RuntimeException("compress error:" + ioException.getMessage(), ioException); } } return minFileName; }