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:edu.wisc.doit.tcrypt.ant.EncryptFileTask.java

@Override
public void execute() throws BuildException {
    final FileEncrypter fileEncrypter;
    Reader publicKeyReader = null;
    try {//from  ww w.  java2 s . c  o  m
        publicKeyReader = new InputStreamReader(new BufferedInputStream(this.publicKey.getInputStream()),
                FileEncrypter.CHARSET);
        fileEncrypter = new BouncyCastleFileEncrypter(publicKeyReader);
    } catch (IOException e) {
        throw new BuildException("Failed to create BouncyCastleFileEncrypter for public key: " + this.publicKey,
                e);
    } finally {
        IOUtils.closeQuietly(publicKeyReader);
    }

    final File outputFile = getOutputFile();

    InputStream srcFileInputStream = null;
    OutputStream encryptedFileOutputStream = null;
    try {
        srcFileInputStream = new BufferedInputStream(this.srcFile.getInputStream());
        encryptedFileOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

        this.log("Encrypting '" + this.srcFile + "' to '" + outputFile + "'");

        final String fileName = FilenameUtils.getName(this.srcFile.getName());
        final long size = this.srcFile.getSize();
        fileEncrypter.encrypt(fileName, (int) size, srcFileInputStream, encryptedFileOutputStream);
    } catch (IOException e) {
        throw new BuildException("Failed to encrypt file from '" + this.srcFile + "' to '" + outputFile + "'",
                e);
    } catch (InvalidCipherTextException e) {
        throw new BuildException("Public key '" + this.publicKey + "' is invalid", e);
    } finally {
        IOUtils.closeQuietly(srcFileInputStream);
        IOUtils.closeQuietly(encryptedFileOutputStream);
    }
}

From source file:cat.calidos.morfeu.model.injection.URIToParsedModule.java

@Produces
@Named("FetchedEffectiveContent")
InputStream fetchedContentReady(@Named("FetchableContentURI") URI uri,
        @Named("FetchedRawContent") Producer<InputStream> rawContentProvider,
        @Named("FetchedTransformedContent") Producer<InputStream> transformedContentProvider)
        throws FetchingException {

    // if uri ends with yaml, we transform it from yaml to xml, otherwise we just fetch it raw, assuming xml

    String name = FilenameUtils.getName(uri.getPath());

    try {/*ww w  .  j  av a2 s  .co  m*/
        if (name.endsWith("yaml")) {

            return transformedContentProvider.get().get();

        } else {

            return rawContentProvider.get().get();

        }
    } catch (InterruptedException | ExecutionException e) {
        log.error("Could not complete executing fetch of '{}' ({}", uri, e);
        throw new FetchingException("Problem executing fetch '" + uri + "'", e);
    }

}

From source file:com.docd.purefm.utils.BookmarksHelper.java

@NonNull
public static List<BookmarkItem> getAllBookmarks(@NonNull final Activity activity) {
    final List<BookmarkItem> items = new ArrayList<>();
    int internalCount = 0;
    int externalCount = 0;
    int usbCount = 0;

    final Resources.Theme theme = activity.getTheme();
    final Drawable iconStorage = ThemeUtils.getDrawableNonNull(theme, R.attr.ic_storage);
    final Drawable iconSdcard = ThemeUtils.getDrawableNonNull(theme, R.attr.ic_sdcard);
    final Drawable iconUsb = ThemeUtils.getDrawableNonNull(theme, R.attr.ic_usb);
    final Drawable iconUser = ThemeUtils.getDrawableNonNull(theme, R.attr.ic_bookmark);

    for (final StorageHelper.StorageVolume v : Environment.getStorageVolumes()) {
        final BookmarkItem item = new BookmarkItem();
        switch (v.getType()) {
        case EXTERNAL:
            externalCount++;//from   w  w  w .  jav  a2 s  .  c  o  m
            item.mIcon = iconSdcard;
            item.mDisplayName = activity.getText(R.string.storage_sdcard);
            if (externalCount > 1) {
                item.mDisplayName = TextUtils.concat(item.mDisplayName, " (" + externalCount + ")");
            }
            break;

        case USB:
            usbCount++;
            item.mIcon = iconUsb;
            item.mDisplayName = activity.getText(R.string.storage_usb);
            if (usbCount > 1) {
                item.mDisplayName = TextUtils.concat(item.mDisplayName, " (" + usbCount + ")");
            }
            break;

        case INTERNAL:
        default:
            internalCount++;
            item.mIcon = iconStorage;
            item.mDisplayName = activity.getText(R.string.storage_internal);
            if (internalCount > 1) {
                item.mDisplayName = TextUtils.concat(item.mDisplayName, " (" + internalCount + ")");
            }
            break;
        }
        item.mDisplayPath = v.file.getAbsolutePath();
        items.add(item);
    }

    for (final String bookmark : Settings.getInstance(activity).getBookmarks()) {
        final BookmarkItem item = new BookmarkItem();
        item.mDisplayName = FilenameUtils.getName(bookmark);
        if (item.mDisplayName.equals(Environment.sRootDirectory.getAbsolutePath())) {
            item.mDisplayName = activity.getText(R.string.root);
        }
        item.mDisplayPath = bookmark;
        item.mIcon = iconUser;
        items.add(item);
    }
    return items;
}

From source file:de.uzk.hki.da.convert.CLIConversionStrategy.java

/**
 * Convert file.//from w w  w  . ja  v a2s  .c  om
 *
 * @param ci the ci
 * @return the list
 * @throws FileNotFoundException the file not found exception
 */
@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException {
    if (pkg == null)
        throw new IllegalStateException("Package not set");
    Path.make(wa.dataPath(), object.getNameOfLatestBRep(), ci.getTarget_folder()).toFile().mkdirs();

    String[] commandAsArray = assemble(wa, ci, object.getNameOfLatestBRep());
    if (!cliConnector.execute(commandAsArray))
        throw new RuntimeException("convert did not succeed");

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(toAbsolutePath(wa.dataPath(), ci.getSource_file()));
    DAFile result = new DAFile(object.getNameOfLatestBRep(),
            ci.getTarget_folder() + "/"
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(toAbsolutePath(wa.dataPath(), ci.getSource_file()))))
                    + "." + targetSuffix);

    Event e = new Event();
    e.setType("CONVERT");
    e.setDetail(StringUtilities.createString(commandAsArray));
    e.setSource_file(ci.getSource_file());
    e.setTarget_file(result);
    e.setDate(new Date());

    List<Event> results = new ArrayList<Event>();
    results.add(e);
    return results;
}

From source file:com.alibaba.otter.node.etl.common.pipe.impl.memory.RowDataMemoryPipe.java

@SuppressWarnings("unused")
private File prepareFile(FileBatch fileBatch) {
    // ?url/*w  ww.ja  v  a2  s . c o  m*/
    String dirname = buildFileName(fileBatch.getIdentity(), ClassUtils.getShortClassName(fileBatch.getClass()));
    File dir = new File(downloadDir, dirname);
    NioUtils.create(dir, false, 3);// 
    // ?
    List<FileData> fileDatas = fileBatch.getFiles();

    for (FileData fileData : fileDatas) {
        String namespace = fileData.getNameSpace();
        String path = fileData.getPath();
        boolean isLocal = StringUtils.isBlank(namespace);
        String entryName = null;
        if (true == isLocal) {
            entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path);
        } else {
            entryName = namespace + File.separator + path;
        }

        InputStream input = retrive(fileBatch.getIdentity(), fileData);
        if (input == null) {
            continue;
        }
        File entry = new File(dir, entryName);
        NioUtils.create(entry.getParentFile(), false, retry);// ?
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(entry);
            NioUtils.copy(input, output);// ?
        } catch (Exception e) {
            throw new PipeException("prepareFile error for file[" + entry.getPath() + "]");
        } finally {
            IOUtils.closeQuietly(output);
        }
    }

    return dir;
}

From source file:com.hortonworks.streamline.streams.cluster.register.impl.AbstractServiceRegistrar.java

@Override
public Service register(Cluster cluster, Config config, List<ConfigFileInfo> configFileInfos)
        throws IOException {
    Service service = environmentService.initializeService(cluster, getServiceName());

    List<ServiceConfiguration> configurations = new ArrayList<>();
    Map<String, String> flattenConfigMap = new HashMap<>();

    List<ServiceConfiguration> serviceConfigurations = createServiceConfigurations(config);
    if (serviceConfigurations != null && !serviceConfigurations.isEmpty()) {
        serviceConfigurations.forEach(sc -> {
            configurations.add(sc);/*  w  ww  .  j a  v  a 2s  . com*/
            try {
                flattenConfigMap.putAll(sc.getConfigurationMap());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    for (ConfigFileInfo configFileInfo : configFileInfos) {
        Map<String, String> configMap = readConfigFile(configFileInfo);

        String fileName = FilenameUtils.getName(configFileInfo.getFileName());
        String confType = getConfType(fileName);
        String actualFileName = ConfigFilePattern.getOriginFileName(confType);

        ServiceConfiguration configuration = environmentService.initializeServiceConfiguration(service.getId(),
                confType, actualFileName, new HashMap<>(configMap));
        configurations.add(configuration);
        flattenConfigMap.putAll(configMap);
    }

    List<Component> components = createComponents(config, flattenConfigMap);

    if (!validateComponents(components)) {
        throw new IllegalArgumentException("Validation failed for components.");
    }

    if (!validateServiceConfigurations(configurations)) {
        throw new IllegalArgumentException("Validation failed for service configurations.");
    }

    if (!validateServiceConfiguationsAsFlattenedMap(flattenConfigMap)) {
        throw new IllegalArgumentException("Validation failed for service configurations.");
    }

    // here we are storing actual catalogs
    // before that we need to replace dummy service id to the actual one
    service = environmentService.addService(service);

    for (Component component : components) {
        component.setServiceId(service.getId());
        environmentService.addComponent(component);
    }

    for (ServiceConfiguration configuration : configurations) {
        configuration.setServiceId(service.getId());
        environmentService.addServiceConfiguration(configuration);
    }

    return service;
}

From source file:eu.esdihumboldt.hale.ui.service.project.RecentProjectsMenu.java

/**
 * @see ContributionItem#fill(Menu, int)
 *//* w  ww . j  a  v  a2s.  c om*/
@Override
public void fill(final Menu menu, int index) {
    RecentProjectsService rfs = PlatformUI.getWorkbench().getService(RecentProjectsService.class);
    RecentProjectsService.Entry[] entries = rfs.getRecentFiles();
    if (entries == null || entries.length == 0) {
        return;
    }

    // add separator
    new MenuItem(menu, SWT.SEPARATOR, index);

    int i = entries.length;
    for (RecentProjectsService.Entry entry : entries) {
        String file = entry.getFile();
        MenuItem mi = new MenuItem(menu, SWT.PUSH, index);
        String filename = FilenameUtils.getName(file);
        String shortened = shorten(file, MAX_LENGTH, filename.length());
        String nr = String.valueOf(i);
        if (i <= 9) {
            // add mnemonic for the first 9 items
            nr = "&" + nr; //$NON-NLS-1$
        }
        mi.setText(nr + "  " + shortened); //$NON-NLS-1$
        mi.setData(file);
        mi.addSelectionListener(new MenuItemSelectionListener(new File(file)));
        --i;
    }
}

From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java

/**
 * Convert file.//  ww  w .j ava  2s . c o  m
 *
 * @param ci the ci
 * @return the list
 * @throws FileNotFoundException the file not found exception
 * @throws IllegalStateException the illegal state exception
 * @author Daniel M. de Oliveira
 * @author Sebastian Cuy
 */
@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci)
        throws FileNotFoundException, IllegalStateException {
    if (object == null)
        throw new IllegalStateException("Object not set");
    if (object.getIdentifier() == null || object.getIdentifier().equals(""))
        throw new IllegalStateException("object.getIdentifier() - returns no valid value");

    String objectId = object.getIdentifier().substring(object.getIdentifier().indexOf("-") + 1);
    logger.debug("objectId: " + objectId);

    Source xmlSource = createXMLSource(wa.toFile(ci.getSource_file()));

    String targetFileName = FilenameUtils
            .removeExtension(FilenameUtils.getName(wa.toFile(ci.getSource_file()).getAbsolutePath()));
    if (!ci.getConversion_routine().getName().endsWith("_paths-for-presenter"))
        targetFileName += "_" + ci.getConversion_routine().getName();

    List<Event> results = new ArrayList<Event>();
    DAFile publFile = new DAFile(WorkArea.TMP_PIPS + "/public",
            ci.getTarget_folder() + "/" + targetFileName + ".xml");
    DAFile instFile = new DAFile(WorkArea.TMP_PIPS + "/institution",
            ci.getTarget_folder() + "/" + targetFileName + ".xml");

    new File(wa.dataPath() + "/" + WorkArea.TMP_PIPS + "/public/" + ci.getTarget_folder()).mkdirs();
    new File(wa.dataPath() + "/" + WorkArea.TMP_PIPS + "/institution/" + ci.getTarget_folder()).mkdirs();

    logger.debug("Will transform {} to {}", ci.getSource_file(), publFile);
    logger.debug("Will transform {} to {}", ci.getSource_file(), instFile);
    try {
        if (objectId != null)
            transformer.setParameter("object-id", objectId);

        transformer.transform(xmlSource, new StreamResult(wa.toFile(publFile).getAbsolutePath()));
        transformer.transform(xmlSource, new StreamResult(wa.toFile(instFile).getAbsolutePath()));

    } catch (TransformerException e) {
        throw new RuntimeException("Error while transforming xml.", e);
    }

    Event e1 = new Event();
    e1.setType("CONVERT");
    e1.setDetail(stylesheet);
    e1.setSource_file(ci.getSource_file());
    e1.setTarget_file(publFile);
    e1.setDate(new Date());

    Event e2 = new Event();
    e2.setType("CONVERT");
    e2.setDetail(stylesheet);
    e2.setSource_file(ci.getSource_file());
    e2.setTarget_file(instFile);
    e2.setDate(new Date());

    results.add(e1);
    results.add(e2);
    return results;
}

From source file:com.exilant.exility.core.TestReport.java

@Override
public void process(final String fileInput, final String masterSummary) throws ExilityException {
    String stamp = ResourceManager.getTimeStamp();
    String qualifiedFileName = null;
    String testFileOutput = null;
    String testFile = null;/*from  w  w  w .  j  a v  a2 s . com*/
    // List<String[]> list = new ArrayList<String[]>();

    File file = new File(fileInput);
    File dir = new File(fileInput);
    testFileOutput = fileInput + "/" + FilenameUtils.getName(file.toString()) + "_" + stamp
            + Constants.OUT_SUFFIX;
    String summaryFile = fileInput + "/" + Constants.SUMMARY + "/" + Constants.SUMMARY + "_" + stamp
            + Constants.XML;

    try {
        if (file.isFile() && (file.getCanonicalPath()).endsWith(Constants.XML)) {
            qualifiedFileName = FilenameUtils.getName(file.toString());

            testFile = testFileOutput + "/" + qualifiedFileName + Constants.OUT_SUFFIX + stamp + Constants.XML;
            this.test(file.toString(), testFile, this.list);
            this.generate(testFile, this.list);

        }
        // else {
        // for (File testFileInput : dir.listFiles()) {
        // try {
        // qualifiedFileName =
        // FilenameUtils.getName(testFileInput.toString());
        //
        // if (qualifiedFileName.equals(Constants.DS_STORE) ||
        // (qualifiedFileName.equals(Constants.SUMMARY))) {
        // continue;
        // }
        // if (testFileInput.isFile() &&
        // (testFileInput.getCanonicalPath()).endsWith(Constants.XML)) {
        //
        // testFile = testFileOutput + "/" +
        // qualifiedFileName.replace(Constants.XML, Constants.OUT_SUFFIX) +
        // Constants.XML;
        // test(testFileInput.toString(), testFile, list);
        // generate(testFile, list);
        //
        // }
        // else continue;
        // } catch (IOException e) {
        // Spit.out("Output file could not be created for " +
        // qualifiedFileName);
        // e.printStackTrace();
        // }
        // }
        //
        // }
        else {
            this.getFiles(dir);
        }
        this.merge(this.list);

        this.generateSummary(summaryFile, this.list, null);

        if (masterSummary != null) {
            this.generateSummary(null, this.summary, masterSummary);
        }

    } catch (IOException e) {
        Spit.out("Output file could not be created for " + fileInput);
        e.printStackTrace();
    }
}

From source file:eu.matejkormuth.crawler2.Document.java

/**
 * Returns the name of this document. Beware that this can returns empty
 * string for index documents with URL like <code>example.com/page/</code>.
 * //from  w  w w.j a  va 2s .c om
 * @return name of this file
 */
public String getName() {
    return FilenameUtils.getName(this.url.toString());
}