Java Code Examples for org.apache.commons.io.FilenameUtils.getExtension()

The following are Jave code examples for showing how to use getExtension() of the org.apache.commons.io.FilenameUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jwala   File: PathValidator.java   View Source Code Vote up 6 votes
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
    try {
        if (StringUtils.isEmpty(value)) {
            return true; // do not validate empty value there are other constraints for that e.g. @NotNull, @Size etc...
        }

        final Path path = Paths.get(value);

        if (checkIfExists && !path.toFile().exists()) {
            return false;
        }

        final String fileExt = FilenameUtils.getExtension(value);
        return allowableFileExtensions.isEmpty() ||
               !allowableFileExtensions.stream().filter(fileExt::equalsIgnoreCase).findFirst().orElse(StringUtils.EMPTY).isEmpty();

    } catch (final InvalidPathException e) {
        LOGGER.error(e.getMessage(), e);
        return false;
    }
}
 
Example 2
Project: smarti   File: PropertyInjectionTransformer.java   View Source Code Vote up 6 votes
@Override
public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
    resource = transformerChain.transform(request, resource);

    final String fileName = resource.getFilename();
    final String fileExt = FilenameUtils.getExtension(fileName);
    switch (fileExt) {
        case "js":
        case "json":
        case "css":
        case "html":
            log.trace("format {} supported for Text-Injection", fileExt);
            return transformText(fileName, resource);
        default:
            log.trace("unsupported Resource-Type: {}", fileExt);
            return resource;
    }
}
 
Example 3
Project: onprom   File: UMLDiagramPanel.java   View Source Code Vote up 6 votes
public void exportImage() {
  try {
    File file = IOUtility.selectFileToSave(FileType.IMAGE);
    if (file != null) {
      Rectangle drawingArea = getDrawingArea();
      String extension = FilenameUtils.getExtension(file.getName());
      if (extension.equals("svg")) {
        SVGGraphics2D svgGenerator = IOUtility.getSVGGraphics(drawingArea.getSize());
        paintDrawing(svgGenerator, drawingArea.x, drawingArea.y);
        svgGenerator.stream(new FileWriter(file));
        svgGenerator.dispose();
      } else {
        BufferedImage bi = new BufferedImage(drawingArea.width, drawingArea.height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        paintDrawing(g, drawingArea.x, drawingArea.y);
        ImageIO.write(bi, extension, file);
        g.dispose();
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 4
Project: coffee-gb   File: Cartridge.java   View Source Code Vote up 6 votes
private static int[] loadFile(File file) throws IOException {
    String ext = FilenameUtils.getExtension(file.getName());
    try (InputStream is = new FileInputStream(file)) {
        if ("zip".equalsIgnoreCase(ext)) {
            try (ZipInputStream zis = new ZipInputStream(is)) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    String name = entry.getName();
                    String entryExt = FilenameUtils.getExtension(name);
                    if (Stream.of("gb", "gbc", "rom").anyMatch(e -> e.equalsIgnoreCase(entryExt))) {
                        return load(zis, (int) entry.getSize());
                    }
                    zis.closeEntry();
                }
            }
            throw new IllegalArgumentException("Can't find ROM file inside the zip.");
        } else {
            return load(is, (int) file.length());
        }
    }
}
 
Example 5
Project: Open_Source_ECOA_Toolset_AS5   File: GenerationUtils.java   View Source Code Vote up 6 votes
public static boolean validate(String container) {
	if (container != null) {
		String[] names = StringUtils.split(container, "/");
		IResource resource = wsRoot.findMember(new Path("/" + names[0]));
		IPath loc = resource.getLocation();
		File prjLoc = new File(loc.toString());
		File[] res = prjLoc.listFiles();
		HashMap<String, ArrayList<File>> fileGroups = new HashMap<String, ArrayList<File>>();
		HashMap<String, Integer> groupCnt = new HashMap<String, Integer>();
		for (File file : res) {
			String extension = FilenameUtils.getExtension(file.getName());
			ArrayList<File> list = fileGroups.get(extension);
			int cnt = (groupCnt.get(extension) == null) ? 0 : groupCnt.get(extension).intValue();
			if (list == null)
				list = new ArrayList<File>();
			list.add(file);
			cnt++;
			groupCnt.put(extension, new Integer(cnt));
			fileGroups.put(extension, list);
		}
		return !validate(groupCnt);
	}
	return false;
}
 
Example 6
Project: AndroidApktool   File: Androlib.java   View Source Code Vote up 6 votes
public void recordUncompressedFiles(ExtFile apkFile, Collection<String> uncompressedFilesOrExts) throws AndrolibException {
    try {
        Directory unk = apkFile.getDirectory();
        Set<String> files = unk.getFiles(true);
        String ext;

        for (String file : files) {
            if (isAPKFileNames(file) && !NO_COMPRESS_PATTERN.matcher(file).find()) {
                if (unk.getCompressionLevel(file) == 0) {
                    ext = FilenameUtils.getExtension(file);
                    if (ext.isEmpty()) {
                        ext = file;
                    }
                    if (! uncompressedFilesOrExts.contains(ext)) {
                        uncompressedFilesOrExts.add(ext);
                    }
                }
            }
        }
    } catch (DirectoryException ex) {
        throw new AndrolibException(ex);
    }
}
 
Example 7
Project: walle   File: Batch2Command.java   View Source Code Vote up 5 votes
private void generateChannelApk(final File inputFile, final File outputDir, final String channel, final String alias, final Map<String, String> extraInfo) {
    final String channelName = alias == null ? channel : alias;
    final String name = FilenameUtils.getBaseName(inputFile.getName());
    final String extension = FilenameUtils.getExtension(inputFile.getName());
    final String newName = name + "_" + channelName + "." + extension;
    final File channelApk = new File(outputDir, newName);
    try {
        FileUtils.copyFile(inputFile, channelApk);
        ChannelWriter.put(channelApk, channel, extraInfo);
    } catch (IOException | SignatureNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: onprom   File: FileTypeFilter.java   View Source Code Vote up 5 votes
public boolean accept(File file) {
    if (file.isDirectory()) {
        return true;
    }
    String extension = FilenameUtils.getExtension(file.getName());
    if (!extension.isEmpty()) {
        for (FileType ft : fileType) {
            if (ft.contains(extension))
                return true;
        }
    }
    return false;
}
 
Example 9
Project: JAddOn   File: JUtils.java   View Source Code Vote up 5 votes
public static String[] getNamesWithOnlyExtensionOufOfNames(String[] names) {
    String[] ausgabe = new String[names.length];
    int i = 0;
    for(String g : names) {
        ausgabe[i] = FilenameUtils.getExtension(g);
        i++;
    }
    return ausgabe;
}
 
Example 10
Project: NGB-master   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Gets file's extension, including .gz postfix if present
 * @param fileName the name of the file
 * @return file's extension
 */
public static String getFileExtension(String fileName) {
    String result = fileName;
    boolean compressed = false;
    if (fileName.endsWith(GZ_EXTENSION)) {
        result = fileName.substring(0, fileName.length() - GZ_EXTENSION.length());
        compressed = true;
    }
    result = FilenameUtils.getExtension(result);
    return '.' + (compressed ? (result + GZ_EXTENSION) : result);
}
 
Example 11
Project: gw4e.project   File: GraphWalkerFacade.java   View Source Code Vote up 5 votes
public static ContextFactory getContextFactory(Path path) {
	String extension = FilenameUtils.getExtension(path.toString());
	ContextFactory factory = cache.get(extension);
	if (factory == null) {
		throw new NullPointerException(" No factory found for : " + path);
	}
	return factory;
}
 
Example 12
Project: goobi-viewer-indexer   File: Utils.java   View Source Code Vote up 5 votes
/**
 * 
 * @param file
 * @return
 * @should extract file name correctly
 */
public static String extractPiFromFileName(Path file) {
    String fileExtension = FilenameUtils.getExtension(file.getFileName().toString());
    if (MetsIndexer.ANCHOR_UPDATE_EXTENSION.equals("." + fileExtension) || "delete".equals(fileExtension) || "purge".equals(fileExtension)) {
        String pi = FilenameUtils.getBaseName(file.getFileName().toString());
        if (pi.contains("#")) {
            pi = pi.substring(0, pi.indexOf("#"));
        }
        logger.info("Record identifier extracted from file name: {}", pi);
        return pi;
    }

    return null;
}
 
Example 13
Project: y2t187test   File: UserControl.java   View Source Code Vote up 5 votes
@RequestMapping(method=RequestMethod.POST)
public ModelAndView userRegist(@Valid User reguser,  BindingResult result,
		MultipartFile idPicPath,
		HttpServletRequest request) throws Exception{
	ModelAndView mv = new ModelAndView();
	//if(result.hasErrors()){
	//	mv.setViewName("useradd");
	//}else{
		// ��ȡWebContent����Ŀ¼���·��
		String path = request.getServletContext().getRealPath("/upload");
	
		// �����ϴ���ͼƬ�ļ�
		String fileName = idPicPath.getOriginalFilename(); // ԭʼ�ļ���
		// �ļ��� = "����ַ������" + ".��׺��"
		String ext = FilenameUtils.getExtension(fileName);
		fileName = UUID.randomUUID().toString() + "." + ext;
				//System.currentTimeMillis() 
				//Math.random() * 100000
		
		File file = 
				new File(path + "/" + fileName);
		idPicPath.transferTo(file);  // "���Ϊ"ָ��Ŀ���ļ�
		
		reguser.setIdpicpath("upload/" + fileName); // �ļ����·��(д����ݿ�)
		
		int count = userService.insertUser(reguser);
		if(count > 0) {
			// ע��ɹ�����ת���û��б�ҳ��
			// �ض��� response.sendRedirect("/user");
			mv.setViewName("redirect:/user");
		}else{
			mv.setViewName("useradd");
		}
	//}
	return mv;
}
 
Example 14
Project: sctalk   File: ThumbUrlUtils.java   View Source Code Vote up 5 votes
/**
 * 缩略图文件URL/ID编辑 <br>
 * 取缩略图
 * 
 * @param orgiUrl 原图URL
 * @param width 文件宽
 * @param height 文件高
 * @return 缩略图URl
 */
public static String getThumbUrl(String orgiUrl, int width, int height) {

    if (orgiUrl == null) {
        return null;
    }

    String extension = FilenameUtils.getExtension(orgiUrl);
    if (extension == null) {
        return orgiUrl;
    }

    if ("jpg".equalsIgnoreCase(extension)) {
        // 缩略图
    } else if ("png".equalsIgnoreCase(extension)) {
        // 缩略图
    } else {
        return orgiUrl;
    }

    int extensionPos = orgiUrl.length() - extension.length() - 1;

    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(orgiUrl.substring(0, extensionPos));
    stringBuffer.append("_").append(width).append("x").append(height);
    stringBuffer.append(orgiUrl.substring(extensionPos));

    return stringBuffer.toString();
}
 
Example 15
Project: osc-core   File: PluginUploader.java   View Source Code Vote up 4 votes
private boolean validateFileExtension(String fileName) {
    String extension = FilenameUtils.getExtension(fileName);
    return extension.equals("bar");
}
 
Example 16
Project: goobi-viewer-indexer   File: SingleRepositoryStrategy.java   View Source Code Vote up 4 votes
@Override
public DataRepository[] selectDataRepository(String pi, Path dataFile, Map<String, Path> dataFolders, SolrHelper solrHelper)
        throws FatalIndexerException {
    DataRepository[] ret = new DataRepository[] { null, null };

    // Extract PI from the file name, if not value was passed (e.g. when deleting a record)
    if (StringUtils.isEmpty(pi) && dataFile != null) {
        String fileExtension = FilenameUtils.getExtension(dataFile.getFileName().toString());
        if (MetsIndexer.ANCHOR_UPDATE_EXTENSION.equals("." + fileExtension) || "delete".equals(fileExtension) || "purge".equals(fileExtension)) {
            pi = Utils.extractPiFromFileName(dataFile);
        }
    }
    if (StringUtils.isBlank(pi)) {
        if (dataFile != null) {
            logger.error("Could not parse PI from '{}'", dataFile.getFileName().toString());
        }
        return ret;
    }

    String previousRepository = null;
    try {
        // Look up previous repository in the index
        previousRepository = solrHelper.findCurrentDataRepository(pi);
    } catch (SolrServerException e) {
        logger.error(e.getMessage(), e);
    }
    if (previousRepository != null) {
        if ("?".equals(previousRepository)) {
            // Record is already indexed, but not in a data repository
            ret[0] = new DataRepository("");
            return ret;
        }

        // Find previous repository
        for (DataRepository repository : dataRepositories) {
            if (previousRepository.equals(repository.getPath())) {
                logger.info(
                        "'{}' is currently indexed in data repository '{}'. Since 'SingleRepositoryStrategy' is configured, the record will be moved to out of the repository.",
                        pi, previousRepository);
                ret[0] = new DataRepository("");
                ret[1] = repository;
                return ret;
            }
        }
        logger.warn("Previous data repository for '{}' does not exist: {}", pi, previousRepository);
    }

    ret[0] = new DataRepository("");
    return ret;
}
 
Example 17
Project: CodeCompilerApp   File: AccessStorageApi.java   View Source Code Vote up 4 votes
public static String getExtension(Context context, Uri uri) {
    return FilenameUtils.getExtension(getName(context, uri));
}
 
Example 18
Project: FiveMinsMore   File: MapsActivity.java   View Source Code Vote up 4 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data == null || resultCode != RESULT_OK)
        return;

    ArrayList<NormalFile> fileList = data.getParcelableArrayListExtra(Constant.RESULT_PICK_FILE);
    if (fileList.isEmpty())
        return;

    switch (requestCode) {
        case REQUEST_CODE_PICK_MAPSFORGE_FILE:
            mapFile = fileList.get(0).getPath();

            final TextView currentMapFile =
                    (TextView) currentDialog.findViewById(R.id.current_map_file);
            currentMapFile.setText(new File(mapFile).getName());

            break;

        case REQUEST_CODE_PICK_MAPSFORGE_THEME_FILE:
            themeFile = fileList.get(0).getPath();

            final TextView currentThemeFile =
                    (TextView) currentDialog.findViewById(R.id.current_theme_file);
            currentThemeFile.setText(new File(themeFile).getName());

            break;

        case REQUEST_CODE_PICK_GPX_FILE:
            for (NormalFile fileData : fileList) {
                File file = new File(fileData.getPath());
                String suffix = FilenameUtils.getExtension(file.getName());
                if (suffix.equals(SUFFIX_GPX)) {
                    mGpxManager.addGpxFile(file, mMapsManager);
                } else {
                    mGpxManager.addKmlFile(file, mMapsManager);
                }
                mGpxManager.refreshDialog();
            }
            break;

        case REQUEST_CODE_PICK_POI_FILE:
            poiFile = fileList.get(0).getPath();
            if (poiFile == null)
                Toast.makeText(this, "無法開啟檔案", Toast.LENGTH_SHORT).show();
            else
                onClick(mPoiSearchBtn);
            break;
    }
}
 
Example 19
Project: CityPower-Build-Sample   File: ImageStorageServiceImpl.java   View Source Code Vote up 4 votes
private String getIncidentImageFilename(String IncidentId,String FileName) {
	String fileExt = FilenameUtils.getExtension(FileName);
	return String.format("%s.%s", IncidentId,fileExt);
}
 
Example 20
Project: s3-proxy-chunk-upload   File: S3File.java   View Source Code Vote up 4 votes
public String getExtension() {
    return "." +  FilenameUtils.getExtension(name);
}