Java Code Examples for org.apache.commons.io.FileUtils#getFile()

The following examples show how to use org.apache.commons.io.FileUtils#getFile() . 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: HugeGraphLoader.java    From hugegraph-loader with Apache License 2.0 6 votes vote down vote up
private void createSchema() {
    LoadOptions options = this.context.options();
    if (!StringUtils.isEmpty(options.schema)) {
        File file = FileUtils.getFile(options.schema);
        HugeClient client = this.context.client();
        GroovyExecutor groovyExecutor = new GroovyExecutor();
        groovyExecutor.bind(Constants.GROOVY_SCHEMA, client.schema());
        String script;
        try {
            script = FileUtils.readFileToString(file, Constants.CHARSET);
        } catch (IOException e) {
            throw new LoadException("Failed to read schema file '%s'", e,
                                    options.schema);
        }
        groovyExecutor.execute(script, client);
    }
    this.context.updateSchemaCache();
}
 
Example 2
Source File: Server2ControllerSegmentUploaderTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setUp()
    throws URISyntaxException, IOException, HttpErrorStatusException {
  SegmentCompletionProtocol.Response successResp = new SegmentCompletionProtocol.Response();
  successResp.setStatus(SegmentCompletionProtocol.ControllerResponseStatus.UPLOAD_SUCCESS);
  successResp.setSegmentLocation(SEGMENT_LOCATION);
  SimpleHttpResponse successHttpResponse = new SimpleHttpResponse(200, successResp.toJsonString());

  SegmentCompletionProtocol.Response failureResp = new SegmentCompletionProtocol.Response();
  failureResp.setStatus(SegmentCompletionProtocol.ControllerResponseStatus.FAILED);
  SimpleHttpResponse failHttpResponse = new SimpleHttpResponse(404, failureResp.toJsonString());

  _fileUploadDownloadClient = mock(FileUploadDownloadClient.class);

  when(_fileUploadDownloadClient
      .uploadSegment(eq(new URI(GOOD_CONTROLLER_VIP)), anyString(), any(File.class), any(), any(), anyInt()))
      .thenReturn(successHttpResponse);
  when(_fileUploadDownloadClient
      .uploadSegment(eq(new URI(BAD_CONTROLLER_VIP)), anyString(), any(File.class), any(), any(), anyInt()))
      .thenReturn(failHttpResponse);

  _file = FileUtils.getFile(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
  _file.deleteOnExit();

  _llcSegmentName = new LLCSegmentName("test_REALTIME", 1, 0, System.currentTimeMillis());
}
 
Example 3
Source File: GenerateSourcesBuilder.java    From spoofax with Apache License 2.0 6 votes vote down vote up
private PackSdfBuild oldParseTableGenerationPack(GenerateSourcesBuilder.Input input, File srcGenSyntaxDir,
    String sdfModule, File sdfFile, File sdfExternalDef) throws IOException {
    // Get the SDF .def file, either from existing external .def, or by running pack SDF on the grammar
    // specification
    final @Nullable File packSdfFile;
    final @Nullable Origin packSdfOrigin;

    if(sdfExternalDef != null) {
        packSdfFile = sdfExternalDef;
        packSdfOrigin = null;
    } else if(sdfFile != null) {
        require(sdfFile, FileExistsStamper.instance);
        if(!sdfFile.exists()) {
            throw new IOException("Main SDF file at " + sdfFile + " does not exist");
        }

        packSdfFile = FileUtils.getFile(srcGenSyntaxDir, sdfModule + ".def");
        packSdfOrigin = PackSdfLegacy.origin(new PackSdfLegacy.Input(context, sdfModule, sdfFile, packSdfFile,
            input.packSdfIncludePaths, input.packSdfArgs, null));
    } else {
        packSdfFile = null;
        packSdfOrigin = null;
    }

    return new PackSdfBuild(packSdfFile, packSdfOrigin);
}
 
Example 4
Source File: JsonYamlUtils.java    From support-diagnostics with Apache License 2.0 5 votes vote down vote up
public static Map readYamlFromPath(String path, boolean isBlock) throws Exception {
   File fl = FileUtils.getFile(path);
   InputStream inputStream = new FileInputStream(fl);
   Map doc = JsonYamlUtils.readYaml(inputStream, isBlock);
   SystemUtils.streamClose(path, inputStream);
   return doc;
}
 
Example 5
Source File: CommonsIOUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {

    String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
    File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));

    Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
}
 
Example 6
Source File: GenerateSourcesBuilder.java    From spoofax with Apache License 2.0 5 votes vote down vote up
private MakePermissiveBuild oldParseTableGenerationMakePermissive(PackSdfBuild packSdfBuild, File srcGenSyntaxDir,
    String sdfModule) throws IOException {
    final File permissiveDefFile = FileUtils.getFile(srcGenSyntaxDir, sdfModule + "-permissive.def");
    final Origin permissiveDefOrigin = MakePermissive.origin(
        new MakePermissive.Input(context, packSdfBuild.file, permissiveDefFile, sdfModule, packSdfBuild.origin));

    return new MakePermissiveBuild(permissiveDefFile, permissiveDefOrigin);
}
 
Example 7
Source File: MappingUtil.java    From hugegraph-loader with Apache License 2.0 5 votes vote down vote up
public static void write(LoadMapping mapping, String path) {
    File file = FileUtils.getFile(path);
    String json = JsonUtil.toJson(mapping);
    try {
        FileUtils.write(file, json, Constants.CHARSET);
    } catch (IOException e) {
        throw new LoadException("Failed to write mapping %s to file '%s'",
                                e, mapping, file);
    }
}
 
Example 8
Source File: LicenseManagerTest.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
public static LicenseVerifier build(String path) throws IOException {
    File file = FileUtils.getFile(path);
    String json;
    try {
        json = FileUtils.readFileToString(file, CHARSET);
    } catch (IOException e) {
        throw new RuntimeException(String.format(
                  "Failed to read file '%s'", path));
    }
    LicenseVerifyParam param = MAPPER.readValue(
                               json, LicenseVerifyParam.class);
    return new LicenseVerifier(param);
}
 
Example 9
Source File: LicenseManagerTest.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
public static LicenseCreator build(String path) throws IOException {
    File file = FileUtils.getFile(path);
    String json;
    try {
        json = FileUtils.readFileToString(file, CHARSET);
    } catch (IOException e) {
        throw new RuntimeException(String.format(
                  "Failed to read file '%s'", path));
    }
    LicenseCreateParam param = MAPPER.readValue(
                               json, LicenseCreateParam.class);
    return new LicenseCreator(param);
}
 
Example 10
Source File: LicenceFileService.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
public BigDecimal getFileSize(String fileName) {
	try {
		if (fileExists(fileName)) {
			File file = FileUtils.getFile(fileName);
			BigDecimal fileSize = new BigDecimal(file.length());
			fileSize = fileSize.divide(new BigDecimal(1024 * 1024));
			return fileSize.setScale(2, RoundingMode.HALF_UP);
		}
	} catch (IOException e) {
	}
	return null;
}
 
Example 11
Source File: Asqatasun.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param path
 * @param option
 * @param testWritable
 * @return whether the given path is valid for the given argument
 */
private static boolean isValidPath(String path, String option, boolean testWritable) {
    File file = FileUtils.getFile(path);
    if (file.exists() && file.canExecute() && file.canRead()) {
        if (!testWritable) {
            return true;
        } else if (file.canWrite()) {
            return true;
        }
    }
    System.out.println("\n"+path + " is an invalid path for " + option + " option.\n");
    return false;
}
 
Example 12
Source File: ImportsSorter452Test.java    From EclipseCodeFormatter with Apache License 2.0 5 votes vote down vote up
@Test
public void issue104a() throws Exception {
	//@formatter:off
	String expected =
			"import com.mycorp.Foo;\n" +
					"\n" +
					"import static com.mycorp.Foo.foo;\n" +
					"\n" +
					"import com.google.bar;\n" +
					"\n" +
					"import static com.google.bar.bar;\n";

	String imports =
			"import static com.google.bar.bar;\n" +
			"import com.google.bar;\n" +
			"import static com.mycorp.Foo.foo;\n" +
			"import com.mycorp.Foo;\n" +
					"";

	//@formatter:on


	List<String> importsList = StringUtils.trimImports(imports);
	Collections.shuffle(importsList);

	Settings settings = new Settings();
	File file = FileUtils.getFile("resources/issue104.importorder");
	setPath(settings, file);
	ImportOrderProvider importOrderProvider = new ImportOrderProvider(settings);

	List<String> strings = sort(importsList, importOrderProvider.get());
	printAndAssert(expected, strings);
}
 
Example 13
Source File: GenerateSourcesBuilder.java    From spoofax with Apache License 2.0 5 votes vote down vote up
private Origin oldParseTableGeneration(MakePermissiveBuild makePermissiveBuild, String sdfModule,
    String parseTableFilename, String modulePrefix) throws IOException {
    final File targetMetaborgDir = toFile(paths.targetMetaborgDir());
    final File tableFile = FileUtils.getFile(targetMetaborgDir, parseTableFilename);
    return Sdf2TableLegacy.origin(new Sdf2TableLegacy.Input(context, makePermissiveBuild.file, tableFile,
        modulePrefix + sdfModule, makePermissiveBuild.origin));
}
 
Example 14
Source File: GraphStructV1.java    From hugegraph-loader with Apache License 2.0 5 votes vote down vote up
public static GraphStructV1 of(LoadContext context) {
    LoadOptions options = context.options();
    File file = FileUtils.getFile(options.file);
    try {
        String json = FileUtils.readFileToString(file, Constants.CHARSET);
        GraphStructV1 struct = JsonUtil.fromJson(json, GraphStructV1.class);
        struct.check();
        return struct;
    } catch (IOException | IllegalArgumentException e) {
        throw new LoadException(
                  "Failed to parse graph mapping description file '%s'",
                  e, options.file);
    }
}
 
Example 15
Source File: AdminServiceTest.java    From kylin with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetPublicConfig() throws IOException {
    //set ../examples/test_metadata/kylin.properties empty
    File file = FileUtils.getFile(LOCALMETA_TEMP_DATA + "kylin.properties");
    FileUtils.deleteQuietly(file);
    FileUtils.touch(file);
    String path = Thread.currentThread().getContextClassLoader().getResource("kylin.properties").getPath();

    KylinConfig config = KylinConfig.createInstanceFromUri(path);
    String timeZone = config.getTimeZone();
    try (SetAndUnsetThreadLocalConfig autoUnset = KylinConfig.setAndUnsetThreadLocalConfig(config)) {
    
        String expected = "kylin.web.link-streaming-guide=http://kylin.apache.org/\n" +
                "kylin.web.dashboard-enabled=\n" +
                "kylin.web.contact-mail=\n" +
                "kylin.job.scheduler.default=0\n" +
                "kylin.query.cache-enabled=true\n" +
                "kylin.web.link-diagnostic=\n" +
                "kylin.web.help.length=4\n" +
                "kylin.web.timezone=\n" +
                "kylin.server.external-acl-provider=\n" +
                "kylin.storage.default=2\n" +
                "kylin.cube.cubeplanner.enabled=true\n" +
                "kylin.web.help=\n" +
                "kylin.web.export-allow-other=true\n" +
                "kylin.cube.migration.enabled=false\n" +
                "kylin.web.link-hadoop=\n" +
                "kylin.web.hide-measures=RAW\n" +
                "kylin.htrace.show-gui-trace-toggle=false\n" +
                "kylin.security.additional-profiles=\n" +
                "kylin.web.export-allow-admin=true\n" +
                "kylin.env=QA\n" +
                "kylin.web.hive-limit=20\n" +
                "kylin.engine.default=2\n" +
                "kylin.web.help.3=onboard|Cube Design Tutorial|http://kylin.apache.org/docs/howto/howto_optimize_cubes.html\n" +
                "kylin.web.default-time-filter=1\n" +
                "kylin.web.help.2=tableau|Tableau Guide|http://kylin.apache.org/docs/tutorial/tableau_91.html\n" +
                "kylin.web.help.1=odbc|ODBC Driver|http://kylin.apache.org/docs/tutorial/odbc.html\n" +
                "kylin.web.help.0=start|Getting Started|http://kylin.apache.org/docs/tutorial/kylin_sample.html\n" +
                "kylin.security.profile=testing\n";
        Assert.assertEquals(expected, adminService.getPublicConfig());
    }
}
 
Example 16
Source File: AdminServiceTest.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetPublicConfig() throws IOException {
    //set ../examples/test_metadata/kylin.properties empty
    File file = FileUtils.getFile(LOCALMETA_TEMP_DATA + "kylin.properties");
    FileUtils.deleteQuietly(file);
    FileUtils.touch(file);
    String path = Thread.currentThread().getContextClassLoader().getResource("kylin.properties").getPath();

    KylinConfig config = KylinConfig.createInstanceFromUri(path);
    String timeZone = config.getTimeZone();
    try (SetAndUnsetThreadLocalConfig autoUnset = KylinConfig.setAndUnsetThreadLocalConfig(config)) {
    
        String expected = "kylin.web.link-streaming-guide=http://kylin.apache.org/\n" +
                "kylin.web.dashboard-enabled=\n" +
                "kylin.web.contact-mail=\n" +
                "kylin.job.scheduler.default=0\n" +
                "kylin.query.cache-enabled=true\n" +
                "kylin.web.link-diagnostic=\n" +
                "kylin.web.help.length=4\n" +
                "kylin.web.timezone=\n" +
                "kylin.server.external-acl-provider=\n" +
                "kylin.tool.auto-migrate-cube.enabled=\n" +
                "kylin.storage.default=2\n" +
                "kylin.cube.cubeplanner.enabled=true\n" +
                "kylin.web.help=\n" +
                "kylin.web.export-allow-other=true\n" +
                "kylin.web.link-hadoop=\n" +
                "kylin.web.hide-measures=RAW\n" +
                "kylin.htrace.show-gui-trace-toggle=false\n" +
                "kylin.security.additional-profiles=\n" +
                "kylin.web.export-allow-admin=true\n" +
                "kylin.env=QA\n" +
                "kylin.web.hive-limit=20\n" +
                "kylin.engine.default=2\n" +
                "kylin.web.help.3=onboard|Cube Design Tutorial|http://kylin.apache.org/docs/howto/howto_optimize_cubes.html\n" +
                "kylin.web.default-time-filter=1\n" +
                "kylin.web.help.2=tableau|Tableau Guide|http://kylin.apache.org/docs/tutorial/tableau_91.html\n" +
                "kylin.web.help.1=odbc|ODBC Driver|http://kylin.apache.org/docs/tutorial/odbc.html\n" +
                "kylin.web.help.0=start|Getting Started|http://kylin.apache.org/docs/tutorial/kylin_sample.html\n" +
                "kylin.security.profile=testing\n";
        Assert.assertEquals(expected, adminService.getPublicConfig());
    }
}
 
Example 17
Source File: JsonYamlUtils.java    From support-diagnostics with Apache License 2.0 4 votes vote down vote up
public static JsonNode createJsonNodeFromFileName(String fileName) {
   File jsonFile = FileUtils.getFile(fileName);
   return createJsonNodeFromFile(jsonFile);
}
 
Example 18
Source File: DefaultFSSinkProvider.java    From ambari-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void sinkMetricData(Collection<TimelineMetrics> metrics) {
  String dirPath = TimelineMetricConfiguration.getInstance().getDefaultMetricsSinkDir();
  File dir = new File(dirPath);
  if (!dir.exists()) {
    LOG.error("Cannot sink data to file system, incorrect dir path " + dirPath);
    return;
  }

  File f = FileUtils.getFile(dirPath, SINK_FILE_NAME);
  if (shouldReCreate(f)) {
    if (!f.delete()) {
      LOG.warn("Unable to delete external sink file.");
      return;
    }
    createFile(f);
  }

  if (metrics != null) {
    for (TimelineMetrics timelineMetrics : metrics) {
      for (TimelineMetric metric : timelineMetrics.getMetrics()) {
        StringBuilder sb = new StringBuilder();
        sb.append(metric.getMetricName());
        sb.append(SEPARATOR);
        sb.append(metric.getAppId());
        sb.append(SEPARATOR);
        if (StringUtils.isEmpty(metric.getInstanceId())) {
          sb.append(SEPARATOR);
        } else {
          sb.append(metric.getInstanceId());
          sb.append(SEPARATOR);
        }
        if (StringUtils.isEmpty(metric.getHostName())) {
          sb.append(SEPARATOR);
        } else {
          sb.append(metric.getHostName());
          sb.append(SEPARATOR);
        }
        sb.append(new Date(metric.getStartTime()));
        sb.append(SEPARATOR);
        sb.append(metric.getMetricValues().toString());
        sb.append(LINE_SEP);
        try {
          FileUtils.writeStringToFile(f, sb.toString());
        } catch (IOException e) {
          LOG.warn("Unable to sink data to file " + f.getPath());
        }
      }
    }
  }
}
 
Example 19
Source File: JsonYamlUtils.java    From support-diagnostics with Apache License 2.0 4 votes vote down vote up
public static JsonNode createJsonNodeFromFileName(String dir, String fileName) {
   File jsonFile = FileUtils.getFile(dir, fileName);
   return createJsonNodeFromFile(jsonFile);
}
 
Example 20
Source File: LicenceFileService.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean fileExists(String filename) throws IOException {
	logger.debug("checking file " + filename + " exists");
	File file = FileUtils.getFile(filename);
	return file.exists();
}