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

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

Introduction

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

Prototype

public static String getBaseName(String filename) 

Source Link

Document

Gets the base name, minus the full path and extension, from a full filename.

Usage

From source file:context.ui.misc.FileHandler.java

/**
 *
 * @param path
 * @return
 */
public static String getFileName(String path) {
    return FilenameUtils.getBaseName(path);
}

From source file:io.wcm.devops.conga.plugins.aem.postprocessor.ContentPackageOsgiConfigPostProcessor.java

@Override
public List<FileContext> apply(FileContext fileContext, PostProcessorContext context) {
    File file = fileContext.getFile();
    Logger logger = context.getLogger();
    Map<String, Object> options = context.getOptions();

    try {/*from  w  ww  .j  av  a2 s . c o  m*/
        // extract file header
        FileHeaderContext fileHeader = extractFileHeader(fileContext, context);

        // generate OSGi configurations
        Model model = ProvisioningUtil.getModel(fileContext);

        // create AEM content package with configurations
        File zipFile = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName()) + ".zip");
        logger.info("Generate " + zipFile.getCanonicalPath());

        String rootPath = ContentPackageUtil.getMandatoryProp(options, PROPERTY_PACKAGE_ROOT_PATH);

        ContentPackageBuilder builder = ContentPackageUtil.getContentPackageBuilder(options, fileHeader);

        try (ContentPackage contentPackage = builder.build(zipFile)) {

            // always create folder for root path
            contentPackage.addContent(rootPath, ImmutableMap.of("jcr:primaryType", "nt:folder"));

            generateOsgiConfigurations(model, contentPackage, rootPath, fileHeader, context);
        }

        // delete provisioning file after transformation
        file.delete();

        // set force to true by default for CONGA-generated packages (but allow override from role definition)
        Map<String, Object> modelOptions = new HashMap<>();
        modelOptions.put("force", true);
        modelOptions.putAll(fileContext.getModelOptions());

        return ImmutableList.of(new FileContext().file(zipFile).modelOptions(modelOptions));
    } catch (IOException ex) {
        throw new GeneratorException("Unable to post-process sling provisioning OSGi configurations.", ex);
    }
}

From source file:bear.main.FXConf.java

public String getSelectedSettings() {
    return FilenameUtils.getBaseName($(projectFile).getName());
}

From source file:com.chingo247.structureapi.plan.StructurePlan.java

public void load(AbstractDocument document) throws StructureDataException, IOException {
    xmlFile = document.getDocumentFile();
    pluginElement = document.getPluginElement(Bukkit.getPluginManager().getPlugin("SettlerCraft"));

    Element scElement = pluginElement.getAsElement();

    Node schematicNode = scElement.selectSingleNode(Nodes.SCHEMATIC_NODE);
    if (schematicNode == null) {
        throw new StructureDataException(
                "Missing  Structure Schematic in " + document.getDocumentFile().getAbsolutePath());
    }/*from  w ww  .  ja  va  2  s .c  o m*/

    File s = new File(document.getDocumentFile().getParent(), schematicNode.getText());
    if (s.exists()) {
        schematic = s;
    } else {
        throw new FileNotFoundException("Couldn't resolve path for " + s.getAbsolutePath() + " for config:  "
                + document.getDocumentFile().getAbsolutePath());
    }

    checksum = FileUtils.checksumCRC32(s);

    name = pluginElement.getStringValue(Nodes.NAME_NODE);
    if (name == null) {
        name = FilenameUtils.getBaseName(schematic.getName());
    }
    category = pluginElement.getStringValue(Nodes.CATEGORY_NODE);
    if (category == null) {
        category = "Default";
    }

    description = pluginElement.getStringValue(Nodes.DESCRIPTION_NODE);
    if (description == null) {
        description = "-";
    }

    try {
        price = pluginElement.getDoubleValue(Nodes.PRICE_NODE);
    } catch (NumberFormatException nfe) {
        throw new StructureDataException("Value of 'Price' must be a number, error generated in "
                + document.getDocumentFile().getAbsolutePath());
    }
    if (price == null) {
        price = 0.0;
    }

    Node worldGuardFlagsNode = scElement.selectSingleNode(Nodes.WORLDGUARD_FLAGS_NODE);
    if (worldGuardFlagsNode != null) {
        regionFlags = new StructureRegionFlagLoader().load((Element) worldGuardFlagsNode);
    } else {
        regionFlags = new LinkedList<>();
    }

    Node structureOverviewsNode = scElement.selectSingleNode(Nodes.STRUCTURE_OVERVIEWS_NODE);
    if (structureOverviewsNode != null) {
        overviews = new StructureOverviewLoader().load((Element) structureOverviewsNode);
    } else {
        overviews = new LinkedList<>();
    }

    Node structureHologramsNode = scElement.selectSingleNode(Nodes.HOLOGRAMS_NODE);
    if (structureOverviewsNode != null) {
        holograms = new StructureHologramLoader().load((Element) structureHologramsNode);
    } else {
        holograms = new LinkedList<>();
    }
}

From source file:OogieDocumentConverter.java

protected void loadAndExport(String inputUrl, Map/*<String,Object>*/ loadProperties, String outputUrl,
        Map/*<String,Object>*/ storeProperties) throws Exception {
    XComponentLoader desktop = openOfficeConnection.getDesktop();
    XComponent document = desktop.loadComponentFromURL(inputUrl, "_blank", 0, toPropertyValues(loadProperties));
    if (document == null) {
        throw new OpenOfficeException("conversion failed: input document is null after loading");
    }/*from   w  w w.  ja va 2  s. c  o  m*/

    refreshDocument(document);

    try {

        outputUrl = FilenameUtils.getFullPath(outputUrl) + FilenameUtils.getBaseName(outputUrl);

        //          filter
        PropertyValue[] loadProps = new PropertyValue[4];

        // type of image
        loadProps[0] = new PropertyValue();
        loadProps[0].Name = "MediaType";
        loadProps[0].Value = "image/png";

        // Height and width
        PropertyValue[] filterDatas = new PropertyValue[4];
        for (int i = 0; i < 4; i++) {
            filterDatas[i] = new PropertyValue();
        }

        filterDatas[0].Name = "PixelWidth";
        filterDatas[0].Value = new Integer(this.width);
        filterDatas[1].Name = "PixelHeight";
        filterDatas[1].Value = new Integer(this.height);
        filterDatas[2].Name = "LogicalWidth";

        filterDatas[2].Value = new Integer(2000);
        filterDatas[3].Name = "LogicalHeight";
        filterDatas[3].Value = new Integer(2000);

        XDrawPagesSupplier pagesSupplier = (XDrawPagesSupplier) UnoRuntime
                .queryInterface(XDrawPagesSupplier.class, document);
        //System.out.println(pagesSupplier.toString());            
        XDrawPages pages = pagesSupplier.getDrawPages();
        int nbPages = pages.getCount();
        String[] slidenames = new String[nbPages];
        Arrays.fill(slidenames, "");

        for (int i = 0; i < nbPages; i++) {

            XDrawPage page = (XDrawPage) UnoRuntime.queryInterface(com.sun.star.drawing.XDrawPage.class,
                    pages.getByIndex(i));
            XShapes xShapes = (XShapes) UnoRuntime.queryInterface(XShapes.class, page);
            int top = 0;
            String slidename = "";
            for (int j = 0; j < xShapes.getCount(); j++) {
                XShape firstXshape = (XShape) UnoRuntime.queryInterface(XShape.class, xShapes.getByIndex(j));
                Point pos = firstXshape.getPosition();
                if (pos.Y < top || top == 0) {
                    XText xText = (XText) UnoRuntime.queryInterface(XText.class, firstXshape);
                    if (xText != null && xText.getString().length() > 0) {
                        top = pos.Y;
                        slidename = xText.getString();
                    }
                }
            }

            String slidenameDisplayed = "";
            if (slidename.trim().length() == 0) {
                slidename = "slide" + (i + 1);
            } else {
                int nbSpaces = 0;
                String formatedSlidename = "";
                slidename = slidename.replaceAll(" ", "_");
                slidename = slidename.replaceAll("\n", "_");
                slidename = slidename.replaceAll("__", "_");

                for (int j = 0; j < slidename.length(); j++) {
                    char currentChar = slidename.charAt(j);
                    if (currentChar == '_') {
                        nbSpaces++;
                    }
                    if (nbSpaces == 5) {
                        break;
                    }
                    formatedSlidename += slidename.charAt(j);
                }

                slidenameDisplayed = formatedSlidename;

                slidename = formatedSlidename.toLowerCase();
                slidename = slidename.replaceAll("\\W", "_");
                slidename = slidename.replaceAll("__", "_");
                slidename = StringOperation.sansAccent(slidename);

            }
            int j = 1;
            String slidenamebackup = slidename;
            Arrays.sort(slidenames);
            while (Arrays.binarySearch(slidenames, slidename) >= 0) {
                j++;
                slidename = slidenamebackup + j;
            }
            slidenames[nbPages - (i + 1)] = slidename;

            XNamed xPageName = (XNamed) UnoRuntime.queryInterface(XNamed.class, page);

            xPageName.setName(slidename);

            XMultiComponentFactory localServiceManager = ((DokeosSocketOfficeConnection) this.openOfficeConnection)
                    .getServiceManager();
            Object GraphicExportFilter = localServiceManager.createInstanceWithContext(
                    "com.sun.star.drawing.GraphicExportFilter",
                    ((DokeosSocketOfficeConnection) this.openOfficeConnection).getComponentContext());

            XExporter xExporter = (XExporter) UnoRuntime.queryInterface(XExporter.class, GraphicExportFilter);

            XComponent xComp = (XComponent) UnoRuntime.queryInterface(XComponent.class, page);

            xExporter.setSourceDocument(xComp);
            loadProps[1] = new PropertyValue();
            loadProps[1].Name = "URL";

            loadProps[1].Value = outputUrl + "/" + xPageName.getName() + ".png";
            loadProps[2] = new PropertyValue();
            loadProps[2].Name = "FilterData";
            loadProps[2].Value = filterDatas;
            loadProps[3] = new PropertyValue();
            loadProps[3].Name = "Quality";
            loadProps[3].Value = new Integer(100);

            XFilter xFilter = (XFilter) UnoRuntime.queryInterface(XFilter.class, GraphicExportFilter);

            xFilter.filter(loadProps);
            if (slidenameDisplayed == "")
                slidenameDisplayed = xPageName.getName();
            System.out.println(slidenameDisplayed + "||" + xPageName.getName() + ".png");

        }

    } finally {
        document.dispose();
    }
}

From source file:io.wcm.devops.conga.generator.Generator.java

private static <T> Map<String, T> readModels(List<ResourceCollection> dirs, ModelReader<T> reader) {
    Map<String, T> models = new HashMap<>();
    for (ResourceCollection dir : dirs) {
        for (Resource file : dir.getResources()) {
            if (reader.accepts(file)) {
                try {
                    T model = reader.read(file);
                    ConfigInheritanceResolver.resolve(model);
                    models.put(FilenameUtils.getBaseName(file.getName()), model);
                } catch (Throwable ex) {
                    throw new GeneratorException("Unable to read definition: " + file.getCanonicalPath(), ex);
                }//from w ww.j a  v  a 2  s .  c om
            }
        }
    }
    return ImmutableMap.copyOf(models);
}

From source file:com.frostwire.gui.UniversalScanner.java

private void scanPictures(String filePath, boolean shared) {
    File file = new File(filePath);

    ContentValues values = new ContentValues();

    String mime = "image/" + FilenameUtils.getExtension(filePath);
    fillCommonValues(values, Constants.FILE_TYPE_PICTURES, filePath, file, mime, shared);

    try {/*  w  ww .j  ava  2 s . com*/
        Metadata metadata = ImageMetadataReader.readMetadata(file);

        ExifIFD0Directory dir = metadata.getDirectory(ExifIFD0Directory.class);
        ExifIFD0Descriptor desc = new ExifIFD0Descriptor(dir);

        String title = desc.getWindowsTitleDescription();
        if (StringUtils.isNullOrEmpty(title, true)) {
            title = FilenameUtils.getBaseName(file.getName());
        }

        String artist = desc.getWindowsAuthorDescription();
        if (StringUtils.isNullOrEmpty(artist, true)) {
            artist = dir.getString(ExifIFD0Directory.TAG_ARTIST, "UTF-8");
        }
        if (StringUtils.isNullOrEmpty(artist, true)) {
            artist = "";
        }

        String album = "";
        String year = dir.getString(ExifIFD0Directory.TAG_DATETIME);
        if (StringUtils.isNullOrEmpty(year, true)) {
            year = "";
        }

        values.put(Columns.TITLE, title);
        values.put(Columns.ARTIST, artist);
        values.put(Columns.ALBUM, album);
        values.put(Columns.YEAR, year);
    } catch (Throwable e) {
        String displayName = FilenameUtils.getBaseName(file.getName());

        values.put(Columns.TITLE, displayName);
        values.put(Columns.ARTIST, "");
        values.put(Columns.ALBUM, "");
        values.put(Columns.YEAR, "");
    }

    ShareFilesDB db = ShareFilesDB.intance();

    db.insert(values);
}

From source file:com.mbrlabs.mundus.utils.FbxConv.java

public FbxConvResult execute() {
    FbxConvResult result = new FbxConvResult();
    if (input == null || output == null) {
        result.setSuccess(false);/*from w  ww. j a v  a2s . co  m*/
        result.setResultCode(FbxConvResult.RESULT_CODE_PARAM_ERROR);
        Log.error("FbxCov input or output not defined");
        return result;
    }

    if (!input.endsWith("fbx")) {
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_WRONG_INPUT_FORMAT);
        Log.error("FbxCov input format not supported");
    }

    // build arguments
    String outputFilename = FilenameUtils.getBaseName(input);
    List<String> args = new ArrayList<String>(6);
    if (flipTexture)
        args.add("-f");
    if (verbose)
        args.add("-v");
    if (outputFormat == OUTPUT_FORMAT_G3DJ) {
        args.add("-o");
        args.add("g3dj");
        outputFilename += ".g3dj";
    } else {
        outputFilename += ".g3db";
    }

    args.add(input);
    String path = FilenameUtils.concat(output, outputFilename);
    args.add(path);
    Log.debug("FbxConv", "Command: " + args);
    pb.command().addAll(args);

    // execute fbx-conv process
    try {
        Process process = pb.start();
        int exitCode = process.waitFor();
        String log = IOUtils.toString(process.getInputStream());

        if (exitCode == 0 && !log.contains("ERROR")) {
            result.setSuccess(true);
            result.setOutputFile(path);
        }
        result.setLog(log);

    } catch (IOException e) {
        e.printStackTrace();
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_IO_ERROR);
    } catch (InterruptedException e) {
        e.printStackTrace();
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_INTERRUPTED);
    }

    return result;
}

From source file:net.sf.jooreports.web.spring.controller.AbstractDocumentGenerator.java

private void renderDocument(Object model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    DocumentConverter converter = (DocumentConverter) getApplicationContext().getBean("documentConverter");
    DocumentFormatRegistry formatRegistry = (DocumentFormatRegistry) getApplicationContext()
            .getBean("documentFormatRegistry");
    String outputExtension = FilenameUtils.getExtension(request.getRequestURI());
    DocumentFormat outputFormat = formatRegistry.getFormatByFileExtension(outputExtension);
    if (outputFormat == null) {
        throw new ServletException("unsupported output format: " + outputExtension);
    }/*from w ww . j  av a 2 s  . co  m*/
    File templateFile = null;
    String documentName = FilenameUtils.getBaseName(request.getRequestURI());
    Resource templateDirectory = getTemplateDirectory(documentName);
    if (templateDirectory.exists()) {
        templateFile = templateDirectory.getFile();
    } else {
        templateFile = getTemplateFile(documentName).getFile();
        if (!templateFile.exists()) {
            throw new ServletException("template not found: " + documentName);
        }
    }

    DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
    DocumentTemplate template = documentTemplateFactory.getTemplate(templateFile);

    ByteArrayOutputStream odtOutputStream = new ByteArrayOutputStream();
    try {
        template.createDocument(model, odtOutputStream);
    } catch (DocumentTemplateException exception) {
        throw new ServletException(exception);
    }
    response.setContentType(outputFormat.getMimeType());
    response.setHeader("Content-Disposition",
            "inline; filename=" + documentName + "." + outputFormat.getFileExtension());

    if ("odt".equals(outputFormat.getFileExtension())) {
        // no need to convert
        response.getOutputStream().write(odtOutputStream.toByteArray());
    } else {
        ByteArrayInputStream odtInputStream = new ByteArrayInputStream(odtOutputStream.toByteArray());
        DocumentFormat inputFormat = formatRegistry.getFormatByFileExtension("odt");
        converter.convert(odtInputStream, inputFormat, response.getOutputStream(), outputFormat);
    }
}

From source file:de.thischwa.pmcms.tool.PathTool.java

/**
 * Generates the file name of an {@link IRenderable}.<br>
 * If 'renderable' is an {@link Image}, the name will be constructed by the following pattern: <br>
 * <code>[gallery name]-[image base name].[ext]</code>.
 * /*from   ww w . j av  a  2 s  .  c  o m*/
 * @param renderable
 * @param extension file extension
 * @return Return the file name without path!
 */
public static String getExportBaseFilename(final IRenderable renderable, String extension) {
    if (renderable == null)
        throw new IllegalArgumentException("Can't handle IRenderable is null!");
    StringBuilder name = new StringBuilder();
    if (InstanceUtil.isPage(renderable)) {
        Page page = (Page) renderable;
        if (OrderableInfo.isFirst(page))
            name.append(InitializationManager.getBean(PropertiesManager.class)
                    .getSiteProperty("pmcms.site.export.file.welcome"));
        else {
            name.append(page.getName());
            name.append('.');
            name.append(extension);
        }
    } else if (InstanceUtil.isImage(renderable)) {
        Image image = (Image) renderable;
        name.append(image.getParent().getName());
        name.append('-');
        name.append(FilenameUtils.getBaseName(image.getFileName()));
        name.append('.');
        name.append(extension);
    } else
        throw new IllegalArgumentException("Unknown object TYPE!");

    return name.toString();
}