Java Code Examples for org.apache.commons.io.FilenameUtils#getBaseName()

The following examples show how to use org.apache.commons.io.FilenameUtils#getBaseName() . 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: DecryptOnePm.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
private String patchTargetFilenameIfNeeded(String sourceFileStr, String targetFilename) {
	if (StringUtils.hasText(targetFilename)) {
		if (targetFilename.contains("/")) {
			targetFilename = targetFilename.substring(targetFilename.lastIndexOf("/") + 1);
		} else if (targetFilename.contains("\\")) {
			targetFilename = targetFilename.substring(targetFilename.lastIndexOf("\\") + 1);
		}
	}

	if (!StringUtils.hasText(targetFilename)) {
		targetFilename = FilenameUtils.getBaseName(sourceFileStr);
		log.warn("Wasn't able to find initial file name from " + sourceFileStr + ". Will use this name: "
				+ targetFilename);
	}
	return targetFilename;
}
 
Example 2
Source File: BackupStoragePathMaker.java    From zstack with Apache License 2.0 6 votes vote down vote up
private static String makeFilename(String installPath, String format) {
    File f = new File(installPath);
    String baseName = FilenameUtils.getBaseName(f.getAbsolutePath());
    String suffix = FilenameUtils.getExtension(f.getAbsolutePath());
    if (!knownImageExtensions.contains(baseName)) {
        if (format.equals(ImageMediaType.RootVolumeTemplate.toString())) {
            suffix = "template";
        } else if (format.equals(ImageMediaType.ISO.toString())) {
            suffix = "iso";
        } else if (format.equals(ImageMediaType.DataVolumeTemplate.toString())) {
            suffix = "volume";
        }
    }

    return String.format("%s.%s", baseName, suffix);
}
 
Example 3
Source File: DescriptorsMonitor.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void onFileDelete(File file) {
  // For simple descriptors, we need to make sure to delete any corresponding full topology descriptors to trigger undeployment
  for (String ext : DefaultTopologyService.SUPPORTED_TOPOLOGY_FILE_EXTENSIONS) {
    File topologyFile = new File(topologiesDir, FilenameUtils.getBaseName(file.getName()) + "." + ext);
    if (topologyFile.exists()) {
      LOG.deletingTopologyForDescriptorDeletion(topologyFile.getName(), file.getName());
      topologyFile.delete();
    }
  }

  final String normalizedFilePath = FilenameUtils.normalize(file.getAbsolutePath());
  String reference = null;
  for (Map.Entry<String, List<String>> entry : providerConfigReferences.entrySet()) {
    if (entry.getValue().contains(normalizedFilePath)) {
      reference = entry.getKey();
      break;
    }
  }

  if (reference != null) {
    providerConfigReferences.get(reference).remove(normalizedFilePath);
    LOG.removedProviderConfigurationReference(normalizedFilePath, reference);
  }
}
 
Example 4
Source File: CrawlerTest.java    From jbake with MIT License 6 votes vote down vote up
@Test
public void renderWithPrettyUrls() throws Exception {

    config.setUriWithoutExtension(true);
    config.setPrefixForUriWithoutExtension("/blog");

    Crawler crawler = new Crawler(db, config);
    crawler.crawl();

    Assert.assertEquals(4, db.getDocumentCount("post"));
    Assert.assertEquals(3, db.getDocumentCount("page"));

    DocumentList documents = db.getPublishedPosts();

    for (Map<String, Object> model : documents) {
        String noExtensionUri = "blog/\\d{4}/" + FilenameUtils.getBaseName((String) model.get("file")) + "/";

        Assert.assertThat(model.get("noExtensionUri"), RegexMatcher.matches(noExtensionUri));
        Assert.assertThat(model.get("uri"), RegexMatcher.matches(noExtensionUri + "index\\.html"));

        assertThat(model).containsEntry("rootpath", "../../../");
    }
}
 
Example 5
Source File: GISJob.java    From datasync with MIT License 5 votes vote down vote up
private static List<String> getLayerListFromShapefile(String filePath) throws IOException {
    try (ZipFile zipFile = new ZipFile(filePath)) {
        List<String> layers = new ArrayList<>();
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (FilenameUtils.getExtension(entry.getName()).equals("shp")) {
                String layerName = FilenameUtils.getBaseName(entry.getName());
                layers.add(layerName);
            }
        }

        return layers;
    }
}
 
Example 6
Source File: ThemeConstantsRepository.java    From cuba with Apache License 2.0 5 votes vote down vote up
public String parseThemeName(String fileName) {
    String name = FilenameUtils.getBaseName(fileName);
    if (name.endsWith("-theme")) {
        int dashIndex = name.lastIndexOf("-theme");
        return name.substring(0, dashIndex);
    } else {
        return name;
    }
}
 
Example 7
Source File: LocalDocReader.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check existence of PAGE XML or txt files and return tree map of (fake) image filenames and files
 * @param baseDir folder in which images should be found
 * @return
 * @throws IOException
 */
public static TreeMap<String, File> createDummyImgFiles(File baseDir) throws IOException {
	
	//for syncing page file: the base directory can also be directly the page folder		
	File xmlDir = (baseDir.getName().equals(LocalDocConst.PAGE_FILE_SUB_FOLDER)) ? baseDir : getPageXmlInputDir(baseDir);
	
	//File xmlDir = getPageXmlInputDir(baseDir);
	File txtDir = getTxtInputDir(baseDir);
	
	// check whether xml directory contains files, if not, assume txt directory has content
	File workingDir = (xmlDir==null || !xmlDir.exists())?txtDir:xmlDir;
	File[] fileArr = workingDir.listFiles();
	
	//Use number sensitive ordering so that:		
	//img1 -> img2 -> ... -> img9 -> img10 -> etc.
	//try Java 8: http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--
	Comparator<String> naturalOrderComp = new NaturalOrderComparator();
	TreeMap<String, File> pageMap = new TreeMap<>(naturalOrderComp);

	if (fileArr == null || fileArr.length == 0){
		if (!workingDir.exists()) {
			logger.debug("Could not find directory " +workingDir.getName() + " holding files for synchronisation!");
		}

		logger.debug("Folder " + workingDir.getAbsolutePath() + " does not contain any files!");
		logger.debug("No PAGE XML nor txt files found - returning empty TreeMap");
		return pageMap;
	}
	
	for (File page : fileArr) {
		final String pageName = FilenameUtils.getBaseName(page.getName());
		if (!pageMap.containsKey(pageName)) {
			//new page. add this xml
			File img = new File(baseDir, pageName+".png");
			pageMap.put(pageName, img);
			logger.debug(pageName + ": created fake image " + img.getName());
		} 
	}
	return pageMap;
}
 
Example 8
Source File: TemplateRecordConfigurationCreatingConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the output writer for the configuration yaml files.
 *
 * @param documentSourceName the document source name
 * @return the writer
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Writer createOutputWriter(final String documentSourceName) throws IOException {
  Path directoryPath = Paths.get(outputDirectory);
  if (!directoryPath.toFile().exists()) {
    Files.createDirectories(directoryPath);
  }
  String baseName = FilenameUtils.getBaseName(documentSourceName);
  Path outputFilePath = directoryPath.resolve(baseName + ".yaml");

  if (outputFilePath.toFile().exists()) {
    getMonitor().warn("Overwriting existing output properties file {}", outputFilePath);
  }
  return Files.newBufferedWriter(outputFilePath, StandardCharsets.UTF_8);
}
 
Example 9
Source File: NioFileCopierWithProgessMeterTestUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static Path getSourcePathFromPseudoUrl(final String source) {
    final Path sourcePath;
    if (source.startsWith("GS:")) {
        sourcePath = IOUtils.getPath(BaseTest.getGCPTestInputPath() + source.substring(3));
    }
    else {
        final String sourceBaseName = FilenameUtils.getBaseName(source);
        final String sourceExtension = FilenameUtils.getExtension(source);
        sourcePath = IOUtils.createTempFile(sourceBaseName, sourceExtension).toPath();
    }
    return sourcePath;
}
 
Example 10
Source File: FileTemplateRecordConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an output writer for a new file in the configured output directory, with appropriate
 * name and extension.
 *
 * <p>Note: this overwrites existing files (warning if it does so).
 *
 * @param documentSourceName the document source name
 * @return the writer
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Writer createOutputWriter(final String documentSourceName) throws IOException {
  Path directoryPath = Paths.get(outputDirectory);
  if (!directoryPath.toFile().exists()) {
    Files.createDirectories(directoryPath);
  }
  String baseName = FilenameUtils.getBaseName(documentSourceName);
  Path outputFilePath = directoryPath.resolve(baseName + "." + outputFileExtension);

  if (outputFilePath.toFile().exists()) {
    getMonitor().warn("Overwriting existing output properties file {}", outputFilePath);
  }
  return Files.newBufferedWriter(outputFilePath, StandardCharsets.UTF_8);
}
 
Example 11
Source File: FileNameDialog.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
public static String[] makeFileNames(final String baseName) {
  final String[] result = new String[4];
  for (int i = 0; i < 4; i++) {
    result[i] = FilenameUtils.getBaseName(baseName) + '_' + i + '.' +
        FilenameUtils.getExtension(baseName);
  }
  return result;
}
 
Example 12
Source File: GnuDemanglerNativeProcess.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void checkForError(String[] command) throws IOException {

		//
		// We do not want to read the error stream in the happy path case, as that will block.
		// Send a test string over and read the result.   If the test string is blank, then
		// there was an error.
		//
		String testResult = doDemangle("test");
		if (!StringUtils.isBlank(testResult)) {
			return;
		}

		InputStream err = process.getErrorStream();
		String error = null;
		try {
			List<String> errorLines = IOUtils.readLines(err, Charset.defaultCharset());
			error = StringUtils.join(errorLines, '\n');
		}
		catch (IOException e) {
			throw new IOException("Unable to read process error stream: ", e);
		}

		if (StringUtils.isBlank(error)) {
			return;
		}

		String executable = command[0];
		String baseName = FilenameUtils.getBaseName(executable);
		command[0] = baseName;

		// cleanup full path, as it is ugly in the error message
		error = error.replace(executable, "");
		throw new IOException("Error starting demangler with command: '" +
			Arrays.toString(command) + "' " + error);
	}
 
Example 13
Source File: FileFixture.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
private String findNameForFile(String fileFromWiki) {
    String basename = FilenameUtils.getBaseName(fileFromWiki);
    String target = getFullName(basename);
    ensureParentExists(target);
    String targetExt = FilenameUtils.getExtension(fileFromWiki);

    return FileUtil.determineFilename(target, targetExt).getAbsolutePath();
}
 
Example 14
Source File: MediaFile.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
public String getName() {
    if (isFile()) {
        return title != null ? title : FilenameUtils.getBaseName(path);
    }

    return FilenameUtils.getName(path);
}
 
Example 15
Source File: InputFile.java    From JavaTelegramBot-API with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create an InputFile object based on an external URL to be sent within a SendableMessage
 *
 * @param url The URL of the file you want this InputFile to point to
 */
public InputFile(URL url) {

    File file = TelegramBot.getFileManager().getFile(url);
    String extension = null;
    if (file == null) {
        try {
            String stringifiedUrl = url.toExternalForm();
            HttpResponse<InputStream> response = Unirest.get(stringifiedUrl).asBinary();
            extension = FileExtension.getByMimeType(response.getHeaders().getFirst("content-type"));
            if (extension == null) {
                extension = stringifiedUrl.substring(stringifiedUrl.lastIndexOf('.') + 1);

                int variableIndex = extension.indexOf('?');
                if (variableIndex > 0) extension = extension.substring(0, variableIndex);

                if (extension.length() > 4) {
                    extension = null; // Default to .tmp if there was no valid extension
                }
            }
            file = File.createTempFile("jtb-" + System.currentTimeMillis(), "." + extension, FileManager.getTemporaryFolder());
            file.deleteOnExit();
            TelegramBot.getFileManager().cacheUrl(url, file);
            Files.copy(response.getRawBody(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (UnirestException | IOException ex) {
            ex.printStackTrace();
        }
    }
    this.fileName = FilenameUtils.getBaseName(url.toString()) + "." + extension;
    this.file = file;
    this.fileID = TelegramBot.getFileManager().getFileID(file);
    this.inputStream = null;
}
 
Example 16
Source File: BatchCommand.java    From walle with Apache License 2.0 5 votes vote down vote up
private void generateChannelApk(final File inputFile, final File outputDir, final String channel) {
    final String name = FilenameUtils.getBaseName(inputFile.getName());
    final String extension = FilenameUtils.getExtension(inputFile.getName());
    final String newName = name + "_" + channel + "." + extension;
    final File channelApk = new File(outputDir, newName);
    try {
        FileUtils.copyFile(inputFile, channelApk);
        ChannelWriter.put(channelApk, channel, extraInfo);
    } catch (IOException | SignatureNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: MatrixConverter.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
public MatrixConverter(File inputMatrix) throws IOException {
	this.inputFile = inputMatrix;
	this.directory = inputMatrix.getParent();
	this.baseName = FilenameUtils.getBaseName(inputMatrix.getName());
	this.binaryOutputFile = new BinaryFile(directory + "/" + baseName + ".dat", BinaryFile.W);
	this.snpFile = new TextFile(directory + "/" + baseName + "-RowNames.txt.gz", TextFile.W);
	this.columnFile = new TextFile(directory + "/" + baseName + "-ColNames.txt.gz", TextFile.W);
	
	snpFile.writeln("SNP\tAlleles\tMinorAllele\tAlleleAssessed\tNrCalled\tMaf\tHWE\tCallRate");
	
}
 
Example 18
Source File: Common.java    From pdf-extract with GNU General Public License v3.0 4 votes vote down vote up
public String getBaseName(String filepath) {
	return FilenameUtils.getBaseName(filepath);
}
 
Example 19
Source File: AbstractFilePlugin.java    From zxpoly with GNU General Public License v3.0 4 votes vote down vote up
protected static String addNumberToFileName(final String name, final int number) {
  String base = FilenameUtils.getBaseName(name);
  final String ext = FilenameUtils.getExtension(name);
  return base + number + '.' + ext;
}
 
Example 20
Source File: UcteExporterTest.java    From powsybl-core with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Utility method to load a network file from resource directory without calling
 * @param filePath path of the file relative to resources directory
 * @return imported network
 */
private static Network loadNetworkFromResourceFile(String filePath) {
    ReadOnlyDataSource dataSource = new ResourceDataSource(FilenameUtils.getBaseName(filePath), new ResourceSet(FilenameUtils.getPath(filePath), FilenameUtils.getName(filePath)));
    return new UcteImporter().importData(dataSource, NetworkFactory.findDefault(), null);
}