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

The following are Jave code examples for showing how to use getName() of the org.apache.commons.io.FilenameUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: restheart-java-client   File: RestHeartBasicClientApiTest.java   View Source Code Vote up 8 votes
@Test
public void testGetDocById() throws MalformedURLException {
    createCollection();
    RestHeartClientResponse restHeartClientResponse = insertDocInDB();
    String documentUrlLocation = restHeartClientResponse.getDocumentUrlLocation();
    URL url = new URL(documentUrlLocation);
    String idCreate = FilenameUtils.getName(url.getPath());

    RestHeartClientResponse response = api.getDocumentById(dbName, collName, idCreate);
    Assert.assertNotNull("Response is null", response);

    JsonObject responseObject = response.getResponseObject();
    Assert.assertNotNull("Json object response is null", responseObject);

    String idRes = responseObject.get("_id").getAsJsonObject().get("$oid").getAsString();
    Assert.assertEquals("Id's do not match", idCreate, idRes);

    LOGGER.info(GsonUtils.toJson(response.getResponseObject()));
}
 
Example 2
Project: devops-cstack   File: AbstractModuleControllerTestIT.java   View Source Code Vote up 8 votes
@Test
public void test_runScript() throws Exception {
    requestAddModule();
    String filename = FilenameUtils.getName(testScriptPath);
    if (filename == null) {
        logger.info("No script found - test escape");
    } else {
        MockMultipartFile file = new MockMultipartFile(
                "file",
                filename,
                "application/sql",
                new FileInputStream(testScriptPath));

        String genericModule = NamingUtils.getContainerName(applicationName, module, "johndoe");

        ResultActions result = mockMvc.perform(
                fileUpload("/module/{moduleName}/run-script", genericModule)
                        .file(file)
                        .session(session)
                        .contentType(MediaType.MULTIPART_FORM_DATA))
                .andDo(print());
        result.andExpect(status().isOk());
    }
}
 
Example 3
Project: url-to-google-drive   File: DriveUploaderBuilder.java   View Source Code Vote up 6 votes
private String findFileName(String contentDisposition) {

		if (contentDisposition != null)
			try {
				Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);

				if (matcher.find()) {
					String match = matcher.group(1);

					if (match != null && !match.equals("")) {
						match = URLDecoder.decode(match, "UTF-8");
						return match;
					}
				}

			} catch (IllegalStateException ex) {
				// cannot find filename using content disposition http header.
				// Use url to find filename;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		return FilenameUtils.getName(downloadFileInfo.getUploadUrl().getPath());
	}
 
Example 4
Project: osc-core   File: ImportApplianceSoftwareVersionService.java   View Source Code Vote up 6 votes
private File loadMetadataFile(File[] tmpFolderList) throws VmidcBrokerValidationException {
    File metaDataFile = null;
    for (File tmpFolderFile : tmpFolderList) {
        String fileName = FilenameUtils.getName(tmpFolderFile.getName());
        if (fileName.equals(ImageMetadata.META_FILE_NAME)) {
            metaDataFile = tmpFolderFile;
            break;
        }
    }

    if (metaDataFile != null) {
        return metaDataFile;
    } else {
        throw new VmidcBrokerValidationException(
                VmidcMessages.getString(VmidcMessages_.UPLOAD_APPLIANCE_INVALID_METAFILE, ImageMetadata.META_FILE_NAME)
                );
    }
}
 
Example 5
Project: satisfy   File: BaseFileUploadSteps.java   View Source Code Vote up 6 votes
private File getFileFromResourcesByFilePath(String filePath) {
    URL url = BaseFileUploadSteps.class.getResource(filePath);
    String file = url.getFile();
    if (file.contains(".jar!/")) {
        try {
            File tempFile = new File(Files.createTempDir(), FilenameUtils
                    .getName(url.getFile()));
            IOUtils.copy(url.openStream(), org.apache.commons.io
                    .FileUtils.openOutputStream(tempFile));
            return tempFile;
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    return new File(file);
}
 
Example 6
Project: generator-thundr-gae-react   File: AttachmentService.java   View Source Code Vote up 5 votes
/**
 * Get a signed url to view an attachment. The url will last 24 hours. The file name portion of the id is url escaped internally.
 *
 * @param id The id of the attachment.
 * @return Url
 */
public String getDownloadUrl(String id) {
    String filename = FilenameUtils.getName(id);
    String path = FilenameUtils.getFullPath(id);
    String escapedFullPath = FilenameUtils.concat(path, UrlEscapers.urlFragmentEscaper().escape(filename));
    return cloudStorage.generateSignedUrl(gcsDefaultBucket, escapedFullPath, DEFAULT_LINK_EXPIRY_DURATION);
}
 
Example 7
Project: GitHub   File: Jsonschema2Pojo.java   View Source Code Vote up 5 votes
private static String getNodeName(URL file, GenerationConfig config) {
    try {
        String fileName = FilenameUtils.getName(URLDecoder.decode(file.toString(), "UTF-8"));
        String[] extensions = config.getFileExtensions();
        boolean extensionRemoved = false;
        for (int i = 0; i < extensions.length; i++) {
            String extension = extensions[i];
            if (extension.length() == 0) {
                continue;
            }
            if (!extension.startsWith(".")) {
                extension = "." + extension;
            }
            if (fileName.endsWith(extension)) {
                fileName = removeEnd(fileName, extension);
                extensionRemoved = true;
                break;
            }
        }
        if (!extensionRemoved) {
            fileName = FilenameUtils.getBaseName(fileName);
        }
        return fileName;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", file.toString()), e);
    }

}
 
Example 8
Project: restheart-java-client   File: RestHeartBasicClientApiTest.java   View Source Code Vote up 5 votes
@Test
public void testDeleteDocById() throws MalformedURLException {
    createCollection();
    RestHeartClientResponse restHeartClientResponse = insertDocInDB();
    String documentUrlLocation = restHeartClientResponse.getDocumentUrlLocation();
    URL url = new URL(documentUrlLocation);
    String id = FilenameUtils.getName(url.getPath());

    RestHeartClientResponse deleteDocByIdResponse = api.deleteDocumentById(dbName, collName, id);
    Assert.assertEquals(
        "response not as expected, Code" + deleteDocByIdResponse.getStatusCode() + ", ETag-"
            + deleteDocByIdResponse.getEtag(), 204,
        deleteDocByIdResponse.getStatusCode());
}
 
Example 9
Project: main_carauto_board   File: AudioController.java   View Source Code Vote up 5 votes
private void readFileAndSetInitialStateForAudioItem(final File singleFileFromOpenedDialog, final VBox vboxPlaylist)
        throws IOException {
    final AudioItem audioItem = new AudioItem();
    final String openDialogFilePath = singleFileFromOpenedDialog.getPath();
    LOGGER.info("Now is opening: " + openDialogFilePath);
    final String baseName = FilenameUtils.getName(openDialogFilePath);
    final String path = singleFileFromOpenedDialog.toURI().toASCIIString();
    final Media mediaSound = new Media(path);
    LOGGER.info("MediaSound " + mediaSound.getSource() + " opened");
    final MediaPlayer mediaPlayer = new MediaPlayer(mediaSound);
    final MediaView mediaView = new MediaView(mediaPlayer);

    setupTimeSliderDependsOnMediaPlayer(audioItem.getSlider(), audioItem.getLabel_for_time(), mediaPlayer);

    audioItem.getLabel_for_name().setText(baseName);
    audioItem.getChildren().addAll(mediaView);

    audioItem.getStop().setOnAction(action -> {
        mediaPlayer.stop();
        alreadyPlaying = false;
    });

    audioItem.getPlay().setOnAction(action -> {
        if (!alreadyPlaying) {
            final String formatted = formatDurationForMedia(mediaSound.getDuration());
            audioItem.getLabel_for_time().setText(formatted);
            mediaPlayer.play();
            alreadyPlaying = true;
        }
    });

    vboxPlaylist.getChildren().add(audioItem);

}
 
Example 10
Project: airsonic   File: MediaFile.java   View Source Code Vote up 5 votes
public String getName() {
    if (isFile()) {
        return title != null ? title : FilenameUtils.getBaseName(path);
    }

    return FilenameUtils.getName(path);
}
 
Example 11
Project: java-natives   File: NativeLibrary.java   View Source Code Vote up 5 votes
private File extractNativeLibraries(final File nativesDirectory, final String libraryPath) {
  final URL libraryUrl = Thread.currentThread().getContextClassLoader().getResource(libraryPath);
  if (libraryUrl == null) {
    throw new IllegalArgumentException(
        String.format("Unable to find native binary %s for library %s", libraryPath, key));
  }
  final String libraryName;
  libraryName = FilenameUtils.getName(libraryPath);
  final File libraryFile = new File(nativesDirectory, libraryName);
  libraryFile.getParentFile().mkdirs();
  try {
    final URLConnection urlConnection = libraryUrl.openConnection();
    try (final InputStream inputStream = urlConnection.getInputStream()) {
      try (final OutputStream outputStream =
          new BufferedOutputStream(new FileOutputStream(libraryFile))) {
        IOUtils.copy(inputStream, outputStream);
      }
    }
  } catch (final Exception exception) {
    throw new RuntimeException(exception);
  }
  if (deleteOnExit) {
    libraryFile.deleteOnExit();
  }
  // TODO make accessible for linux and mac
  return libraryFile;
}
 
Example 12
Project: osc-core   File: ImportPluginService.java   View Source Code Vote up 5 votes
private void validate(EntityManager em, ImportFileRequest request, File tmpUploadFolder) throws Exception {

        if (!ServerUtil.isEnoughSpace()) {
            throw new VmidcException(VmidcMessages.getString("upload.plugin.nospace"));
        }

		File[] tmpFolderList = FileUtil.getFileListFromDirectory(tmpUploadFolder.getPath());
        for (File tmpFolderFile : tmpFolderList) {
            String fileName = FilenameUtils.getName(tmpFolderFile.getName());
            if (FilenameUtils.getExtension(fileName).equals("bar")) {
                this.barFile = tmpFolderFile;
                break;
            }
        }

        if (this.barFile == null) {
            throw new VmidcBrokerValidationException(
                    "Invalid upload folder. Should contain single .bar file.");
        }

        try (JarFile jar = new JarFile(this.barFile)) {
			Manifest manifest = jar.getManifest();
			Attributes attributes = manifest.getMainAttributes();
			String symbolicName = attributes.getValue("Deployment-SymbolicName");

			if (symbolicName == null) {
				throw new VmidcBrokerValidationException("uploaded file does not contain Deployment-SymbolicName: " + this.barFile);
			}

			this.deploymentName = symbolicName + ".bar";
        }

    }
 
Example 13
Project: cyberduck   File: PathNormalizer.java   View Source Code Vote up 5 votes
public static String name(final String path) {
    final String normalized = normalize(path, true);
    if(String.valueOf(Path.DELIMITER).equals(normalized)) {
        return path;
    }
    return FilenameUtils.getName(normalized);
}
 
Example 14
Project: OneClient   File: CurseModInstaller.java   View Source Code Vote up 5 votes
@Override
public String getName() {
	if (fileData != null) {
		name = FilenameUtils.getName(fileData.getURL());
	}
	return super.getName();
}
 
Example 15
Project: atlas   File: BetterZip.java   View Source Code Vote up 4 votes
public static File extractFile(File zipFile, String path, File destDir) {

        destDir.mkdirs();

        new File(destDir, path).delete();

        //unzip -j taobao-android-debug.apk  res/drawable/abc_wb_textfield_cdf.jpg -d .
        boolean success = CmdExecutor.execute("", "unzip", "-o", "-j", zipFile.getAbsolutePath(), path, "-d",
                                              destDir.getAbsolutePath());

        if (success) {
            return new File(destDir, FilenameUtils.getName(path));
        }

        return ZipUtils.extractZipFileToFolder(zipFile, path, destDir);
    }
 
Example 16
Project: NGB-master   File: BedManager.java   View Source Code Vote up 4 votes
private BedFile registerBedFileFromFile(final IndexedFileRegistrationRequest request)
    throws HistogramReadingException, IOException {

    Reference reference = referenceGenomeManager.loadReferenceGenome(request.getReferenceId());

    BiologicalDataItemResourceType resourceType = BiologicalDataItemResourceType.translateRequestType(
        request.getType());
    String fileName = FilenameUtils.getName(request.getPath());

    final BedFile bedFile = new BedFile();
    bedFile.setId(bedFileManager.createBedFileId());
    bedFile.setCompressed(resourceType == BiologicalDataItemResourceType.FILE && IOHelper.isGZIPFile(fileName));
    bedFile.setPath(request.getPath());
    bedFile.setName(request.getName() != null ? request.getName() : fileName);
    bedFile.setType(resourceType); // For now we're working only with files
    bedFile.setCreatedDate(new Date());
    bedFile.setCreatedBy(AuthUtils.getCurrentUserId());
    bedFile.setReferenceId(reference.getId());

    long bedId = bedFile.getId();

    try {
        biologicalDataItemManager.createBiologicalDataItem(bedFile);
        bedFile.setBioDataItemId(bedFile.getId());
        bedFile.setId(bedId);

        if (StringUtils.isNotBlank(request.getIndexPath())) {
            final BiologicalDataItem indexItem = new BiologicalDataItem();
            indexItem.setCreatedDate(new Date());
            indexItem.setPath(request.getIndexPath());
            indexItem.setFormat(BiologicalDataItemFormat.BED_INDEX);
            indexItem.setType(BiologicalDataItemResourceType
                    .translateRequestType(request.getIndexType()));
            indexItem.setName(bedFile.getName() + "_index");
            indexItem.setCreatedBy(AuthUtils.getCurrentUserId());

            bedFile.setIndex(indexItem);
        } else {
            Assert.isTrue(resourceType == BiologicalDataItemResourceType.FILE,
                    "Auto indexing is supported only for FILE type requests");
            fileManager.makeBedDir(bedFile.getId(), AuthUtils.getCurrentUserId());
            fileManager.makeBedIndex(bedFile);
        }

        double time1 = Utils.getSystemTimeMilliseconds();
        if (resourceType == BiologicalDataItemResourceType.FILE) {
            createHistogram(bedFile);
        }
        double time2 = Utils.getSystemTimeMilliseconds();
        LOG.debug("Making BED histogram took {} ms", time2 - time1);
        LOG.info(getMessage(MessagesConstants.INFO_GENE_REGISTER, bedFile.getId(),
                bedFile.getPath()));
        biologicalDataItemManager.createBiologicalDataItem(bedFile.getIndex());
        bedFileManager.createBedFile(bedFile);
        return bedFile;
    } finally {
        if (bedFile.getId() != null && bedFile.getBioDataItemId() != null
                && bedFileManager.loadBedFile(bedFile.getId()) == null) {
            biologicalDataItemManager.deleteBiologicalDataItem(bedFile.getBioDataItemId());
        }
    }
}
 
Example 17
Project: cyberduck   File: Local.java   View Source Code Vote up 4 votes
/**
 * @return The last path component.
 */
@Override
public String getName() {
    return FilenameUtils.getName(path);
}
 
Example 18
Project: OneClient   File: FileUtil.java   View Source Code Vote up 4 votes
public static File extractFromURL(String url, File location) {
	File zipDownload = new File(location, FilenameUtils.getName(url));
	File file = downloadFromURL(url, zipDownload);
	File directory = new File(location, FilenameUtils.getBaseName(url));
	return extract(file, directory);
}
 
Example 19
Project: OneClient   File: FileUtil.java   View Source Code Vote up 4 votes
public static File downloadToName(String url, File location) {
	String name = FilenameUtils.getName(url);
	return downloadFromURL(url.replace(" ", "%20"), new File(location, name));
}
 
Example 20
Project: NGB-master   File: VcfManager.java   View Source Code Vote up 4 votes
private VcfFile createVcfFile(final IndexedFileRegistrationRequest request,
        final FeatureReader<VariantContext> reader) {
    VcfFile vcfFile;
    vcfFile = new VcfFile();

    VCFHeader header = (VCFHeader) reader.getHeader();
    Map<String, Integer> sampleMap = header.getSampleNameToOffset();

    if (sampleMap != null && !sampleMap.isEmpty()) {
        List<VcfSample> samples = sampleMap.entrySet().stream().map(e -> new VcfSample(e.getKey(), e.getValue()))
                .collect(Collectors.toList());
        vcfFile.setSamples(samples);
    }

    BiologicalDataItemResourceType resourceType = BiologicalDataItemResourceType.translateRequestType(
        request.getType());
    String fileName = FilenameUtils.getName(request.getPath());

    vcfFile.setCompressed(resourceType == BiologicalDataItemResourceType.FILE && IOHelper.isGZIPFile(fileName));
    vcfFile.setName(request.getName() != null ? request.getName() : fileName);
    vcfFile.setId(vcfFileManager.createVcfFileId());
    vcfFile.setPath(request.getPath());
    vcfFile.setType(resourceType);
    vcfFile.setCreatedDate(new Date());
    vcfFile.setCreatedBy(AuthUtils.getCurrentUserId());
    vcfFile.setReferenceId(request.getReferenceId());

    if (StringUtils.isNotBlank(request.getIndexPath())) {
        BiologicalDataItem indexItem = new BiologicalDataItem();
        indexItem.setCreatedDate(new Date());
        indexItem.setPath(request.getIndexPath());
        indexItem.setFormat(BiologicalDataItemFormat.VCF_INDEX);
        indexItem.setType(BiologicalDataItemResourceType.translateRequestType(request.getIndexType()));
        indexItem.setName(vcfFile.getName() + "_index");
        indexItem.setCreatedBy(AuthUtils.getCurrentUserId());

        vcfFile.setIndex(indexItem);
    }
    long vcfId = vcfFile.getId();
    biologicalDataItemManager.createBiologicalDataItem(vcfFile);
    vcfFile.setBioDataItemId(vcfFile.getId());
    vcfFile.setId(vcfId);
    LOGGER.info(getMessage(MessagesConstants.INFO_GENE_REGISTER, vcfFile.getId(), vcfFile.getPath()));
    return vcfFile;
}