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

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

Introduction

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

Prototype

public static String removeExtension(String filename) 

Source Link

Document

Removes the extension from a filename.

Usage

From source file:ch.cyberduck.core.local.LaunchServicesApplicationFinder.java

/**
 * Determine the human readable application name for a given bundle identifier.
 *
 * @param search Bundle identifier//from ww w  .ja v a  2s  . c om
 * @return Application human readable name
 */
@Override
public Application getDescription(final String search) {
    if (applicationNameCache.containsKey(search)) {
        return applicationNameCache.get(search);
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Find application for %s", search));
    }
    final String identifier;
    final String name;
    synchronized (NSWorkspace.class) {
        final NSWorkspace workspace = NSWorkspace.sharedWorkspace();
        final String path;
        if (null != workspace.absolutePathForAppBundleWithIdentifier(search)) {
            path = workspace.absolutePathForAppBundleWithIdentifier(search);
        } else {
            log.warn(String.format(
                    "Cannot determine installation path for bundle identifier %s. Try with name.", search));
            path = workspace.fullPathForApplication(search);
        }
        if (StringUtils.isNotBlank(path)) {
            final NSBundle app = NSBundle.bundleWithPath(path);
            if (null == app) {
                log.error(String.format("Loading bundle %s failed", path));
                identifier = search;
                name = FilenameUtils.removeExtension(LocalFactory.get(path).getDisplayName());
            } else {
                NSDictionary dict = app.infoDictionary();
                if (null == dict) {
                    log.error(String.format("Loading application dictionary for bundle %s failed", path));
                    applicationNameCache.put(search, Application.notfound);
                    return null;
                } else {
                    final NSObject bundlename = dict.objectForKey("CFBundleName");
                    if (null == bundlename) {
                        log.warn(String.format("No CFBundleName in bundle %s", path));
                        name = FilenameUtils.removeExtension(LocalFactory.get(path).getDisplayName());
                    } else {
                        name = bundlename.toString();
                    }
                    final NSObject bundleIdentifier = dict.objectForKey("CFBundleIdentifier");
                    if (null == bundleIdentifier) {
                        log.warn(String.format("No CFBundleName in bundle %s", path));
                        identifier = search;
                    } else {
                        identifier = bundleIdentifier.toString();
                    }

                }
            }
        } else {
            log.warn(String.format("Cannot determine installation path for %s", search));
            applicationNameCache.put(search, Application.notfound);
            return Application.notfound;
        }
    }
    final Application application = new Application(identifier, name);
    applicationNameCache.put(search, application);
    return application;
}

From source file:com.yoncabt.ebr.executor.jasper.JasperReport.java

private static File compile(File jrxmlFile) throws JRException {
    logManager.info(jrxmlFile + " compile");
    File jasperFile = new File(jrxmlFile.getAbsolutePath().replace(".jrxml", ".jasper"));
    jasperFile.getParentFile().mkdirs();
    if (jrxmlFile.lastModified() > jasperFile.lastModified()) {
        JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile.getAbsolutePath());
        net.sf.jasperreports.engine.JasperReport jasperReport = JasperCompileManager
                .compileReport(jasperDesign);
        JRSaver.saveObject(jasperReport, jasperFile.getAbsolutePath());
        //toLog("Saving compiled report to: " + jasperFile.getAbsolutePath());
        //Compile sub reports
        JRElementsVisitor.visitReport(jasperReport, new JRVisitor() {

            @Override/*from   w ww .jav a  2 s.  com*/
            public void visitBreak(JRBreak breakElement) {
            }

            @Override
            public void visitChart(JRChart chart) {
            }

            @Override
            public void visitCrosstab(JRCrosstab crosstab) {
            }

            @Override
            public void visitElementGroup(JRElementGroup elementGroup) {
            }

            @Override
            public void visitEllipse(JREllipse ellipse) {
            }

            @Override
            public void visitFrame(JRFrame frame) {
            }

            @Override
            public void visitImage(JRImage image) {
            }

            @Override
            public void visitLine(JRLine line) {
            }

            @Override
            public void visitRectangle(JRRectangle rectangle) {
            }

            @Override
            public void visitStaticText(JRStaticText staticText) {
            }

            @Override
            public void visitSubreport(JRSubreport subreport) {
                String subReportName = subreport.getExpression().getText().replace("repo:", "");
                subReportName = StringUtils.strip(subReportName, "\"");
                //uzant jrxml olduuna emin olalm
                subReportName = FilenameUtils.removeExtension(subReportName) + ".jrxml";
                File subReportFile = new File(jrxmlFile.getParentFile(), subReportName);
                //Sometimes the same subreport can be used multiple times, but
                //there is no need to compile multiple times
                // burada tam path bulmak gerekebilir
                File compiledSubReportFile = compileIfRequired(subReportFile.getAbsoluteFile());
                File destSubReportFile = new File(
                        EBRConf.INSTANCE.getValue("report.subreport.path",
                                "/home/eastblue/apache-tomcat-8.0.28/webapps/ebr/WEB-INF/classes"),
                        compiledSubReportFile.getName());
                try {
                    // copy to classpoath
                    FileUtils.copyFile(compiledSubReportFile, destSubReportFile);
                } catch (IOException ex) {
                    throw new ReportException(ex);
                }
            }

            @Override
            public void visitTextField(JRTextField textField) {
            }

            @Override
            public void visitComponentElement(JRComponentElement componentElement) {
            }

            @Override
            public void visitGenericElement(JRGenericElement element) {
            }

        });
        JasperCompileManager.compileReportToFile(jrxmlFile.getAbsolutePath(), jasperFile.getAbsolutePath());
    }
    return jasperFile;
}

From source file:es.ehu.si.ixa.pipe.parse.Annotate.java

/**
 * Takes a file containing Penn Treebank oneline annotation and annotates the
 * headwords, saving it to a file with the *.th extension. Optionally also
 * processes recursively an input directory adding heads only to the files
 * with the files with the specified extension
 * /*  w w w  .j a v  a 2s.co m*/
 * @param dir
 *          the input file or directory
 * @param ext
 *          the extension to look for in the directory
 * @throws IOException
 */
public void processTreebankWithHeadWords(File dir, String ext) throws IOException {
    // process one file
    if (dir.isFile()) {
        List<String> inputTrees = FileUtils.readLines(new File(dir.getCanonicalPath()), "UTF-8");
        File outfile = new File(FilenameUtils.removeExtension(dir.getPath()) + ".th");
        String outTree = addHeadWordsToTreebank(inputTrees);
        FileUtils.writeStringToFile(outfile, outTree, "UTF-8");
        System.err.println(">> Wrote headWords to Penn Treebank to " + outfile);
    } else {
        // recursively process directories
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            if (ext == null) {
                System.out.println(
                        "For recursive directory processing of treebank files specify the extension of the files containing the syntactic trees.");
                System.exit(1);
            }
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    processTreebankWithHeadWords(listFile[i], ext);
                } else {
                    try {
                        List<String> inputTrees = FileUtils.readLines(
                                new File(FilenameUtils.removeExtension(listFile[i].getCanonicalPath()) + ext),
                                "UTF-8");
                        File outfile = new File(FilenameUtils.removeExtension(listFile[i].getPath()) + ".th");
                        String outTree = addHeadWordsToTreebank(inputTrees);
                        FileUtils.writeStringToFile(outfile, outTree, "UTF-8");
                        System.err.println(">> Wrote headWords to " + outfile);
                    } catch (FileNotFoundException noFile) {
                        continue;
                    }
                }
            }
        }
    }
}

From source file:io.proleap.cobol.TestGenerator.java

protected static String getInputFilename(final File inputFile) {
    final String result = firstToUpper(FilenameUtils.removeExtension(inputFile.getName()));
    return result;
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();//from  ww w  . j a  v a 2  s  . c  om
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:edu.ur.ir.repository.service.DefaultRepositoryService.java

/**
 * Create a versioned file in the repository which is a file that is emtpy.
 * //ww  w.  ja v  a 2  s. c om
 * @param repositoryId - id of the repository to create the versioned file in.
 * @param fileName - name user wishes to give the file.
 * @param descrption - description of the file.
 * @param original file name - original file name used to upload this file
 * and the user wishes to give the file a name that is different than the one on the file system
 * 
 * @return - the created versioned file.
 * @throws edu.ur.file.IllegalFileSystemNameException 
 */
public VersionedFile createVersionedFile(IrUser user, Repository repository, String fileName,
        String description) throws IllegalFileSystemNameException {
    FileInfo info = createFileInfo(repository, fileName);

    VersionedFile versionedFile = new VersionedFile(user, info, FilenameUtils.removeExtension(fileName));
    versionedFile.setDescription(description);
    versionedFileDAO.makePersistent(versionedFile);

    return versionedFile;
}

From source file:ffx.algorithms.mc.RosenbluthCBMC.java

private void write() {
    if (writer == null) {
        writer = new PDBFilter(mola.getFile(), mola, null, null);
    }//from w  w w. j ava 2s. co  m
    String filename = FilenameUtils.removeExtension(mola.getFile().toString());
    filename = mola.getFile().getAbsolutePath();
    if (!filename.contains("_mc")) {
        filename = FilenameUtils.removeExtension(filename) + "_mc.pdb";
    }
    File file = new File(filename);
    writer.writeFile(file, false);
}

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

private void addArchive(File element) throws IOException {
    if (addCached(element)) {
        return;/*from w  w  w  . ja v a 2s.c  om*/
    }

    List classes = new ArrayList();
    List resources = new ArrayList();
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(element);
        Enumeration entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                String name = entry.getName();

                if ("class".equals(FilenameUtils.getExtension(name))) {
                    String className = FilenameUtils.removeExtension(name).replace('/', '.').replace('\\', '.');

                    classes.add(className);
                    addClass(className, element);
                } else {
                    String resourcePath = name.replace('\\', File.separatorChar);

                    resources.add(resourcePath);
                    addResource(resourcePath, element);
                }
            }
        }

        CACHED_BY_ELEMENT.put(element, new Cached(classes, resources));
    } finally {
        // IOUtils has no closeQuietly for Closable in the 1.x series.
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ex) {
                // ignored
            }
        }
    }
}

From source file:de.nbi.ontology.test.OntologyMatchTest.java

/**
 * Test, if terms are properly match to concept labels. The a list of terms
 * contains a term in each line.//www.  j  ava  2  s.co m
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "similarTestFiles", groups = { "functest" })
public void similar(File inFile) throws IOException {
    log.info("Processing " + inFile.getName());
    String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath());
    File outFile = new File(basename + ".out");
    File resFile = new File(basename + ".res");

    List<String> terms = FileUtils.readLines(inFile);
    PrintWriter w = new PrintWriter(new FileWriter(outFile));
    for (String term : terms) {
        log.trace("** matching " + term);
        w.println(index.getSimilarMatches(term));
    }
    w.flush();
    w.close();

    Assert.assertTrue(FileUtils.contentEquals(outFile, resFile));
}

From source file:com.aurel.track.exchange.importer.MsProjectImportActionTest.java

/**
 * This method executes the ms project file import. In case if needed handles resource mappings.
 *//*from   www .j a  v  a2s .c o  m*/
@Test
public void testSubmitResourceMapping() {
    try {
        File msProjectFolder = new File(MS_PROJECT_FILES_PATH);
        File[] listOfFiles = msProjectFolder.listFiles();
        for (File fileToUpload : listOfFiles) {
            if (fileToUpload.isFile()) {
                System.out.println("Testing the following Ms. project file: " + fileToUpload.getName());
                File tempFile = new File(
                        msProjectFolder + "/" + FilenameUtils.removeExtension(fileToUpload.getName()) + "Tmp."
                                + FilenameUtils.getExtension(fileToUpload.getName()));

                Files.copy(fileToUpload, tempFile);

                MsProjectExchangeDataStoreBean msProjectExchangeDataStoreBean;

                msProjectExchangeDataStoreBean = MsProjectExchangeBL.initMsProjectExchangeBeanForImport(
                        PROJECT_OR_RELEASE_ID, PersonBL.loadByPrimaryKey(1), tempFile, null);

                SortedMap<String, Integer> resourceNameToResourceUIDMap = MsProjectImporterBL
                        .getResourceNameToResourceUIDMap(msProjectExchangeDataStoreBean.getWorkResources());
                Map<Integer, Integer> resourceUIDToPersonIDMap = new HashMap<Integer, Integer>();
                for (String key : resourceNameToResourceUIDMap.keySet()) {
                    resourceUIDToPersonIDMap.put(resourceNameToResourceUIDMap.get(key), DEFAULT_PERSON_ID);

                }
                sessionMap.put("msProjectImporterBean", msProjectExchangeDataStoreBean);
                ActionProxy actionProxy = getActionProxy("/msProjectImport!submitResourceMapping.action");
                actionProxy.getInvocation().getInvocationContext().setSession(sessionMap);

                String result = actionProxy.execute();
                String responseText = response.getContentAsString();

                assertTrue(responseText.length() > 0);
                assertNotNull(responseText);
                System.out.println("Test method name: submitResourceMapping result: " + result + " response: "
                        + responseText);
                deleteProjectTasks();
                if (tempFile.exists()) {
                    tempFile.delete();
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}