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:com.chingo247.structureapi.util.ConfigUpdater.java

public void checkAndUpdate() throws Exception {
    if (currentConfigFile.exists()) {
        String newConfigVersion = ConfigProvider.getVersion(configFileToCheck);
        String currentConfigVersion = null;
        boolean needsUpdating = false;
        try {/*from  w  ww .  j  av  a 2 s  . co  m*/
            currentConfigVersion = ConfigProvider.getVersion(currentConfigFile);
        } catch (Exception ex) {
            YAMLProcessor processor = new YAMLProcessor(currentConfigFile, false);
            if (processor.getProperty("version") != null) {
                throw new Exception(
                        "An error occurred while loading the config file, if the config file is missing expected values, try removing the file. When the file is removed, a new (default) config will be generated");
            } else {
                needsUpdating = true;
            }
        }
        if (needsUpdating || (currentConfigVersion == null
                || (VersionUtil.compare(currentConfigVersion, newConfigVersion) == -1))) {
            int count = 1;
            String baseName = FilenameUtils.getBaseName(currentConfigFile.getName());
            File oldFile = new File(currentConfigFile.getParent(), baseName + "(" + count + ").old.yml");
            while (oldFile.exists()) {
                count++;
                oldFile = new File(currentConfigFile.getParent(), baseName + "(" + count + ").old.yml");
            }

            String reason;
            if (needsUpdating || (currentConfigVersion == null)) {
                reason = "No 'version' value found in config";
            } else {
                reason = "Older 'version' value found in config.yml";
            }

            onUpdate(reason);

            FileUtils.copyFile(currentConfigFile, oldFile);
            FileUtils.copyFile(configFileToCheck, currentConfigFile);
        }
    } else {
        FileUtils.copyFile(configFileToCheck, currentConfigFile);
    }

}

From source file:edu.emory.library.tast.images.ThumbnailServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // location of images
    String baseUrl = AppConfig.getConfiguration().getString(AppConfig.IMAGES_URL);
    baseUrl = StringUtils.trimEnd(baseUrl, '/');

    // image name and size
    String imageFileName = request.getParameter("i");
    int thumbnailWidth = Integer.parseInt(request.getParameter("w"));
    int thumbnailHeight = Integer.parseInt(request.getParameter("h"));

    // image dir/* w  w  w. ja  v a2  s.  c o  m*/
    String imagesDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);

    // create the thumbnail name
    String thumbnailFileName = FilenameUtils.getBaseName(imageFileName) + "-" + thumbnailWidth + "x"
            + thumbnailHeight + ".png";

    // does it exist?
    File thumbnailFile = new File(imagesDir, thumbnailFileName);
    if (thumbnailFile.exists()) {
        response.sendRedirect(baseUrl + "/" + thumbnailFileName);
        return;
    }

    // read the image
    File imageFile = new File(imagesDir, imageFileName);
    BufferedImage image = ImageIO.read(imageFile);
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    BufferedImage imageCopy = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    imageCopy.getGraphics().drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight,
            null);

    // height is calculated automatically
    if (thumbnailHeight == 0)
        thumbnailHeight = (int) ((double) thumbnailWidth / (double) imageWidth * (double) imageHeight);

    // width is calculated automatically
    if (thumbnailWidth == 0)
        thumbnailWidth = (int) ((double) thumbnailHeight / (double) imageHeight * (double) imageWidth);

    // create an empty thumbnail
    BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D gr = thumbnail.createGraphics();
    gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // determine the piece of the image which we want to clip
    int clipX1, clipX2, clipY1, clipY2;
    if (imageWidth * thumbnailHeight > thumbnailWidth * imageHeight) {

        int clipWidth = (int) Math
                .round(((double) thumbnailWidth / (double) thumbnailHeight) * (double) imageHeight);
        int imgCenterX = imageWidth / 2;
        clipX1 = imgCenterX - clipWidth / 2;
        clipX2 = imgCenterX + clipWidth / 2;
        clipY1 = 0;
        clipY2 = imageHeight;
    } else {
        int clipHeight = (int) Math
                .round(((double) thumbnailHeight / (double) thumbnailWidth) * (double) imageWidth);
        int imgCenterY = imageHeight / 2;
        clipX1 = 0;
        clipX2 = imageWidth;
        clipY1 = imgCenterY - clipHeight / 2;
        clipY2 = imgCenterY + clipHeight / 2;
    }

    // we filter the image first to get better results when shrinking
    if (2 * thumbnailWidth < clipX2 - clipX1 || 2 * thumbnailHeight < clipY2 - clipY1) {

        int kernelDimX = (clipX2 - clipX1) / (thumbnailWidth);
        int kernelDimY = (clipY2 - clipY1) / (thumbnailHeight);

        if (kernelDimX % 2 == 0)
            kernelDimX++;
        if (kernelDimY % 2 == 0)
            kernelDimY++;

        if (kernelDimX < kernelDimY)
            kernelDimX = kernelDimY;
        if (kernelDimY < kernelDimX)
            kernelDimY = kernelDimX;

        float[] blurKernel = new float[kernelDimX * kernelDimY];
        for (int i = 0; i < kernelDimX; i++)
            for (int j = 0; j < kernelDimY; j++)
                blurKernel[i * kernelDimX + j] = 1.0f / (float) (kernelDimX * kernelDimY);

        BufferedImageOp op = new ConvolveOp(new Kernel(kernelDimX, kernelDimY, blurKernel));
        imageCopy = op.filter(imageCopy, null);

    }

    // draw the thumbnail
    gr.drawImage(imageCopy, 0, 0, thumbnailWidth, thumbnailHeight, clipX1, clipY1, clipX2, clipY2, null);

    // and we are done
    gr.dispose();
    ImageIO.write(thumbnail, "png", thumbnailFile);

    // redirect to it
    response.sendRedirect(baseUrl + "/" + thumbnailFileName);

}

From source file:it.geosolutions.geoserver.rest.ConfigTest.java

@Test
public void insertStyles() throws FileNotFoundException, IOException {
    if (!enabled()) {
        LOGGER.info("Skipping test " + "insertStyles" + "for class:" + this.getClass().getSimpleName());
        return;// w  w  w  .j  a  v  a 2s .c o m
    }
    deleteAllStyles();

    File sldDir = new ClassPathResource("testdata").getFile();
    for (File sldFile : sldDir.listFiles((FilenameFilter) new SuffixFileFilter(".sld"))) {
        LOGGER.info("Existing styles: " + reader.getStyles().getNames());
        String basename = FilenameUtils.getBaseName(sldFile.toString());
        LOGGER.info("Publishing style " + sldFile + " as " + basename);
        assertTrue("Cound not publish " + sldFile, publisher.publishStyle(sldFile, basename));
    }
}

From source file:com.googlecode.dex2jar.tools.Jar2Jasmin.java

@Override
protected void doCommandLine() throws Exception {
    if (remainingArgs.length != 1) {
        usage();/*from  www.ja  v  a2s  .com*/
        return;
    }

    File jar = new File(remainingArgs[0]);
    if (!jar.exists()) {
        System.err.println(jar + " is not exists");
        usage();
        return;
    }

    if (output == null) {
        if (jar.isDirectory()) {
            output = new File(jar.getName() + "-jar2jasmin/");
        } else {
            output = new File(FilenameUtils.getBaseName(jar.getName()) + "-jar2jasmin/");
        }
    }

    if (output.exists() && !forceOverwrite) {
        System.err.println(output + " exists, use --force to overwrite");
        usage();
        return;
    }

    System.out.println("disassemble " + jar + " -> " + output);
    final int flags = debugInfo ? 0 : ClassReader.SKIP_DEBUG;
    final OutHandler fo = FileOut.create(output, false);
    try {
        new FileWalker().withStreamHandler(new StreamHandler() {

            @Override
            public void handle(boolean isDir, String name, StreamOpener current, Object nameObject)
                    throws IOException {
                if (isDir || !name.endsWith(".class")) {
                    return;
                }

                OutputStream os = null;
                PrintWriter out = null;
                try {
                    InputStream is = current.get();
                    ClassReader r = new ClassReader(is);
                    os = fo.openOutput(r.getClassName().replace('.', '/') + ".j", nameObject);
                    out = new PrintWriter(new OutputStreamWriter(os, encoding));
                    r.accept(new JasminifierClassAdapter(out, null), flags | ClassReader.EXPAND_FRAMES);
                } catch (IOException ioe) {
                    System.err.println("error in " + name);
                    ioe.printStackTrace(System.err);
                } finally {
                    IOUtils.closeQuietly(out);
                    IOUtils.closeQuietly(os);
                }
            }
        }).walk(jar);
    } finally {
        IOUtils.closeQuietly(fo);
    }
}

From source file:java.it.geosolutions.geoserver.rest.ConfigTest.java

@Test
public void insertStyles() throws FileNotFoundException, IOException {
    if (!enabled()) {
        LOGGER.info("Skipping test " + "insertStyles" + "for class:" + this.getClass().getSimpleName());
        return;//from   w  ww .j  a  va2s  . c  o  m
    }
    deleteAllStyles();

    File sldDir = new ClassPathResource("testdata").getFile();
    for (File sldFile : sldDir.listFiles((FilenameFilter) new SuffixFileFilter(".sld"))) {
        LOGGER.info("Existing styles: " + reader.getStyles().getNames());
        String basename = FilenameUtils.getBaseName(sldFile.toString());
        LOGGER.info("Publishing style " + sldFile + " as " + basename);
        assertTrue("Could not publish " + sldFile, publisher.publishStyle(sldFile, basename));
    }
}

From source file:gov.nih.nci.caarray.platforms.AbstractDataFileHandler.java

/**
 * {@inheritDoc}/*from   w  w w. j av a2s .co  m*/
 */
@Override
public List<String> getHybridizationNames() {
    return Collections.singletonList(FilenameUtils.getBaseName(this.caArrayFile.getName()));
}

From source file:it.geosolutions.geobatch.unredd.script.test.utils.ResourceLoader.java

public void loadResources(GeoStoreClient geostore) throws FileNotFoundException, IOException {
    deleteAllResources(geostore);//from  w  w  w  .  j  a va  2s  .c  o  m

    File geostoreDir = loadFile("georepo/resources");
    for (File resFile : geostoreDir.listFiles((FilenameFilter) new PrefixFileFilter("resource"))) {
        Resource res = JAXB.unmarshal(resFile, Resource.class);
        LOGGER.info("LOADED " + res.getCategory().getName() + " : " + res.getName());

        String basename = FilenameUtils.getBaseName(resFile.getName());
        String sid = basename.substring(basename.indexOf("_") + 1);
        String dataFileName = "data_" + sid + ".txt";
        File dataFile = new File(geostoreDir, dataFileName);
        String data = IOUtils.toString(new FileReader(dataFile));

        RESTResource restRes = FlowUtil.copyResource(res);
        restRes.setData(data);

        LOGGER.info("INSERTING " + res.getCategory().getName() + " : " + res.getName());
        geostore.insert(restRes);
    }

}

From source file:exifIndexer.MetadataReader.java

public static void walk(String path, boolean is_recursive) {

    File root = new File(path);
    File[] list = root.listFiles();
    String filePath;/*from ww w .  j  av  a2  s.c o  m*/
    String fileName;
    String fileExt;
    String valueName;
    String tagName;
    String catName;
    Metadata metadata;
    long fileSize;
    long fileLastModified;
    java.util.Date utilDate;
    java.sql.Date sqlDate;

    String sql = "{ ? = call INSERTIMAGE(?,?,?,?,?) }";
    String sqlMetaData = "{ call INSERTMETADATA (?,?,?,?) }";

    CallableStatement statement;
    CallableStatement statementMeta;
    long result;

    if (list == null) {
        return;
    }

    for (File f : list) {
        if (f.isDirectory() && is_recursive) {
            walk(f.getAbsolutePath(), true);
        } else {

            filePath = FilenameUtils.getFullPath(f.getAbsolutePath());
            fileName = FilenameUtils.getBaseName(f.getName());
            fileExt = FilenameUtils.getExtension(f.getName());
            utilDate = new java.util.Date(f.lastModified());
            sqlDate = new java.sql.Date(utilDate.getTime());

            fileSize = f.length();

            try {
                metadata = ImageMetadataReader.readMetadata(f.getAbsoluteFile());
                try {
                    DBHandler db = new DBHandler();
                    db.openConnection();
                    Connection con = db.getCon();
                    // llamada al metodo insertar imagen SQL con (filePath,fileName,fileExtension,fileSize, fileLastModified)
                    statement = con.prepareCall(sql);
                    statement.setString(2, filePath);
                    statement.setString(3, fileName);
                    statement.setString(4, fileExt);
                    statement.setLong(5, fileSize);
                    statement.setDate(6, sqlDate);
                    statement.registerOutParameter(1, java.sql.Types.NUMERIC);
                    statement.execute();
                    result = statement.getLong(1);

                    // llamada al metodo insertar metadatos SQL con (idImg,valueName, tagName, catName)
                    for (Directory directory : metadata.getDirectories()) {
                        for (Tag tag : directory.getTags()) {

                            valueName = tag.getDescription();
                            tagName = tag.getTagName();
                            catName = directory.getName();

                            if (isNull(valueName) || isNull(tagName) || isNull(catName) || valueName.equals("")
                                    || tagName.equals("") || catName.equals("") || valueName.length() > 250
                                    || tagName.length() > 250 || catName.length() > 500) {
                                System.out.println("Exif row omitted.");
                                System.out.println("Omitting: [" + catName + "] " + tagName + " " + valueName);
                            } else {
                                statementMeta = con.prepareCall(sqlMetaData);
                                statementMeta.setLong(1, result);
                                statementMeta.setString(2, valueName);
                                statementMeta.setString(3, tagName);
                                statementMeta.setString(4, catName);
                                statementMeta.executeUpdate();
                            }
                        }
                    }
                    db.closeConnection();
                } catch (SQLException ex) {
                    System.err.println("Error with SQL command. \n" + ex);
                }
            } catch (ImageProcessingException e) {
                System.out.println("ImageProcessingException " + e);
            } catch (IOException e) {
                System.out.println("IOException " + e);
            }

        }

    }

}

From source file:ch.cyberduck.core.transfer.upload.RenameExistingFilter.java

/**
 * Rename existing file on server if there is a conflict.
 *//* w  w w  . j  av  a 2s  . co  m*/
@Override
public void apply(final Path file, final Local local, final TransferStatus status,
        final ProgressListener listener) throws BackgroundException {
    // Rename existing file before putting new file in place
    if (status.isExists()) {
        Path rename;
        do {
            final String proposal = MessageFormat.format(
                    PreferencesFactory.get().getProperty("queue.upload.file.rename.format"),
                    FilenameUtils.getBaseName(file.getName()),
                    UserDateFormatterFactory.get().getMediumFormat(System.currentTimeMillis(), false)
                            .replace(Path.DELIMITER, '-').replace(':', '-'),
                    StringUtils.isNotBlank(file.getExtension()) ? String.format(".%s", file.getExtension())
                            : StringUtils.EMPTY);
            rename = new Path(file.getParent(), proposal, file.getType());
        } while (find.find(rename));
        if (log.isInfoEnabled()) {
            log.info(String.format("Rename existing file %s to %s", file, rename));
        }
        move.move(file, rename, new TransferStatus().exists(false), new Delete.DisabledCallback(),
                new DisabledConnectionCallback());
        if (log.isDebugEnabled()) {
            log.debug(String.format("Clear exist flag for file %s", file));
        }
        status.setExists(false);
    }
    super.apply(file, local, status, listener);
}

From source file:ch.cyberduck.CreateFileController.java

protected void createFile(final Path workdir, final String filename, final boolean edit) {
    final BrowserController c = (BrowserController) parent;

    c.background(new BrowserBackgroundAction(c) {
        final Path file = PathFactory.createPath(this.getSession(), workdir.getAbsolute(),
                LocalFactory.createLocal(Preferences.instance().getProperty("tmp.dir"), filename));

        public void run() {
            int no = 0;
            while (file.getLocal().exists()) {
                no++;/*from  ww  w. j  a  v  a  2 s.c om*/
                String proposal = FilenameUtils.getBaseName(filename) + "-" + no;
                if (StringUtils.isNotBlank(FilenameUtils.getExtension(filename))) {
                    proposal += "." + FilenameUtils.getExtension(filename);
                }
                file.setLocal(
                        LocalFactory.createLocal(Preferences.instance().getProperty("tmp.dir"), proposal));
            }
            file.getLocal().touch();
            TransferOptions options = new TransferOptions();
            options.closeSession = false;
            try {
                UploadTransfer upload = new UploadTransfer(file);
                upload.start(new TransferPrompt() {
                    public TransferAction prompt() {
                        return TransferAction.ACTION_OVERWRITE;
                    }
                }, options);
                file.getParent().invalidate();
            } finally {
                file.getLocal().delete(false);
            }
            if (file.exists()) {
                //                    if(edit) {
                //                        Editor editor = EditorFactory.createEditor(c, file);
                //                        editor.open();
                //                    }
            }
        }

        @Override
        public String getActivity() {
            return MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"), file.getName());
        }

        @Override
        public void cleanup() {
            if (filename.charAt(0) == '.') {
                c.setShowHiddenFiles(true);
            }
            c.reloadData(Collections.singletonList(file));
        }
    });
}