Example usage for org.apache.commons.io FilenameUtils getName

List of usage examples for org.apache.commons.io FilenameUtils getName

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getName.

Prototype

public static String getName(String filename) 

Source Link

Document

Gets the name minus the path from a full filename.

Usage

From source file:net.bpelunit.framework.control.deploy.ode.ODEDeployer.java

private String getArchiveLocation(String pathToTest) {
    String pathToArchive = FilenameUtils.concat(pathToTest, FilenameUtils.getFullPath(fArchive));
    String archiveName = FilenameUtils.getName(fArchive);
    return FilenameUtils.concat(pathToArchive, archiveName);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

private void uploadSourceDocument(ZipFile zip, ZipEntry entry, Project project, User user, String aFileType)
        throws IOException, UIMAException {
    String fileName = FilenameUtils.getName(entry.toString());

    InputStream zipStream = zip.getInputStream(entry);
    SourceDocument document = new SourceDocument();
    document.setName(fileName);//from   ww w  .  ja va2 s . c o m
    document.setProject(project);
    document.setFormat(aFileType);
    // Meta data entry to the database
    projectRepository.createSourceDocument(document, user);
    // Import source document to the project repository folder
    projectRepository.uploadSourceDocument(zipStream, document);
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.DownloadItem.java

public String getFileName() throws MalformedURLException {
    if (contentDispositionFilename != null)
        return contentDispositionFilename;
    if (uri == null)
        return null;
    String urlFile = uri.toURL().getPath();
    if (urlFile == null)
        return null;
    return FilenameUtils.getName(urlFile);
}

From source file:de.mpg.imeji.logic.item.ItemService.java

/**
 * Create an {@link Item} with an external {@link File} according to its URL
 *
 * @param item//from   w  ww  .  ja va 2 s . c  om
 * @param c
 * @param externalFileUrl
 * @param download
 * @param user
 * @return
 * @throws IOException
 * @throws ImejiException
 */
public Item createWithExternalFile(Item item, CollectionImeji c, String externalFileUrl, String filename,
        boolean download, User user) throws ImejiException {
    final String origName = FilenameUtils.getName(externalFileUrl);
    if ("".equals(filename) || filename == null) {
        filename = origName;
    }
    // Filename extension will be added if not provided.
    // Will not be appended if it is the same value from original external reference again
    // Original external reference will be appended to the provided extension in addition
    else if (FilenameUtils.getExtension(filename).equals("")
            || !FilenameUtils.getExtension(filename).equals(FilenameUtils.getExtension(origName))) {
        filename = filename + "." + FilenameUtils.getExtension(origName);
    }

    if (filename == null || filename.equals("")) {
        throw new BadRequestException(
                "Could not derive the filename. Please provide the filename with the request!");
    }

    if (externalFileUrl == null || externalFileUrl.equals("")) {
        throw new BadRequestException("Please provide fetchUrl or referenceUrl with the request!");
    }
    if (item == null) {
        item = ImejiFactory.newItem(c);
    }
    if (download) {
        // download the file in storage
        final File tmp = readFile(externalFileUrl);
        item = createWithFile(item, tmp, filename, c, user);
    } else {
        item.setFilename(filename);
        item.setFiletype(StorageUtils.getMimeType(FilenameUtils.getExtension(externalFileUrl)));
        item = create(item, c, user);
        new ContentService().create(item, externalFileUrl, user);
    }
    return item;
}

From source file:com.abiquo.am.services.ovfformat.TemplateFromOVFEnvelope.java

/**
 * TODO re-DOC <br>/*from   w  w  w .  j a  v  a  2  s .  com*/
 * REQUIRE THE OVFID IS PLACED ON A REMOTE LOCATION (WARINING on generation)<BR>
 * Creates a list of VirtualInfo relative to the VirtualDisk (from the disk section) and
 * requirements (from the VirtualHardwareSection) contained on the provided OVF envelope. Used
 * to add VirtualImage on database once an OVFPackage completes its download. No duplicated Disk
 * are returned.
 * 
 * @param ovfDescription, the OVF description of the required OVF package.
 * @return an array containing all the DiskInfo properties and requirements.
 * @throws RepositoryException, if the envelope do not contain the required info to get
 *             VirtualDisk information.
 **/
public static TemplateDto createTemplateDto(final String ovfId, final EnvelopeType envelope)
        // TODO String userID, String category
        throws AMException {

    TemplateDto diskInfo = null;

    Map<String, VirtualDiskDescType> diskIdToDiskFormat = new HashMap<String, VirtualDiskDescType>();
    Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();
    Map<String, List<String>> diskIdToVSs = new HashMap<String, List<String>>();
    Map<String, TemplateDto> requiredByVSs = new HashMap<String, TemplateDto>();
    DiskSectionType diskSectionType;

    try {
        ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

        ProductSectionType product = OVFEnvelopeUtils.getSection(contentType, ProductSectionType.class);

        String description = null;
        if (product.getInfo() != null && product.getInfo().getValue() != null) {
            description = product.getInfo().getValue();
        }

        String categoryName = null;
        if (product.getOtherAttributes().containsKey(new QName("CategoryName"))) {
            categoryName = product.getOtherAttributes().get(new QName("CategoryName"));
        }

        String iconPath = getIconPath(product, fileIdToFileType, ovfId);

        diskSectionType = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

        for (FileType fileType : envelope.getReferences().getFile()) {
            fileIdToFileType.put(fileType.getId(), fileType);
        }
        // Create a hash
        for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk()) {
            diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
        }

        if (contentType instanceof VirtualSystemType) {

            VirtualSystemType vs = (VirtualSystemType) contentType;
            TemplateDto req = getDiskInfo(vs, diskIdToDiskFormat, diskIdToVSs);

            requiredByVSs.put(vs.getId(), req);
        } else if (contentType instanceof VirtualSystemCollectionType) {
            List<VirtualSystemType> virtualSystems = OVFEnvelopeUtils
                    .getVirtualSystems((VirtualSystemCollectionType) contentType);

            for (VirtualSystemType virtualSystemType : virtualSystems) {
                TemplateDto req = getDiskInfo(virtualSystemType, diskIdToDiskFormat, diskIdToVSs);

                requiredByVSs.put(virtualSystemType.getId(), req);
            }
        }

        for (VirtualDiskDescType diskDescType : diskIdToDiskFormat.values()) {

            String diskId = diskDescType.getDiskId();
            String fileId = diskDescType.getFileRef();

            if (!fileIdToFileType.containsKey(fileId)) {
                String msg = "File Id [" + fileId + "] not found on the ReferencesSection";
                throw new IdNotFoundException(msg);
            }

            FileType file = fileIdToFileType.get(fileId);
            final String filePath = file.getHref();
            final Long fileSize = file.getSize().longValue();

            String format = diskDescType.getFormat(); // XXX using the same format on the OVF
            // disk

            if (!diskIdToVSs.containsKey(diskId)) {
                throw new IdNotFoundException("Any virtualSystem is using diskId[" + diskId + "]"); // XXX warning ??
            }

            if (diskIdToVSs.size() != 1) {
                throw new AMException(AMError.TEMPLATE_INVALID, String
                        .format("There are more than one virtual system on the OVF Envelope [%s]", ovfId));
            }

            for (String vssName : diskIdToVSs.get(diskId)) {
                diskInfo = new TemplateDto();
                diskInfo.setName(vssName);
                diskInfo.setUrl(ovfId);

                DiskFormat diskFormat = DiskFormat.fromValue(format);
                DiskFormatType ovfDiskFormat = DiskFormatType.valueOf(diskFormat.name());

                diskInfo.setDiskFileFormat(ovfDiskFormat);
                diskInfo.setDiskFileSize(fileSize);

                // Note that getHRef() will now return the relative path
                // of the file at the downloaded repository space

                if (filePath.startsWith("http:")) {
                    diskInfo.setDiskFilePath(FilenameUtils.getName(filePath));
                } else {
                    diskInfo.setDiskFilePath(filePath);
                }

                diskInfo.setIconPath(iconPath);
                diskInfo.setDescription(description);
                diskInfo.setCategoryName(categoryName);
                // XXX diskInfo.setSO(value);

                if (!requiredByVSs.containsKey(vssName)) {
                    throw new IdNotFoundException("VirtualSystem id not found [" + vssName + "]");
                }

                TemplateDto requirement = requiredByVSs.get(vssName);

                // XXX disk format ::: diskInfo.setImageType(requirement.getImageType());

                diskInfo.setCpu(requirement.getCpu());
                diskInfo.setRam(requirement.getRam());
                diskInfo.setHd(requirement.getHd());

                diskInfo.setRamSizeUnit(requirement.getRamSizeUnit());
                diskInfo.setHdSizeUnit(requirement.getHdSizeUnit());

                diskInfo.setEthernetDriverType(requirement.getEthernetDriverType());

                // TODO diskInfo.setEnterpriseId(enterpriseId);
                // diskInfo.setUserId(userId); TODO user ID
                // diskInfo.getCategories().add(category); TODO category

            } // all vss
        } // all disks
    } catch (EmptyEnvelopeException e) {
        String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
        throw new AMException(AMError.TEMPLATE_INVALID, msg, e);
    } catch (Exception e) {
        throw new AMException(AMError.TEMPLATE_INVALID, e);
    }

    if (diskInfo == null) {
        String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
        throw new AMException(AMError.TEMPLATE_INVALID, msg);
    }

    return diskInfo;
}

From source file:com.vmihalachi.turboeditor.fragment.NavigationDrawerListFragment.java

private void refreshList() {
    // File paths saved in preferences
    String[] savedPaths = PreferenceHelper.getSavedPaths(getActivity());
    // File names for the list
    fileNames = new ArrayList<String>(savedPaths.length);
    // StringBuilder that will contain the file paths
    StringBuilder sb = new StringBuilder();
    // for cycle to convert paths to names
    for (String path : savedPaths) {
        File file = new File(path);
        // Check that the file exist
        if (file.exists()) {
            fileNames.add(FilenameUtils.getName(path));
            sb.append(path).append(",");
        }/*from  w  ww.  j  a  v a2 s  .com*/
    }
    // save list without empty or non existed files
    PreferenceHelper.setSavedPaths(getActivity(), sb);
    // Adapter
    arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.item_drawer_list, fileNames);
    // Set adapter
    setListAdapter(arrayAdapter);
}

From source file:fr.avianey.androidsvgdrawable.NinePatchGenerationTest.java

@Test
public void fromJson() throws URISyntaxException, JsonIOException, JsonSyntaxException, IOException,
        TranscoderException, InstantiationException, IllegalAccessException {
    try (final Reader reader = new InputStreamReader(new FileInputStream(PATH_IN + ninePatchConfig))) {
        Type t = new TypeToken<Set<NinePatch>>() {
        }.getType();/*w w w  .ja v a  2  s. c om*/
        Set<NinePatch> ninePatchSet = new GsonBuilder().create().fromJson(reader, t);
        NinePatchMap ninePatchMap = NinePatch.init(ninePatchSet);
        QualifiedResource svg = QualifiedResource.fromFile(new File(PATH_IN + resourceName));
        NinePatch ninePatch = ninePatchMap.getBestMatch(svg);

        Assert.assertNotNull(ninePatch);

        final String name = svg.getName();
        Reflect.on(svg).set("name", name + "_" + targetDensity.name());
        Rectangle bounds = plugin.extractSVGBounds(svg);
        plugin.transcode(svg, targetDensity, bounds, new File(GenDrawableTestSuite.PATH_OUT), ninePatch);
        final File ninePatchFile = new File(GenDrawableTestSuite.PATH_OUT + svg.getName() + ".9."
                + GenDrawableTestSuite.OUTPUT_FORMAT.name().toLowerCase());
        final File nonNinePatchFile = new File(GenDrawableTestSuite.PATH_OUT + svg.getName() + "."
                + GenDrawableTestSuite.OUTPUT_FORMAT.name().toLowerCase());

        if (GenDrawableTestSuite.OUTPUT_FORMAT.hasNinePatchSupport()) {
            Assert.assertTrue(
                    FilenameUtils.getName(ninePatchFile.getAbsolutePath())
                            + " does not exists although the output format supports nine patch",
                    ninePatchFile.exists());
            Assert.assertTrue(
                    FilenameUtils.getName(nonNinePatchFile.getAbsolutePath())
                            + " file does not exists although the output format supports nine patch",
                    !nonNinePatchFile.exists());
            BufferedImage image = ImageIO.read(new FileInputStream(ninePatchFile));
            tester.test(image);
            // test corner pixels
            int w = image.getWidth();
            int h = image.getHeight();
            new PixelTester(new int[][] {},
                    new int[][] { { 0, 0 }, { 0, h - 1 }, { w - 1, 0 }, { w - 1, h - 1 } }).test(image);
        } else {
            Assert.assertTrue(
                    FilenameUtils.getName(ninePatchFile.getAbsolutePath())
                            + " exists although the output format does not support nine patch",
                    !ninePatchFile.exists());
            Assert.assertTrue(
                    FilenameUtils.getName(nonNinePatchFile.getAbsolutePath())
                            + " does not exists although the output format does not support nine patch",
                    nonNinePatchFile.exists());
        }
    }
}

From source file:com.splunk.shuttl.archiver.filesystem.PathResolverTest.java

public void resolveTempPathForBucketMetadata_bucketAndFile_hasFileNameOfMetadataFile() {
    File metadataFile = createFile("fileName.meta");
    String tempPath = pathResolver.resolveTempPathForBucketMetadata(bucket, metadataFile);
    assertEquals(metadataFile.getName(), FilenameUtils.getName(tempPath));
}

From source file:de.catma.ui.repository.wizard.FileTypePanel.java

private ArrayList<SourceDocumentResult> makeSourceDocumentResultsFromInputFile(TechInfoSet inputTechInfoSet)
        throws MalformedURLException, IOException {

    ArrayList<SourceDocumentResult> output = new ArrayList<SourceDocumentResult>();

    FileType inputFileType = FileType.getFileType(inputTechInfoSet.getMimeType());

    if (inputFileType != FileType.ZIP) {
        SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();

        String sourceDocumentID = repository.getIdFromURI(inputTechInfoSet.getURI());
        outputSourceDocumentResult.setSourceDocumentID(sourceDocumentID);

        SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult.getSourceDocumentInfo();
        outputSourceDocumentInfo.setTechInfoSet(new TechInfoSet(inputTechInfoSet));
        outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

        outputSourceDocumentInfo.getTechInfoSet().setFileType(inputFileType);

        output.add(outputSourceDocumentResult);
    } else { //TODO: put this somewhere sensible
        URI uri = inputTechInfoSet.getURI();
        ZipFile zipFile = new ZipFile(uri.getPath());
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

        String tempDir = ((CatmaApplication) UI.getCurrent()).getTempDirectory();
        IDGenerator idGenerator = new IDGenerator();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = FilenameUtils.getName(entry.getName());
            String fileId = idGenerator.generate();

            File entryDestination = new File(tempDir, fileId);
            if (entryDestination.exists()) {
                entryDestination.delete();
            }//from   w  w  w.jav  a 2 s .c o m

            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination));
                IOUtils.copy(bis, bos);
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(bos);

                SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();
                URI newURI = entryDestination.toURI();

                String repositoryId = repository.getIdFromURI(newURI); // we need to do this as a catma:// is appended

                outputSourceDocumentResult.setSourceDocumentID(repositoryId);

                SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult
                        .getSourceDocumentInfo();
                TechInfoSet newTechInfoSet = new TechInfoSet(fileName, null, newURI); // TODO: MimeType detection ?
                FileType newFileType = FileType.getFileTypeFromName(fileName);
                newTechInfoSet.setFileType(newFileType);

                outputSourceDocumentInfo.setTechInfoSet(newTechInfoSet);
                outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

                output.add(outputSourceDocumentResult);
            }
        }

        ZipFile.closeQuietly(zipFile);
    }

    for (SourceDocumentResult sdr : output) {
        TechInfoSet sdrTechInfoSet = sdr.getSourceDocumentInfo().getTechInfoSet();
        String sdrSourceDocumentId = sdr.getSourceDocumentID();

        ProtocolHandler protocolHandler = getProtocolHandlerForUri(sdrTechInfoSet.getURI(), sdrSourceDocumentId,
                sdrTechInfoSet.getMimeType());
        String mimeType = protocolHandler.getMimeType();

        sdrTechInfoSet.setMimeType(mimeType);
        FileType sdrFileType = FileType.getFileType(mimeType);
        sdrTechInfoSet.setFileType(sdrFileType);

        if (sdrFileType.isCharsetSupported()) {
            Charset charset = Charset.forName(protocolHandler.getEncoding());
            sdrTechInfoSet.setCharset(charset);
        } else {
            sdrTechInfoSet.setFileOSType(FileOSType.INDEPENDENT);
        }

        loadSourceDocumentAndContent(sdr);
    }

    return output;
}

From source file:gov.ca.cwds.rest.util.jni.CmsPKCompressor.java

private File createFile(String file) {
    return new File(FilenameUtils.getFullPath(file), FilenameUtils.getName(file)); // NOSONAR
}