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

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

Introduction

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

Prototype

public static String getExtension(String filename) 

Source Link

Document

Gets the extension of a filename.

Usage

From source file:com.zhenhappy.ems.action.user.VisaAction.java

@RequestMapping(value = "/visa/saveVisa", method = RequestMethod.POST)
public ModelAndView saveVisa(@ModelAttribute(Principle.PRINCIPLE_SESSION_ATTRIBUTE) Principle principle,
        @ModelAttribute SaveVisaInfoRequest visa,
        @RequestParam(value = "license", required = false) MultipartFile license,
        @RequestParam(value = "passportPageFile", required = false) MultipartFile passportPage) {
    ModelAndView modelAndView = new ModelAndView("/user/callback");
    try {/*from ww w .j a  va 2  s .  c  om*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(visa.getBirthDay())) {
            visa.setBirth(sdf.parse(visa.getBirthDay()));
        }
        if (StringUtils.isNotEmpty(visa.getFromDate())) {
            visa.setFrom(sdf.parse(visa.getFromDate()));
        }
        if (StringUtils.isNotEmpty(visa.getToDate())) {
            visa.setTo(sdf.parse(visa.getToDate()));
        }
        if (StringUtils.isNotEmpty(visa.getExpireDate())) {
            visa.setExpDate(sdf.parse(visa.getExpireDate()));
        }
        if (license != null) {
            String fileName = systemConfig.getVal(Constants.appendix_directory) + "/" + new Date().getTime()
                    + "." + FilenameUtils.getExtension(license.getOriginalFilename());
            if (license != null && license.getSize() != 0) {
                FileUtils.copyInputStreamToFile(license.getInputStream(), new File(fileName));
                visa.setBusinessLicense(fileName);
            }
        }

        if (passportPage != null) {
            String fileName = systemConfig.getVal(Constants.appendix_directory) + "/" + new Date().getTime()
                    + "." + FilenameUtils.getExtension(passportPage.getOriginalFilename());
            if (passportPage != null && passportPage.getSize() != 0) {
                FileUtils.copyInputStreamToFile(passportPage.getInputStream(), new File(fileName));
                visa.setPassportPage(fileName);
            }
        }
        visa.setEid(principle.getExhibitor().getEid());
        TVisa temp = new TVisa();
        BeanUtils.copyProperties(visa, temp);
        visaService.saveOrUpdate(temp);
        modelAndView.addObject("method", "addSuccess");
    } catch (Exception e) {
        log.error("add visa error", e);
        modelAndView.addObject("method", "addFailure");
    }
    return modelAndView;
}

From source file:com.us.servlet.FileManager.java

@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    // //from w  w w .  j  a  va  2  s  .  c  o m
    final String fileRoot = AppHelper.KIND_CONFIG.get(FILE_MGR_ROOT).toString();
    File root = FileHelper.getFile(AppHelper.APPSET.getFilePath(), fileRoot);

    PrintWriter out = resp.getWriter();
    final String path = req.getParameter("path") != null ? req.getParameter("path") : "";
    final String dirType = req.getParameter("dir").toLowerCase();// ??name or size or type
    String order = req.getParameter("order") != null ? req.getParameter("order").toLowerCase() : "name";
    if (!root.exists()) {
        root.mkdirs();
    }

    String currentUrl = AppHelper.APPSET.getWebPath() + fileRoot + path;
    String currentDirPath = path;
    String moveupDirPath = "";
    if (!"".equals(path)) {
        String str = currentDirPath.substring(0, currentDirPath.length() - 1);
        moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
    }

    String[] imageType = AppHelper.KIND_CONFIG.get(FILE_IMAGE_TYPE).toString().split(",");

    // ??..
    if (path.indexOf("..") >= 0) {
        out.println(I118Helper.i118Value("${fileMgr.accessFail}", req));
        return;
    }
    // ??/
    if (!"".equals(path) && !path.endsWith("/")) {
        out.println(I118Helper.i118Value("${fileMgr.badArgs}", req));
        return;
    }

    File showDir = FileHelper.getFile(root, currentDirPath);
    if (!showDir.isDirectory()) {
        out.println(I118Helper.i118Value("${fileMgr.rootNotExist}", req));
        return;
    }

    List<Hashtable<String, Object>> fileList = new ArrayList<Hashtable<String, Object>>();
    final File[] listFiles = showDir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            if (FileHelper.getFile(dir, name).isDirectory()) {
                return true;
            }
            final List<String> fileTypeList = Arrays
                    .<String>asList(AppHelper.KIND_CONFIG.get(dirType).toString().split(","));
            return fileTypeList.contains(FilenameUtils.getExtension(name));
        }
    });
    if (listFiles != null) {
        for (File file : listFiles) {
            Hashtable<String, Object> hash = new Hashtable<String, Object>();
            String fileName = file.getName();
            if (file.isDirectory()) {
                hash.put("is_dir", true);
                hash.put("has_file", (file.listFiles() != null));
                hash.put("filesize", 0L);
                hash.put("is_photo", false);
                hash.put("filetype", "");
            } else if (file.isFile()) {
                String fileExt = FilenameUtils.getExtension(fileName).toLowerCase();
                hash.put("is_dir", false);
                hash.put("has_file", false);
                hash.put("filesize", file.length());
                hash.put("is_photo", Arrays.<String>asList(imageType).contains(fileExt));
                hash.put("filetype", fileExt);
            }
            hash.put("filename", fileName);
            hash.put("datetime", DateUtil.format(file.lastModified(), DateUtil.DATETIME_PATTERN));
            fileList.add(hash);
        }
    }

    if ("size".equals(order)) {
        Collections.sort(fileList, new SizeComparator<Hashtable<String, Object>>());
    } else if ("type".equals(order)) {
        Collections.sort(fileList, new TypeComparator<Hashtable<String, Object>>());
    } else {
        Collections.sort(fileList, new NameComparator<Hashtable<String, Object>>());
    }

    KindFileMgr mgr = new KindFileMgr();
    mgr.setMoveup_dir_path(moveupDirPath);
    mgr.setCurrent_dir_path(currentDirPath);
    mgr.setCurrent_url(currentUrl);
    mgr.setTotal_count(fileList.size());
    mgr.setFile_list(fileList);
    resp.setContentType("application/json; charset=UTF-8");
    out.println(JSONHelper.obj2Json(mgr));
}

From source file:eu.edisonproject.classification.prepare.controller.DataPrepare.java

@Override
public void execute() {
    File file = new File(inputFolder);
    Document davro;//from  ww  w . ja  v  a2 s .  c om
    DocumentAvroSerializer dAvroSerializer = null;
    if (file.isDirectory()) {
        File[] filesInDir = file.listFiles();
        //            Arrays.sort(filesInDir);

        //            LocalDate date = getCreationDate(file);
        for (File f : filesInDir) {
            if (f.isFile() && FilenameUtils.getExtension(f.getName()).endsWith("txt")) {
                LocalDate date = getCreationDate(f);
                documentObject = new DocumentObject();
                documentObject.setDate(date);
                ReaderFile rf = new ReaderFile(f.getAbsolutePath());
                String contents = rf.readFile();
                cleanStopWord.setDescription(contents);
                String cleanCont = cleanStopWord.execute().toLowerCase();
                cleanLemmatisation.setDescription(cleanCont);
                cleanCont = cleanLemmatisation.execute();
                documentObject.setDescription(cleanCont);
                documentObject.setDocumentId(FilenameUtils.removeExtension(f.getName()));
                documentObject.setTitle(f.getParentFile().getName());
                //                extract(this.getDocumentObject(), f.getPath());
                //                documentObject.setDescription(documentObject.getDescription().toLowerCase());
                //                clean(this.getDocumentObject().getDescription());
                if (documentObject.getDescription().equals("")) {
                    continue;
                }
                documentObjectList.add(this.getDocumentObject());

                davro = new Document();
                davro.setDocumentId(documentObject.getDocumentId());
                davro.setTitle(documentObject.getTitle());
                davro.setDate(documentObject.getDate().toString());
                davro.setDescription(documentObject.getDescription());

                if (dAvroSerializer == null) {
                    dAvroSerializer = new DocumentAvroSerializer(outputFolder + File.separator
                            + documentObject.getTitle().replaceAll(" ", "_") + date + ".avro",
                            davro.getSchema());
                }
                Logger.getLogger(Text2Avro.class.getName()).log(Level.INFO, "Adding :{0} to: {1}{2}{3}{4}.avro",
                        new Object[] { documentObject.getDocumentId(), outputFolder, File.separator,
                                documentObject.getTitle().replaceAll(" ", "_"), date });
                dAvroSerializer.serialize(davro);
            }

        }

        if (dAvroSerializer != null) {
            dAvroSerializer.close();
            dAvroSerializer = null;
        }
    }

}

From source file:fr.pilato.elasticsearch.crawler.fs.rest.UploadApi.java

@POST
@Produces(MediaType.APPLICATION_JSON)//from  w w  w. j  a  v a  2 s .c  o  m
@Consumes(MediaType.MULTIPART_FORM_DATA)
public UploadResponse post(@QueryParam("debug") String debug, @QueryParam("simulate") String simulate,
        @FormDataParam("id") String id, @FormDataParam("file") InputStream filecontent,
        @FormDataParam("file") FormDataContentDisposition d) throws IOException, NoSuchAlgorithmException {

    // Create the Doc object
    Doc doc = new Doc();

    String filename = new String(d.getFileName().getBytes("ISO-8859-1"), "UTF-8");
    long filesize = d.getSize();

    // File
    doc.getFile().setFilename(filename);
    doc.getFile().setExtension(FilenameUtils.getExtension(filename).toLowerCase());
    doc.getFile().setIndexingDate(localDateTimeToDate(LocalDateTime.now()));
    // File

    // Path
    if (id == null) {
        id = SignTool.sign(filename);
    } else if (id.equals("_auto_")) {
        // We are using a specific id which tells us to generate a unique _id like elasticsearch does
        id = TIME_UUID_GENERATOR.getBase64UUID();
    }

    doc.getPath().setVirtual(filename);
    doc.getPath().setReal(filename);
    // Path

    // Read the file content
    TikaDocParser.generate(settings, filecontent, filename, doc, messageDigest, filesize);

    String url = null;
    if (Boolean.parseBoolean(simulate)) {
        logger.debug("Simulate mode is on, so we skip sending document [{}] to elasticsearch.", filename);
    } else {
        logger.debug("Sending document [{}] to elasticsearch.", filename);
        bulkProcessor
                .add(new org.elasticsearch.action.index.IndexRequest(settings.getElasticsearch().getIndex(),
                        "doc", id).setPipeline(settings.getElasticsearch().getPipeline())
                                .source(DocParser.toJson(doc), XContentType.JSON));
        // Elasticsearch entity coordinates (we use the first node address)
        Elasticsearch.Node node = settings.getElasticsearch().getNodes().get(0);
        url = buildUrl(node.getScheme().toLowerCase(), node.getHost(), node.getPort()) + "/"
                + settings.getElasticsearch().getIndex() + "/" + "doc" + "/" + id;
    }

    UploadResponse response = new UploadResponse();
    response.setOk(true);
    response.setFilename(filename);
    response.setUrl(url);

    if (logger.isDebugEnabled() || Boolean.parseBoolean(debug)) {
        // We send the content back if debug is on or if we got in the query explicitly a debug command
        response.setDoc(doc);
    }

    return response;
}

From source file:bboss.org.artofsolving.jodconverter.OfficeDocumentConverter.java

public File getRealWordFromWordTemplateWithMapdatas(String wordtemplate, String wordfile,
        Map<String, Object> bookdatas) throws Exception {
    String outputExtension = FilenameUtils.getExtension(wordfile);
    DocumentFormat outputFormat = formatRegistry.getFormatByExtension(outputExtension);
    String inputExtension = FilenameUtils.getExtension(outputExtension);
    DocumentFormat inputFormat = formatRegistry.getFormatByExtension(inputExtension);
    WorkBookmarkConvertorTask conversionTask = new WorkBookmarkConvertorTask(wordtemplate, wordfile, bookdatas,
            outputFormat);/* w  w  w  .j  a  v  a  2 s  .  c  om*/
    Map<String, Object> defaultLoadProperties = new HashMap<String, Object>();
    defaultLoadProperties.put("AsTemplate", new Boolean(true));
    defaultLoadProperties.put("Hidden", new Boolean(true));
    conversionTask.setDefaultLoadProperties(defaultLoadProperties);
    //         conversionTask.setDefaultStroreProperties(defaultLoadProperties);
    conversionTask.setInputFormat(inputFormat);
    officeManager.execute(conversionTask);
    return conversionTask.getOutputFile();
}

From source file:com.ikanow.aleph2.core.shared.utils.JarCacheUtils.java

/** Just creates a cached name as <lib bean id>.cache.jar
 * @param library_bean the library bean to cache
 * @return the cache name// w w w .  j ava  2 s .  com
 */
public static String buildCachedJarName(SharedLibraryBean library_bean) {
    if (library_bean.path_name().endsWith(".jar")) {
        return library_bean._id() + ".cache.jar";
    }
    if (library_bean.path_name().endsWith(".zip")) {
        return library_bean._id() + ".cache.zip";
    } else {
        return library_bean._id() + ".cache.misc." + FilenameUtils.getExtension(library_bean.path_name());
    }
}

From source file:net.sourceforge.atunes.kernel.modules.repository.LocalAudioObjectValidator.java

/**
 * Checks if a file is a valid audio file given its name This method does
 * not check if file exists or it's a directory or even if file is null
 * //from  w  w w.  j  ava2  s.  c o  m
 * @param file
 * @return if the file is a valid audio file
 */
@Override
public boolean isOneOfValidFormats(final File file) {
    return this.extensions.contains(FilenameUtils.getExtension(file.getName()).toLowerCase());
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

public boolean matchesExtension(String path) {
    String extension = FilenameUtils.getExtension(path).toLowerCase();
    return getFileExtensions().contains(extension);
}

From source file:com.sire.web.CajFacturaEnviadaBean.java

public void enviar() {
    if (!file.getFileName().isEmpty()) {
        LOGGER.log(Level.INFO, "file: {0}", file.getFileName());
        fileName = String.valueOf(Calendar.getInstance().getTimeInMillis()) + "."
                + FilenameUtils.getExtension(file.getFileName());
    } else {//from   w w w . j a  va  2s  .co  m
        addMessage("Advertencia", "Imgen requerida.", FacesMessage.SEVERITY_WARN);
        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getFlash().setKeepMessages(true);
        return;
    }

    LOGGER.log(Level.INFO, "cajFacturaEnviada: {0}", cajFacturaEnviada);

    cajFacturaEnviada.getCajFacturaEnviadaPK().setCodEmpresa(obtenerEmpresa());
    cajFacturaEnviada.getCajFacturaEnviadaPK().setSecuencial(null);
    cajFacturaEnviada.setFechaEstado(Calendar.getInstance().getTime());
    cajFacturaEnviada.setIdFoto(fileName);
    cajFacturaEnviada.setNombreUsuario(userManager.getCurrent());
    cajFacturaEnviada.getCajFacturaEnviadaPK().setCodSupervisor(
            obtenerPrySupervisorUsuario().getPrySupervisor().getPrySupervisorPK().getCodSupervisor());
    cajFacturaEnviada.setEstado("G");
    cajFacturaEnviada.setFechaDocumento(fechaDocumento);
    Response response = cajFacturaEnviadaFacadeREST.save_JSON(cajFacturaEnviada);
    if (response.getStatus() == 200) {
        savePicture();
        addMessage("Factura enviada exitosamente.",
                "Num. Factura: " + cajFacturaEnviada.getCajFacturaEnviadaPK().getNumDocumento(),
                FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getFlash().setKeepMessages(true);
    } else if (response.getStatus() == 404) {
        savePicture();
        String developerMessage = response.readEntity(ErrorMessage.class).getDeveloperMessage();
        LOGGER.log(Level.SEVERE, developerMessage);
        addMessage("Advertencia", developerMessage, FacesMessage.SEVERITY_WARN);
        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getFlash().setKeepMessages(true);
    }
    limpiar();
}

From source file:mitm.common.security.keystore.KeyStoreLoader.java

private void determineKeyStoreTypeFromFile(File file) throws KeyStoreException {
    String extension = StringUtils
            .defaultString(StringUtils.lowerCase(FilenameUtils.getExtension(file.getName())));

    keyStoreType = extensionMap.get(extension);

    if (keyStoreType == null) {
        throw new KeyStoreException("Unable to determine key store type for extension " + extension);
    }/*  w w  w.  j a v a2s .co m*/
}