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

The following examples show how to use com.google.common.io.Files#getNameWithoutExtension() . 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: StaticCatalogStore.java    From presto with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: VisualizerPresenter.java    From HdrHistogramVisualizer with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 3
Source File: ExportServiceTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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()));
    });
}
 
Example 4
Source File: PredefinedAttributes.java    From bazel with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 5
Source File: OcamlBuildRulesGenerator.java    From buck with Apache License 2.0 6 votes vote down vote up
/** 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;
  }
}
 
Example 6
Source File: VisualizerPresenter.java    From HdrHistogramVisualizer with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 7
Source File: JobExecutionPlanDagFactoryTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 8
Source File: MainTest.java    From eml-to-pdf-converter with Apache License 2.0 5 votes vote down vote up
@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();
	}
}
 
Example 9
Source File: ConvertJavaCode.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * 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)));
}
 
Example 11
Source File: TestDataUtils.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: PlainTextReportGenerator.java    From JGiven with Apache License 2.0 5 votes vote down vote up
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 );
    }
}
 
Example 13
Source File: OcamlBuildRulesGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
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";
}
 
Example 14
Source File: ResourcePath.java    From purplejs with Apache License 2.0 4 votes vote down vote up
public String getNameWithoutExtension()
{
    final String name = getName();
    return Files.getNameWithoutExtension( name );
}
 
Example 15
Source File: AbstractSpoolDirSourceTaskTest.java    From kafka-connect-spooldir with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example 16
Source File: ListNamingUtils.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** 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());
}
 
Example 17
Source File: AppleResourceProcessing.java    From buck with Apache License 2.0 4 votes vote down vote up
/** 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;
  }
}
 
Example 18
Source File: BulkDecompressorTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/** 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();
}
 
Example 19
Source File: GetFileNameWithoutExtension.java    From levelup-java-examples with Apache License 2.0 4 votes vote down vote up
@Test
public void get_file_name_with_out_extension_guava () {
	
	String fileName = Files.getNameWithoutExtension(FILE_PATH);
	assertEquals("sample", fileName);
}
 
Example 20
Source File: Attachment.java    From vividus with Apache License 2.0 4 votes vote down vote up
public Attachment(byte[] content, String fileName)
{
    this(content, Files.getNameWithoutExtension(fileName), probeContentType(fileName));
}