com.google.common.io.Files#getNameWithoutExtension ( )源码实例Demo

下面列出了com.google.common.io.Files#getNameWithoutExtension ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: presto   文件: StaticCatalogStore.java
private void loadCatalog(File file)
        throws Exception
{
    String catalogName = Files.getNameWithoutExtension(file.getName());
    if (disabledCatalogs.contains(catalogName)) {
        log.info("Skipping disabled catalog %s", catalogName);
        return;
    }

    log.info("-- Loading catalog %s --", file);
    Map<String, String> properties = new HashMap<>(loadPropertiesFrom(file.getPath()));

    String connectorName = properties.remove("connector.name");
    checkState(connectorName != null, "Catalog configuration %s does not contain connector.name", file.getAbsoluteFile());

    connectorManager.createCatalog(catalogName, connectorName, ImmutableMap.copyOf(properties));
    log.info("-- Added catalog %s using connector %s --", catalogName, connectorName);
}
 
@FXML
void saveImage(ActionEvent event) {
    // Suggest name based on input file
    if (!inputFileName.getText().isEmpty()) {
        String suggestedName = Files.getNameWithoutExtension(inputFileName.getText());
        outputFileChooser.setInitialFileName(suggestedName);
    }

    // Show dialog
    File outputFile = imageOutputFileChooser.showSaveDialog(saveImageButton.getScene().getWindow());
    if (outputFile == null)
        return;
    imageOutputFileChooser.setInitialDirectory(outputFile.getParentFile());

    // Create image from current chart content
    WritableImage image = new WritableImage((int) chartPane.getWidth(), (int) chartPane.getHeight());
    chartPane.snapshot(null, image);

    // Write to disk
    try {
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", outputFile);
    } catch (Exception e) {
        Alert dialog = new Alert(AlertType.ERROR, e.getMessage(), ButtonType.CLOSE);
        dialog.showAndWait();
    }
}
 
@FXML
void exportLog(ActionEvent event) {

    // Let user select file (suggest name based on input file without extension)
    checkState(!inputFileName.getText().isEmpty(), "Input file must not be empty");
    String suggestedName = Files.getNameWithoutExtension(inputFileName.getText());
    outputFileChooser.setInitialFileName(suggestedName);
    outputFileChooser.setInitialDirectory(new File(inputFileName.getText()).getAbsoluteFile().getParentFile());

    // Show dialog
    File outputFile = outputFileChooser.showSaveDialog(exportButton.getScene().getWindow());
    if (outputFile == null)
        return;

    // Call HistogramLogProcessor
    try {
        String[] args = getCurrentConfiguration().toCommandlineArgs(outputFile);
        HistogramLogProcessor.main(args);
    } catch (Exception e) {
        Alert dialog = new Alert(AlertType.ERROR, e.getMessage(), ButtonType.CLOSE);
        dialog.showAndWait();
    }
}
 
源代码4 项目: buck   文件: OcamlBuildRulesGenerator.java
/** The bytecode output (which is also executable) */
private static String getMLBytecodeOutputName(String name) {
  String base = Files.getNameWithoutExtension(name);
  String ext = Files.getFileExtension(name);
  Preconditions.checkArgument(OcamlCompilables.SOURCE_EXTENSIONS.contains(ext));
  String dotExt = "." + ext;
  if (dotExt.equals(OcamlCompilables.OCAML_ML) || dotExt.equals(OcamlCompilables.OCAML_RE)) {
    return base + OcamlCompilables.OCAML_CMO;
  } else if (dotExt.equals(OcamlCompilables.OCAML_MLI)
      || dotExt.equals(OcamlCompilables.OCAML_REI)) {
    return base + OcamlCompilables.OCAML_CMI;
  } else {
    Preconditions.checkState(false, "Unexpected extension: " + ext);
    return base;
  }
}
 
源代码5 项目: bazel   文件: PredefinedAttributes.java
private static ImmutableMap<String, RuleDocumentationAttribute> generateAttributeMap(
    String commonType, ImmutableList<String> filenames) {
  ImmutableMap.Builder<String, RuleDocumentationAttribute> builder =
      ImmutableMap.<String, RuleDocumentationAttribute>builder();
  for (String filename : filenames) {
    String name = Files.getNameWithoutExtension(filename);
    try {
      InputStream stream = PredefinedAttributes.class.getResourceAsStream(filename);
      if (stream == null) {
        throw new IllegalStateException("Resource " + filename + " not found");
      }
      String content = new String(ByteStreams.toByteArray(stream), StandardCharsets.UTF_8);
      builder.put(name, RuleDocumentationAttribute.create(name, commonType, content));
    } catch (IOException e) {
      throw new IllegalStateException("Exception while reading " + filename, e);
    }
  }
  return builder.build();
}
 
源代码6 项目: james-project   文件: ExportServiceTest.java
@Test
void exportUserMailboxesDataShouldDeleteBlobAfterCompletion() throws Exception {
    createAMailboxWithAMail(MESSAGE_CONTENT);

    testee.export(progress, BOB).block();

    String fileName = Files.getNameWithoutExtension(getFileUrl());
    String blobId = fileName.substring(fileName.lastIndexOf("-") + 1);

    SoftAssertions.assertSoftly(softly -> {
        assertThatThrownBy(() -> testSystem.blobStore.read(testSystem.blobStore.getDefaultBucketName(), FACTORY.from(blobId)))
            .isInstanceOf(ObjectNotFoundException.class);
        assertThatThrownBy(() -> testSystem.blobStore.read(testSystem.blobStore.getDefaultBucketName(), FACTORY.from(blobId)))
            .hasMessage(String.format("blob '%s' not found in bucket '%s'", blobId, testSystem.blobStore.getDefaultBucketName().asString()));
    });
}
 
源代码7 项目: JGiven   文件: PlainTextReportGenerator.java
public void handleReportModel( ReportModel model, File file ) {
    String targetFileName = Files.getNameWithoutExtension( file.getName() ) + ".feature";
    PrintWriter printWriter = PrintWriterUtil.getPrintWriter( new File( config.getTargetDir(), targetFileName ) );

    try {
        model.accept( new PlainTextScenarioWriter( printWriter, false ) );
    } finally {
        ResourceUtil.close( printWriter );
    }
}
 
源代码8 项目: connect-utils   文件: TestDataUtils.java
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException {
  Preconditions.checkNotNull(packageName, "packageName cannot be null");
  Reflections reflections = new Reflections(packageName, new ResourcesScanner());
  Set<String> resources = reflections.getResources(new FilterBuilder.Include(".*"));
  List<T> datas = new ArrayList<>(resources.size());
  Path packagePath = Paths.get("/" + packageName.replace(".", "/"));
  for (String resource : resources) {
    log.trace("Loading resource {}", resource);
    Path resourcePath = Paths.get("/" + resource);
    Path relativePath = packagePath.relativize(resourcePath);
    File resourceFile = new File("/" + resource);
    T data;
    try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) {
      data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls);
    } catch (IOException ex) {
      if (log.isErrorEnabled()) {
        log.error("Exception thrown while loading {}", resourcePath, ex);
      }
      throw ex;
    }
    String nameWithoutExtension = Files.getNameWithoutExtension(resource);
    if (null != relativePath.getParent()) {
      String parentName = relativePath.getParent().getFileName().toString();
      data.testName(parentName + "/" + nameWithoutExtension);
    } else {
      data.testName(nameWithoutExtension);
    }
    datas.add(data);
  }
  return datas;
}
 
源代码9 项目: incubator-gobblin   文件: GitFlowGraphMonitor.java
/**
 * Helper that overrides the flow edge properties with name derived from the edge file path
 * @param edgeConfig edge config
 * @param edgeFilePath path of the edge file
 * @return config with overridden edge properties
 */
private Config getEdgeConfigWithOverrides(Config edgeConfig, Path edgeFilePath) {
  String source = edgeFilePath.getParent().getParent().getName();
  String destination = edgeFilePath.getParent().getName();
  String edgeName = Files.getNameWithoutExtension(edgeFilePath.getName());

  return edgeConfig.withValue(FlowGraphConfigurationKeys.FLOW_EDGE_SOURCE_KEY, ConfigValueFactory.fromAnyRef(source))
      .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_DESTINATION_KEY, ConfigValueFactory.fromAnyRef(destination))
      .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_ID_KEY, ConfigValueFactory.fromAnyRef(getEdgeId(source, destination, edgeName)));
}
 
源代码10 项目: xtext-xtend   文件: ConvertJavaCode.java
private IFile xtendFileToCreate(ICompilationUnit iCompilationUnit) {
	IContainer parent = iCompilationUnit.getResource().getParent();
	String xtendFileName = Files.getNameWithoutExtension(iCompilationUnit.getElementName()) + "."
			+ fileExtensionProvider.getPrimaryFileExtension();
	IFile file = parent.getFile(new Path(xtendFileName));
	return file;
}
 
源代码11 项目: eml-to-pdf-converter   文件: MainTest.java
@Test
public void main_attachmentsSniffFileExtension() throws MessagingException, IOException, URISyntaxException {
	File tmpPdf = File.createTempFile("emailtopdf", ".pdf");
	String eml = new File(MainTest.class.getClassLoader().getResource("eml/testAttachmentsNoName.eml").toURI()).getAbsolutePath();

	String[] args = new String[]{
			"-o", tmpPdf.getAbsolutePath(),
			"-a",
			eml
	};

	LogLevel old = Logger.level;
	Logger.level = LogLevel.Error;

	Main.main(args);

	Logger.level = old;

	File attachmentDir = new File(tmpPdf.getParent(), Files.getNameWithoutExtension(tmpPdf.getName()) +  "-attachments");

	List<String> attachments = Arrays.asList(attachmentDir.list());
	assertTrue(attachments.get(0).endsWith(".jpg"));

	if (!tmpPdf.delete()) {
		tmpPdf.deleteOnExit();
	}

	for (String fileName : attachments) {
		File f = new File(attachmentDir, fileName);
		if (!f.delete()) {
			f.deleteOnExit();
		}
	}

	if (!attachmentDir.delete()) {
		attachmentDir.deleteOnExit();
	}
}
 
@Test
public void testCreateDag() throws Exception {
  //Create a list of JobExecutionPlans
  List<JobExecutionPlan> jobExecutionPlans = new ArrayList<>();
  for (JobTemplate jobTemplate: this.jobTemplates) {
    String jobSpecUri = Files.getNameWithoutExtension(new Path(jobTemplate.getUri()).getName());
    jobExecutionPlans.add(new JobExecutionPlan(JobSpec.builder(jobSpecUri).withConfig(jobTemplate.getRawTemplateConfig()).
        withVersion("1").withTemplate(jobTemplate.getUri()).build(), specExecutor));
  }

  //Create a DAG from job execution plans.
  Dag<JobExecutionPlan> dag = new JobExecutionPlanDagFactory().createDag(jobExecutionPlans);

  //Test DAG properties
  Assert.assertEquals(dag.getStartNodes().size(), 1);
  Assert.assertEquals(dag.getEndNodes().size(), 1);
  Assert.assertEquals(dag.getNodes().size(), 4);
  String startNodeName = new Path(dag.getStartNodes().get(0).getValue().getJobSpec().getUri()).getName();
  Assert.assertEquals(startNodeName, "job1");
  String templateUri = new Path(dag.getStartNodes().get(0).getValue().getJobSpec().getTemplateURI().get()).getName();
  Assert.assertEquals(templateUri, "job1.job");
  String endNodeName = new Path(dag.getEndNodes().get(0).getValue().getJobSpec().getUri()).getName();
  Assert.assertEquals(endNodeName, "job4");
  templateUri = new Path(dag.getEndNodes().get(0).getValue().getJobSpec().getTemplateURI().get()).getName();
  Assert.assertEquals(templateUri, "job4.job");

  Dag.DagNode<JobExecutionPlan> startNode = dag.getStartNodes().get(0);
  List<Dag.DagNode<JobExecutionPlan>> nextNodes = dag.getChildren(startNode);
  Set<String> nodeSet = new HashSet<>();
  for (Dag.DagNode<JobExecutionPlan> node: nextNodes) {
    nodeSet.add(new Path(node.getValue().getJobSpec().getUri()).getName());
    Dag.DagNode<JobExecutionPlan> nextNode = dag.getChildren(node).get(0);
    Assert.assertEquals(new Path(nextNode.getValue().getJobSpec().getUri()).getName(), "job4");
  }
  Assert.assertTrue(nodeSet.contains("job2"));
  Assert.assertTrue(nodeSet.contains("job3"));
}
 
源代码13 项目: vividus   文件: Attachment.java
public Attachment(byte[] content, String fileName)
{
    this(content, Files.getNameWithoutExtension(fileName), probeContentType(fileName));
}
 
@Test
public void get_file_name_with_out_extension_guava () {
	
	String fileName = Files.getNameWithoutExtension(FILE_PATH);
	assertEquals("sample", fileName);
}
 
源代码15 项目: DataflowTemplates   文件: BulkDecompressorTest.java
/** Tests the {@link BulkDecompressor.Decompress} performs the decompression properly. */
@Test
public void testDecompressCompressedFile() throws Exception {
  // Arrange
  //
  final ValueProvider<String> outputDirectory =
      pipeline.newProvider(tempFolderOutputPath.toString());

  final Metadata compressedFile1Metadata =
      FileSystems.matchSingleFileSpec(compressedFile.toString());

  final Metadata compressedFile2Metadata =
      FileSystems.matchSingleFileSpec(wrongCompressionExtFile.toString());

  final String expectedOutputFilename = Files.getNameWithoutExtension(compressedFile.toString());

  final String expectedOutputFilePath =
      tempFolderOutputPath.resolve(expectedOutputFilename).normalize().toString();

  // Act
  //
  PCollectionTuple decompressOut =
      pipeline
          .apply("CreateWorkItems", Create.of(compressedFile1Metadata, compressedFile2Metadata))
          .apply(
              "Decompress",
              ParDo.of(new Decompress(outputDirectory))
                  .withOutputTags(DECOMPRESS_MAIN_OUT_TAG, TupleTagList.of(DEADLETTER_TAG)));

  // Assert
  //
  PAssert.that(decompressOut.get(DECOMPRESS_MAIN_OUT_TAG))
      .containsInAnyOrder(expectedOutputFilePath);

  PAssert.that(decompressOut.get(DEADLETTER_TAG))
      .satisfies(
          collection -> {
            KV<String, String> kv = collection.iterator().next();
            assertThat(kv.getKey(), is(equalTo(compressedFile2Metadata.resourceId().toString())));
            assertThat(kv.getValue(), is(notNullValue()));
            return null;
          });

  PipelineResult result = pipeline.run();
  result.waitUntilFinish();

  // Validate the uncompressed file written has the expected file content.
  PCollection<String> validatorOut =
      validatorPipeline.apply("ReadOutputFile", TextIO.read().from(expectedOutputFilePath));

  PAssert.that(validatorOut).containsInAnyOrder(FILE_CONTENT);

  validatorPipeline.run();
}
 
protected void poll(final String packageName, TestCase testCase) throws InterruptedException, IOException {
  String keySchemaConfig = ObjectMapperFactory.INSTANCE.writeValueAsString(testCase.keySchema);
  String valueSchemaConfig = ObjectMapperFactory.INSTANCE.writeValueAsString(testCase.valueSchema);

  Map<String, String> settings = this.settings();
  settings.put(AbstractSourceConnectorConfig.INPUT_FILE_PATTERN_CONF, String.format("^.*\\.%s", packageName));
  settings.put(AbstractSpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF, keySchemaConfig);
  settings.put(AbstractSpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF, valueSchemaConfig);

  if (null != testCase.settings && !testCase.settings.isEmpty()) {
    settings.putAll(testCase.settings);
  }

  this.task = createTask();

  SourceTaskContext sourceTaskContext = mock(SourceTaskContext.class);
  OffsetStorageReader offsetStorageReader = mock(OffsetStorageReader.class);
  when(offsetStorageReader.offset(anyMap())).thenReturn(testCase.offset);
  when(sourceTaskContext.offsetStorageReader()).thenReturn(offsetStorageReader);
  this.task.initialize(sourceTaskContext);

  this.task.start(settings);

  String dataFile = new File(packageName, Files.getNameWithoutExtension(testCase.path.toString())) + ".data";
  log.trace("poll(String, TestCase) - dataFile={}", dataFile);

  String inputFileName = String.format("%s.%s",
      Files.getNameWithoutExtension(testCase.path.toString()),
      packageName
  );


  final File inputFile = new File(this.inputPath, inputFileName);
  log.trace("poll(String, TestCase) - inputFile = {}", inputFile);
  final File processingFile = InputFileDequeue.processingFile(AbstractSourceConnectorConfig.PROCESSING_FILE_EXTENSION_DEFAULT, inputFile);
  try (InputStream inputStream = this.getClass().getResourceAsStream(dataFile)) {
    try (OutputStream outputStream = new FileOutputStream(inputFile)) {
      ByteStreams.copy(inputStream, outputStream);
    }
  }

  assertFalse(processingFile.exists(), String.format("processingFile %s should not exist before first poll().", processingFile));
  assertTrue(inputFile.exists(), String.format("inputFile %s should exist.", inputFile));
  List<SourceRecord> records = this.task.poll();
  assertTrue(inputFile.exists(), String.format("inputFile %s should exist after first poll().", inputFile));
  assertTrue(processingFile.exists(), String.format("processingFile %s should exist after first poll().", processingFile));

  assertNotNull(records, "records should not be null.");
  assertFalse(records.isEmpty(), "records should not be empty");
  assertEquals(testCase.expected.size(), records.size(), "records.size() does not match.");

  /*
  The following headers will change. Lets ensure they are there but we don't care about their
  values since they are driven by things that will change such as lastModified dates and paths.
   */
  List<String> headersToRemove = Arrays.asList(
      Metadata.HEADER_LAST_MODIFIED,
      Metadata.HEADER_PATH,
      Metadata.HEADER_LENGTH
  );

  for (int i = 0; i < testCase.expected.size(); i++) {
    SourceRecord expectedRecord = testCase.expected.get(i);
    SourceRecord actualRecord = records.get(i);

    for (String headerToRemove : headersToRemove) {
      assertNotNull(
          actualRecord.headers().lastWithName(headerToRemove),
          String.format("index:%s should have the header '%s'", i, headerToRemove)
      );
      actualRecord.headers().remove(headerToRemove);
      expectedRecord.headers().remove(headerToRemove);
    }
    assertSourceRecord(expectedRecord, actualRecord, String.format("index:%s", i));
  }

  records = this.task.poll();
  assertNull(records, "records should be null after first poll.");
  records = this.task.poll();
  assertNull(records, "records should be null after first poll.");
  assertFalse(inputFile.exists(), String.format("inputFile %s should not exist.", inputFile));
  assertFalse(processingFile.exists(), String.format("processingFile %s should not exist.", processingFile));
  final File finishedFile = new File(this.finishedPath, inputFileName);
  assertTrue(finishedFile.exists(), String.format("finishedFile %s should exist.", finishedFile));
}
 
源代码17 项目: buck   文件: OcamlBuildRulesGenerator.java
private static String getCOutputName(String name) {
  String base = Files.getNameWithoutExtension(name);
  String ext = Files.getFileExtension(name);
  Preconditions.checkArgument(OcamlCompilables.SOURCE_EXTENSIONS.contains(ext));
  return base + ".o";
}
 
源代码18 项目: purplejs   文件: ResourcePath.java
public String getNameWithoutExtension()
{
    final String name = getName();
    return Files.getNameWithoutExtension( name );
}
 
源代码19 项目: nomulus   文件: ListNamingUtils.java
/** Turns a file path into a name suitable for use as the name of a premium or reserved list. */
public static String convertFilePathToName(Path file) {
  return Files.getNameWithoutExtension(file.getFileName().toString());
}
 
源代码20 项目: buck   文件: AppleResourceProcessing.java
/** Adds Resources processing steps to a build rule */
public static void addResourceProcessingSteps(
    SourcePathResolverAdapter resolver,
    Path sourcePath,
    Path destinationPath,
    ImmutableList.Builder<Step> stepsBuilder,
    ImmutableList<String> ibtoolFlags,
    ProjectFilesystem projectFilesystem,
    boolean isLegacyWatchApp,
    ApplePlatform platform,
    Logger LOG,
    Tool ibtool,
    boolean ibtoolModuleFlag,
    BuildTarget buildTarget,
    Optional<String> binaryName) {
  String sourcePathExtension =
      Files.getFileExtension(sourcePath.toString()).toLowerCase(Locale.US);
  switch (sourcePathExtension) {
    case "plist":
    case "stringsdict":
      LOG.debug("Converting plist %s to binary plist %s", sourcePath, destinationPath);
      stepsBuilder.add(
          new PlistProcessStep(
              projectFilesystem,
              sourcePath,
              Optional.empty(),
              destinationPath,
              ImmutableMap.of(),
              ImmutableMap.of(),
              PlistProcessStep.OutputFormat.BINARY));
      break;
    case "storyboard":
      AppleResourceProcessing.addStoryboardProcessingSteps(
          resolver,
          sourcePath,
          destinationPath,
          stepsBuilder,
          ibtoolFlags,
          isLegacyWatchApp,
          platform,
          projectFilesystem,
          LOG,
          ibtool,
          ibtoolModuleFlag,
          buildTarget,
          binaryName);
      break;
    case "xib":
      String compiledNibFilename =
          Files.getNameWithoutExtension(destinationPath.toString()) + ".nib";
      Path compiledNibPath = destinationPath.getParent().resolve(compiledNibFilename);
      LOG.debug("Compiling XIB %s to NIB %s", sourcePath, destinationPath);
      stepsBuilder.add(
          new IbtoolStep(
              projectFilesystem,
              ibtool.getEnvironment(resolver),
              ibtool.getCommandPrefix(resolver),
              ibtoolModuleFlag ? binaryName : Optional.empty(),
              ImmutableList.<String>builder()
                  .addAll(AppleResourceProcessing.BASE_IBTOOL_FLAGS)
                  .addAll(ibtoolFlags)
                  .addAll(ImmutableList.of("--compile"))
                  .build(),
              sourcePath,
              compiledNibPath));
      break;
    default:
      stepsBuilder.add(CopyStep.forFile(projectFilesystem, sourcePath, destinationPath));
      break;
  }
}