Java Code Examples for com.google.common.io.Files#getFileExtension()

The following examples show how to use com.google.common.io.Files#getFileExtension() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileCollectionBackedArchiveTextResource.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public FileCollectionBackedArchiveTextResource(final FileOperations fileOperations,
                                               final TemporaryFileProvider tempFileProvider,
                                               final FileCollection fileCollection,
                                               final String path, Charset charset) {
    super(tempFileProvider, new LazilyInitializedFileTree() {
        @Override
        public FileTree createDelegate() {
            File archiveFile = fileCollection.getSingleFile();
            String fileExtension = Files.getFileExtension(archiveFile.getName());
            FileTree archiveContents = fileExtension.equals("jar") || fileExtension.equals("zip")
                    ? fileOperations.zipTree(archiveFile) : fileOperations.tarTree(archiveFile);
            PatternSet patternSet = new PatternSet();
            patternSet.include(path);
            return archiveContents.matching(patternSet);
        }
        public TaskDependency getBuildDependencies() {
            return fileCollection.getBuildDependencies();
        }
    }, charset);
}
 
Example 2
Source File: FileLogicDefault.java    From canon-sdk-java with MIT License 6 votes vote down vote up
protected File getDestinationOfDownloadFile(final EdsDirectoryItemInfo dirItemInfo, @Nullable final File folderDestination, @Nullable final String filename) {
    final String itemFilename = Native.toString(dirItemInfo.szFileName, DEFAULT_CHARSET.name());
    final String itemFileExtension = Files.getFileExtension(itemFilename);

    final File saveFolder = folderDestination == null ? SYSTEM_TEMP_DIR : folderDestination;
    final String saveFilename;
    if (StringUtils.isBlank(filename)) {
        saveFilename = itemFilename;
    } else {
        final String fileExtension = Files.getFileExtension(filename);
        if (StringUtils.isBlank(fileExtension)) {
            saveFilename = filename + "." + itemFileExtension;
        } else {
            if (fileExtension.equalsIgnoreCase(itemFileExtension)) {
                saveFilename = filename;
            } else {
                saveFilename = filename + "." + itemFileExtension;
            }
        }
    }

    saveFolder.mkdirs();
    return new File(saveFolder, saveFilename);
}
 
Example 3
Source File: ArchiveUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static ArchiveUtils.ArchiveType of(String filename) {
    if (filename == null) return null;
    String ext = Files.getFileExtension(filename);
    try {
        return valueOf(ext.toUpperCase());
    } catch (IllegalArgumentException iae) {
        if (filename.toLowerCase().endsWith(".tar.gz")) {
            return TGZ;
        } else if (filename.toLowerCase().endsWith(".tar.bz") ||
                filename.toLowerCase().endsWith(".tar.bz2") ||
                filename.toLowerCase().endsWith(".tar.xz")) {
            return TBZ;
        } else {
            return UNKNOWN;
        }
    }
}
 
Example 4
Source File: GoDescriptors.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @return the path in the symlink tree as used by the compiler. This is usually the package name
 *     + '.a'.
 */
private static Path getPathInSymlinkTree(
    SourcePathResolverAdapter resolver, Path goPackageName, SourcePath ruleOutput) {
  Path output = resolver.getRelativePath(ruleOutput);

  String extension = Files.getFileExtension(output.toString());
  return Paths.get(goPackageName + (extension.equals("") ? "" : "." + extension));
}
 
Example 5
Source File: BlazeJavascriptAdditionalLibraryRootsProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
static ImmutableList<File> getLibraryFiles(
    Project project, BlazeProjectData projectData, ImportRoots importRoots) {
  if (!JavascriptPrefetchFileSource.languageActive(projectData.getWorkspaceLanguageSettings())) {
    return ImmutableList.of();
  }
  Set<String> jsExtensions = JavascriptPrefetchFileSource.getJavascriptExtensions();
  Predicate<ArtifactLocation> isJs =
      (location) -> {
        String extension = Files.getFileExtension(location.getRelativePath());
        return jsExtensions.contains(extension);
      };
  Predicate<ArtifactLocation> isExternal =
      (location) -> {
        if (!location.isSource()) {
          return true;
        }
        WorkspacePath workspacePath = WorkspacePath.createIfValid(location.getRelativePath());
        return workspacePath == null || !importRoots.containsWorkspacePath(workspacePath);
      };
  ArtifactLocationDecoder decoder = projectData.getArtifactLocationDecoder();
  return projectData.getTargetMap().targets().stream()
      .filter(t -> t.getJsIdeInfo() != null)
      .map(TargetIdeInfo::getJsIdeInfo)
      .map(JsIdeInfo::getSources)
      .flatMap(Collection::stream)
      .filter(isJs)
      .filter(isExternal)
      .distinct()
      .map(a -> OutputArtifactResolver.resolve(project, decoder, a))
      .filter(Objects::nonNull)
      .collect(toImmutableList());
}
 
Example 6
Source File: SceneKitAssetsDescription.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public BuildRule createBuildRule(
    BuildRuleCreationContextWithTargetGraph context,
    BuildTarget buildTarget,
    BuildRuleParams params,
    AppleWrapperResourceArg args) {
  String extension = Files.getFileExtension(args.getPath().getFileName().toString());
  Preconditions.checkArgument(SCENEKIT_ASSETS_EXTENSION.equals(extension));

  return new NoopBuildRuleWithDeclaredAndExtraDeps(
      buildTarget, context.getProjectFilesystem(), params);
}
 
Example 7
Source File: OcamlMLCompileStep.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> cmd =
      ImmutableList.<String>builder()
          .addAll(args.ocamlCompiler.getCommandPrefix(resolver))
          .addAll(OcamlCompilables.DEFAULT_OCAML_FLAGS);

  if (args.stdlib.isPresent()) {
    cmd.add("-nostdlib", OcamlCompilables.OCAML_INCLUDE_FLAG, args.stdlib.get());
  }

  String ext = Files.getFileExtension(args.input.toString());
  String dotExt = "." + ext;
  boolean isImplementation =
      dotExt.equals(OcamlCompilables.OCAML_ML) || dotExt.equals(OcamlCompilables.OCAML_RE);
  boolean isReason =
      dotExt.equals(OcamlCompilables.OCAML_RE) || dotExt.equals(OcamlCompilables.OCAML_REI);

  cmd.add("-cc", args.cCompiler.get(0))
      .addAll(
          MoreIterables.zipAndConcat(
              Iterables.cycle("-ccopt"), args.cCompiler.subList(1, args.cCompiler.size())))
      .add("-c")
      .add("-annot")
      .add("-bin-annot")
      .add("-o", args.output.toString())
      .addAll(Arg.stringify(args.flags, resolver));

  if (isReason && isImplementation) {
    cmd.add("-pp").add("refmt").add("-intf-suffix").add("rei").add("-impl");
  }
  if (isReason && !isImplementation) {
    cmd.add("-pp").add("refmt").add("-intf");
  }

  cmd.add(args.input.toString());
  return cmd.build();
}
 
Example 8
Source File: ImageScalarImpl.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void scale(Resource resource, ImageSize size, Path targetPath) {
    try (InputStream inputStream = resource.openStream()) {
        BufferedImage image = ImageIO.read(inputStream);
        int targetHeight = size.height;
        int targetWidth = size.width;

        if (targetHeight == 0) {
            targetHeight = size.width * image.getHeight() / image.getWidth();
        }

        BufferedImage chopped = chop(image, targetWidth, targetHeight);
        BufferedImage resized = Scalr.resize(chopped, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT,
            targetWidth, targetHeight, Scalr.OP_ANTIALIAS);

        String fileExtension = Files.getFileExtension(resource.path());
        OutputStream out = new FileOutputStream(targetPath.toFile());
        if (isJGP(fileExtension)) {
            writeJPG(resized, out, 0.75);
        } else {
            ImageIO.write(resized, fileExtension, out);
        }
        out.close();
    } catch (IOException e) {
        throw new ApplicationException(e);
    }
}
 
Example 9
Source File: StaticResourceHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
public void service(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
  Require.precondition(isStaticResourceRequest(request), "Expected a static resource request");

  String path = String.format(
      "/%s/%s",
      StaticResourceHandler.class.getPackage().getName().replace(".", "/"),
      request.getPathInfo().substring(STATIC_RESOURCE_BASE_PATH.length()));
  URL url = StaticResourceHandler.class.getResource(path);

  if (url == null) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
  }

  response.setStatus(HttpServletResponse.SC_OK);

  String extension = Files.getFileExtension(path);
  if (MIME_TYPES.containsKey(extension)) {
    response.setContentType(MIME_TYPES.get(extension).toString());
  }

  byte[] data = getResourceData(url);
  response.setContentLength(data.length);

  try (OutputStream output = response.getOutputStream()) {
    output.write(data);
  }
}
 
Example 10
Source File: StateStoreCleaner.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(Path path) {
  String fileName = path.getName();
  String extension = Files.getFileExtension(fileName);
  return isStateMetaFile(fileName) || extension.equalsIgnoreCase("jst") || extension.equalsIgnoreCase("tst") ||
      (extension.equalsIgnoreCase("gst"));
}
 
Example 11
Source File: MultiOpenApiParser.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapperForExtension(File file)
    throws OpenApiConversionException {
  String fileExtension = Files.getFileExtension(file.getAbsolutePath());
  if (mapperForExtension.containsKey(fileExtension)) {
    return mapperForExtension.get(fileExtension);
  }
  throw new OpenApiConversionException(
      String.format(
          "OpenAPI file '%s' has invalid extension '%s'. Only files with {%s} file "
              + "extensions are allowed.",
          file.getName(), fileExtension, Joiner.on(", ").join(mapperForExtension.keySet())));
}
 
Example 12
Source File: ResourcePackManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public ResourcePackManager(File path) {
    if (!path.exists()) {
        path.mkdirs();
    } else if (!path.isDirectory()) {
        throw new IllegalArgumentException(Server.getInstance().getLanguage()
                .translateString("nukkit.resources.invalid-path", path.getName()));
    }

    List<ResourcePack> loadedResourcePacks = new ArrayList<>();
    for (File pack : path.listFiles()) {
        try {
            ResourcePack resourcePack = null;

            if (!pack.isDirectory()) { //directory resource packs temporarily unsupported
                switch (Files.getFileExtension(pack.getName())) {
                    case "zip":
                    case "mcpack":
                        resourcePack = new ZippedResourcePack(pack);
                        break;
                    default:
                        Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
                                .translateString("nukkit.resources.unknown-format", pack.getName()));
                        break;
                }
            }

            if (resourcePack != null) {
                loadedResourcePacks.add(resourcePack);
                this.resourcePacksById.put(resourcePack.getPackId(), resourcePack);
            }
        } catch (IllegalArgumentException e) {
            Server.getInstance().getLogger().warning(Server.getInstance().getLanguage()
                    .translateString("nukkit.resources.fail", pack.getName(), e.getMessage()));
        }
    }

    this.resourcePacks = loadedResourcePacks.toArray(new ResourcePack[loadedResourcePacks.size()]);
    Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
            .translateString("nukkit.resources.success", String.valueOf(this.resourcePacks.length)));
}
 
Example 13
Source File: FileWebController.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
String path(String directoryPath, Resource resource) {
    String fileExtension = Files.getFileExtension(resource.path());
    return directoryPath + UUID.randomUUID().toString() + '.' + fileExtension;
}
 
Example 14
Source File: DataFrameWriter.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public void toFile(File file) throws IOException {
  String extension = Files.getFileExtension(file.getCanonicalPath());
  DataWriter<?> dataWriter = registry.getWriterForExtension(extension);
  dataWriter.write(table, new Destination(file));
}
 
Example 15
Source File: OcamlDepToolStep.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
protected ImmutableList<String> getShellCommandInternal(@Nullable ExecutionContext context) {

  ImmutableList.Builder<String> cmd = ImmutableList.builder();

  cmd.addAll(ocamlDepTool.getCommandPrefix(resolver))
      .add("-one-line")
      .add("-native")
      .addAll(flags)
      .add("-ml-synonym")
      .add(".re")
      .add("-mli-synonym")
      .add(".rei");

  boolean previousFileWasReason = false;

  for (SourcePath sourcePath : input) {
    String filePath = resolver.getAbsolutePath(sourcePath).toString();
    String ext = Files.getFileExtension(filePath);
    String dotExt = "." + ext;

    boolean isImplementation =
        dotExt.equals(OcamlCompilables.OCAML_ML) || dotExt.equals(OcamlCompilables.OCAML_RE);
    boolean isReason =
        dotExt.equals(OcamlCompilables.OCAML_RE) || dotExt.equals(OcamlCompilables.OCAML_REI);

    if (isReason && !previousFileWasReason) {
      cmd.add("-pp").add("refmt");
    } else if (!isReason && previousFileWasReason) {
      // Use cat to restore the preprocessor only when the previous file was Reason.
      cmd.add("-pp").add("cat");
    }

    // Note -impl and -intf must go after the -pp flag, if any.
    cmd.add(isImplementation ? "-impl" : "-intf");

    cmd.add(filePath);

    previousFileWasReason = isReason;
  }

  return cmd.build();
}
 
Example 16
Source File: FileExtension.java    From git-code-format-maven-plugin with MIT License 4 votes vote down vote up
public static FileExtension parse(String path) {
  return new FileExtension(Files.getFileExtension(path));
}
 
Example 17
Source File: FileUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 获取文件名的扩展名部分(不包含.)
 */
public static String getFileExtension(String fullName) {
	return Files.getFileExtension(fullName);
}
 
Example 18
Source File: FileUtils.java    From AuthMeReloaded with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Returns a path to a new file (which doesn't exist yet) with a timestamp in the name in the same
 * folder as the given file and containing the given file's filename.
 *
 * @param file the file based on which a new file path should be created
 * @return path to a file suitably named for storing a backup
 */
public static String createBackupFilePath(File file) {
    String filename = "backup_" + Files.getNameWithoutExtension(file.getName())
        + "_" + createCurrentTimeString()
        + "." + Files.getFileExtension(file.getName());
    return makePath(file.getParent(), filename);
}
 
Example 19
Source File: DataFrameReader.java    From tablesaw with Apache License 2.0 2 votes vote down vote up
/**
 * Best effort method to get the extension from a URL.
 *
 * @param url the url to pull the extension from.
 * @return the extension.
 */
private String getExtension(URL url) {
  return Files.getFileExtension(url.getPath());
}
 
Example 20
Source File: FileSystemDropImporter.java    From mojito with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a {@link BoxFile} to {@link DropFile}
 *
 * @param file file to be converted
 * @return {@link DropFile} resulting of {@link BoxFile} conversion
 */
private DropFile fileToDropFile(File file) {
    String name = file.getName();
    String bcp47Tag = getBcp47TagFromFileName(name);
    return new DropFile(file.toString(), bcp47Tag, name, Files.getFileExtension(name));
}