Java 类com.typesafe.config.ConfigRenderOptions 实例源码

项目:microtrader    文件:AuditVerticleTest.java   
@Test
public void testStockTradesPersisted(TestContext context) throws ClassNotFoundException {
    Async async = context.async();
    JsonObject jdbcConfig = new JsonObject(config.getObject("jdbc").render(ConfigRenderOptions.concise()));
    JDBCClient jdbc = JDBCClient.createNonShared(vertx, jdbcConfig);
    Class.forName(jdbcConfig.getString("driverclass"));

    jdbc.getConnection(ar -> {
        SQLConnection connection = ar.result();
        if (ar.failed()) {
            context.fail(ar.cause());
        } else {
            connection.query(SELECT_STATEMENT, result -> {
                ResultSet set = result.result();
                List<JsonObject> operations = set.getRows().stream()
                        .map(json -> new JsonObject(json.getString("OPERATION")))
                        .collect(Collectors.toList());
                context.assertTrue(operations.size() >= 3);
                connection.close();
                async.complete();
            });
        }
    });
}
项目:metrics-aggregator-daemon    文件:HoconFileSource.java   
private HoconFileSource(final Builder builder) {
    super(builder);
    _file = builder._file;

    JsonNode jsonNode = null;
    if (_file.canRead()) {
        try {
            final Config config = ConfigFactory.parseFile(_file);
            final String hoconAsJson = config.resolve().root().render(ConfigRenderOptions.concise());
            jsonNode = _objectMapper.readTree(hoconAsJson);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    } else if (builder._file.exists()) {
        LOGGER.warn()
                .setMessage("Cannot read file")
                .addData("file", _file)
                .log();
    } else {
        LOGGER.debug()
                .setMessage("File does not exist")
                .addData("file", _file)
                .log();
    }
    _jsonNode = Optional.ofNullable(jsonNode);
}
项目:vertx-configuration-service    文件:HoconProcessor.java   
@Override
public void process(Vertx vertx, JsonObject configuration, Buffer input, Handler<AsyncResult<JsonObject>> handler) {
  // Use executeBlocking even if the bytes are in memory
  // Indeed, HOCON resolution can read others files (includes).
  vertx.executeBlocking(
      future -> {
        Reader reader = new StringReader(input.toString("UTF-8"));
        try {
          Config conf = ConfigFactory.parseReader(reader);
          conf = conf.resolve();
          String output = conf.root().render(ConfigRenderOptions.concise()
              .setJson(true).setComments(false).setFormatted(false));
          JsonObject json = new JsonObject(output);
          future.complete(json);
        } catch (Exception e) {
          future.fail(e);
        } finally {
          closeQuietly(reader);
        }
      },
      handler
  );
}
项目:samantha    文件:AbstractIndexer.java   
private void notifyDataSubscribers(JsonNode entities, RequestContext requestContext) {
    if (subscribers == null) {
        return;
    }
    ObjectNode reqBody = Json.newObject();
    IOUtilities.parseEntityFromJsonNode(requestContext.getRequestBody(), reqBody);
    ObjectNode daoConfig = Json.newObject();
    daoConfig.put(ConfigKey.ENTITY_DAO_NAME_KEY.get(), ConfigKey.REQUEST_ENTITY_DAO_NAME.get());
    daoConfig.set(ConfigKey.REQUEST_ENTITY_DAO_ENTITIES_KEY.get(), entities);
    reqBody.set(daoConfigKey, daoConfig);
    RequestContext pseudoReq = new RequestContext(reqBody, requestContext.getEngineName());
    for (Configuration configuration : subscribers) {
        String name = configuration.getString(ConfigKey.ENGINE_COMPONENT_NAME.get());
        String type = configuration.getString(ConfigKey.ENGINE_COMPONENT_TYPE.get());
        JsonNode configReq = Json.parse(configuration.getConfig(ConfigKey.REQUEST_CONTEXT.get())
                .underlying().root().render(ConfigRenderOptions.concise()));
        IOUtilities.parseEntityFromJsonNode(configReq, reqBody);
        EngineComponent.valueOf(type).getComponent(configService, name, pseudoReq);
    }
}
项目:vertx-config    文件:HoconProcessor.java   
@Override
public void process(Vertx vertx, JsonObject configuration, Buffer input, Handler<AsyncResult<JsonObject>> handler) {
  // Use executeBlocking even if the bytes are in memory
  // Indeed, HOCON resolution can read others files (includes).
  vertx.executeBlocking(
      future -> {
        Reader reader = new StringReader(input.toString("UTF-8"));
        try {
          Config conf = ConfigFactory.parseReader(reader);
          conf = conf.resolve();
          String output = conf.root().render(ConfigRenderOptions.concise()
              .setJson(true).setComments(false).setFormatted(false));
          JsonObject json = new JsonObject(output);
          future.complete(json);
        } catch (Exception e) {
          future.fail(e);
        } finally {
          closeQuietly(reader);
        }
      },
      handler
  );
}
项目:gondola    文件:ConfigWriter.java   
/**
 * Save file.
 *
 * @return the file
 */
public File save() {
    ConfigRenderOptions renderOptions = ConfigRenderOptions.defaults()
        .setComments(true)
        .setFormatted(true)
        .setOriginComments(false)
        .setJson(false);
    bumpVersion();
    String configData = configImpl.root().render(renderOptions);
    FileWriter writer = null;
    try {
        writer = new FileWriter(tmpFile.toFile());
        writer.write(configData);
    } catch (IOException e) {
        logger.warn("failed to write file, message={}", e.getMessage());
    } finally {
        CloseableUtils.closeQuietly(writer);
    }
    return tmpFile.toFile();
}
项目:incubator-gobblin    文件:TestMetastoreDatabaseFactory.java   
public static ITestMetastoreDatabase get(String version, Config dbConfig) throws Exception {
    try {
        synchronized (syncObject) {
            ensureDatabaseExists(dbConfig);
            TestMetadataDatabase instance = new TestMetadataDatabase(testMetastoreDatabaseServer, version);
            instances.add(instance);
            return instance;
        }
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to create TestMetastoreDatabase with version " + version +
           " and config " + dbConfig.root().render(ConfigRenderOptions.defaults().setFormatted(true).setJson(true))
           + " cause: " + e, e);
    }

}
项目:distributeTemplate    文件:TypeSafeConfigLoadUtils.java   
public static void main(String[] args) {
    Config config = ConfigFactory.parseFile(new File("c:/reference.conf"));
    String str = config.root().render(
        ConfigRenderOptions.concise().setFormatted(true).setJson(true).setComments(true));
           //    response.getWriter().write(ConfigFactory.load().root().render());
    /**
     * 
     * 
     *     ConfigParseOptions options = ConfigParseOptions.defaults()
*         .setSyntax(ConfigSyntax.JSON)
*         .setAllowMissing(false)
     * 
     * 
     */
    System.out.println(str);
}
项目:orgsync-api-java    文件:DbTemplate.java   
public static void main(final String[] args) throws IOException {
    File file = new File("build/db_template.json");
    System.out.println("Generating template json to file: "
            + file.getAbsolutePath());

    ConfigRenderOptions renderOptions = ConfigRenderOptions.defaults()
            .setJson(true).setComments(false).setOriginComments(false);

    String json = CONFIG.getValue("template").render(renderOptions);

    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

    bufferedWriter.write(json);

    bufferedWriter.close();
}
项目:bench    文件:ActorBootstrap.java   
/**
 * @param args Arguments from the main method.
 * @throws ValidationException if an invalid actor is being created
 */
@VisibleForTesting
static void mainInternal(final String... args) throws ValidationException {
    if (args.length != 4) {
        log.error("Usage:");
        log.error("ActorBootstrap <actorName> <className> " + //
                          "<tmpClusterConfigFile> <tmpActorConfigFile>");
        throw new IllegalArgumentException();
    }

    ActorKey actorKey = new ActorKey(args[0]);
    String className = checkClassName(args[1]);
    String tmpClusterConfig = checkFilePath(args[2]);
    String tmpActorConfig = checkFilePath(args[3]);

    log.info("{} starting...", actorKey);

    // Read and delete temporary config files
    Config clusterConfig = parseClusterConfig(readAndDelete(tmpClusterConfig));
    String jsonActorConfig = readAndDelete(tmpActorConfig);

    log.debug("{} bootstrap with clusterConfig {}, actorConfig {}",
              actorKey,
              clusterConfig.root().render(ConfigRenderOptions.concise()),
              jsonActorConfig);

    AgentClusterClientFactory clientFactory = ClusterClients.newFactory(AgentClusterClientFactory.class,
                                                                        clusterConfig,
                                                                        new ActorRegistry());

    ActorBootstrap actorBootstrap = new ActorBootstrap(clientFactory);
    RuntimeActor actor = actorBootstrap.createActor(actorKey, className, jsonActorConfig);

    installShutdownHook(actorBootstrap, actor);

    log.info("{} started.", actorKey);
}
项目:bench    文件:ForkedActorManager.java   
private Process createActorProcess(final ActorConfig actorConfig, final Config clusterConfig) {
    try {
        File tempActorConfig = writeTmpFile(actorConfig.getActorJsonConfig());
        File tempClusterConfig = writeTmpFile(clusterConfig.root().render(ConfigRenderOptions.concise()));

        return forkProcess(actorConfig, tempActorConfig.getAbsolutePath(), tempClusterConfig.getAbsolutePath());

    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
项目:bench    文件:JMSClusterConfigFactory.java   
@Override
public Config clusterConfigFor(@NotNull final ActorKey actorKey) {
    return ConfigFactory.parseString("{\"" + ClusterClients.FACTORY_CLASS + "\":" + //
                                             "\"" + JMSClusterClientFactory.class.getName() + "\"," + //
                                             "\"" + ClusterClients.FACTORY_CONFIG + "\":" + //
                                             "" + serverEndpoint.toConfig().root().render(ConfigRenderOptions.concise()) + "}");
}
项目:bench    文件:JgroupsClusterConfigFactory.java   
@Override
public Config clusterConfigFor(@NotNull final ActorKey actorKey) {
    return ConfigFactory.parseString("{\"" + ClusterClients.FACTORY_CLASS + "\":" + //
                                             "\"" + JgroupsClusterClientFactory.class.getName() + "\"," + //
                                             "\"" + ClusterClients.FACTORY_CONFIG + "\":" + //
                                             jgroupsFactoryConfig.root().render(ConfigRenderOptions.concise()) + "}");
}
项目:rkt-launcher    文件:RktLauncherApi.java   
@Override
public void create(final Environment environment) {
  final String json =
      environment.config().getValue("rktLauncher").render(ConfigRenderOptions.concise());
  final RktLauncherConfig rktLauncherConfig;
  try {
    rktLauncherConfig = Json.deserialize(json, RktLauncherConfig.class);
  } catch (IOException e) {
    throw new RktLauncherServiceException("invalid configuration", e);
  }

  final ThreadFactory threadFactory = new ThreadFactoryBuilder()
      .setDaemon(true)
      .setNameFormat("async-command-executor-thread-%d")
      .build();
  final ExecutorService asyncCommandExecutorService =
      Executors.newFixedThreadPool(ASYNC_COMMAND_EXECUTOR_THREADS, threadFactory);

  final RktCommandResource rktCommandResource =
      new RktCommandResource(rktLauncherConfig, asyncCommandExecutorService);
  final RktImageCommandResource rktImageCommandResource =
      new RktImageCommandResource(rktLauncherConfig);

  environment.routingEngine()
      .registerAutoRoute(Route.sync("GET", "/ping", rc -> "pong"))
      .registerRoutes(rktCommandResource.routes())
      .registerRoutes(rktImageCommandResource.routes());
}
项目:QDrill    文件:DrillConfig.java   
@VisibleForTesting
public DrillConfig(Config config, boolean enableServerConfigs) {
  super(config);
  logger.debug("Setting up DrillConfig object.");
  logger.trace("Given Config object is:\n{}",
               config.root().render(ConfigRenderOptions.defaults()));
  mapper = new ObjectMapper();

  if (enableServerConfigs) {
    SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(this))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

    mapper.registerModule(deserModule);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.registerSubtypes(LogicalOperatorBase.getSubTypes(this));
    mapper.registerSubtypes(StoragePluginConfigBase.getSubTypes(this));
    mapper.registerSubtypes(FormatPluginConfigBase.getSubTypes(this));
  }

  RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
  this.startupArguments = ImmutableList.copyOf(bean.getInputArguments());
  logger.debug("DrillConfig object initialized.");
}
项目:StubbornJava    文件:Configs.java   
public Config build() {
    // Resolve substitutions.
    conf = conf.resolve();
    if (log.isDebugEnabled()) {
        log.debug("Logging properties. Make sure sensitive data such as passwords or secrets are not logged!");
        log.debug(conf.root().render(ConfigRenderOptions.concise().setFormatted(true)));
    }
    return conf;
}
项目:dremio-oss    文件:SabotConfig.java   
@VisibleForTesting
public SabotConfig(Config config, boolean enableServerConfigs) {
  super(config);
  logger.debug("Setting up SabotConfig object.");
  logger.trace("Given Config object is:\n{}",
               config.root().render(ConfigRenderOptions.defaults()));
  RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
  this.startupArguments = ImmutableList.copyOf(bean.getInputArguments());
  logger.debug("SabotConfig object initialized.");
}
项目:mpush    文件:Logs.java   
static boolean init() {
    if (logInit) return true;
    System.setProperty("log.home", CC.mp.log_dir);
    System.setProperty("log.root.level", CC.mp.log_level);
    System.setProperty(CONFIG_FILE_PROPERTY, CC.mp.log_conf_path);
    LoggerFactory
            .getLogger("console")
            .info(CC.mp.cfg.root().render(ConfigRenderOptions.concise().setFormatted(true)));
    return true;
}
项目:microtrader    文件:AuditVerticle.java   
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) throws ClassNotFoundException {
    super.start();

    // Get configuration
    config = ConfigFactory.load();

    // creates the jdbc client.
    JsonObject jdbcConfig = new JsonObject(config.getObject("jdbc").render(ConfigRenderOptions.concise()));
    jdbc = JDBCClient.createNonShared(vertx, jdbcConfig);
    Class.forName(jdbcConfig.getString("driverclass"));

    // Start HTTP server and listen for portfolio events
    EventBus eventBus = vertx.eventBus();
    Future<HttpServer> httpEndpointReady = configureTheHTTPServer();
    httpEndpointReady.setHandler(ar -> {
       if (ar.succeeded()) {
           MessageConsumer<JsonObject> portfolioConsumer = eventBus.consumer(config.getString("portfolio.address"));
           portfolioConsumer.handler(message -> {
               storeInDatabase(message.body());
           });
           future.complete();
       } else {
           future.fail(ar.cause());
       }
    });

    publishHttpEndpoint("audit", config.getString("http.host"), config.getInt("http.public.port"), config.getString("http.root"), ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        } else {
            System.out.println("Audit (Rest endpoint) service published : " + ar.succeeded());
        }
    });
}
项目:OpenModLoader    文件:Config.java   
/**
 * Saves the config to disc.
 */
public void save() {
    if (file == null) {
        throw new UnsupportedOperationException("Only root configs can be saved!");
    }
    if (hasChanged()) {
        try {
            FileUtils.writeStringToFile(file, config.root().render(ConfigRenderOptions.defaults().setJson(false).setOriginComments(true).setComments(false)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
项目:J-Kinopoisk2IMDB    文件:Controller.java   
boolean destroy() {
    if (clientExecutor.isRunning()) {
        if (!confirmStop()) {
            return false;
        }

        clientExecutor.terminate();
    }

    byte[] configuration = ConfigFactory.parseMap(configMap)
            .withFallback(config)
            .root()
            .render(ConfigRenderOptions.concise())
            .getBytes();

    try {
        Path parentDir = configPath.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }
        Files.write(configPath, configuration);
    } catch (IOException ignore) {
        // Do nothing
    }

    return true;
}
项目:StubbornJava    文件:Configs.java   
public Config build() {
    // Resolve substitutions.
    conf = conf.resolve();
    if (log.isDebugEnabled()) {
        log.debug("Logging properties. Make sure sensitive data such as passwords or secrets are not logged!");
        log.debug(conf.root().render(ConfigRenderOptions.concise().setFormatted(true)));
    }
    return conf;
}
项目:drill    文件:DrillConfig.java   
@VisibleForTesting
public DrillConfig(Config config, boolean enableServerConfigs) {
  super(config);
  logger.debug("Setting up DrillConfig object.");
  logger.trace("Given Config object is:\n{}",
               config.root().render(ConfigRenderOptions.defaults()));
  RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
  this.startupArguments = ImmutableList.copyOf(bean.getInputArguments());
  logger.debug("DrillConfig object initialized.");
}
项目:Infra    文件:ServiceControlHandler.java   
/**
 * @param request
 * @return response
 * @throws ServiceException
 */
public String getAllConfig(ServiceControlRequest req) throws ServiceException
{

    Config config = ServiceConfig.session().getConfig(ConfigType.ALL);
    String resp = config.root().render(ConfigRenderOptions.concise());
    return resp;
}
项目:runrightfast-vertx    文件:ConfigUtils.java   
static String renderConfig(final Config config, final boolean comments, final boolean orginComments, final boolean json) {
    checkNotNull(config);
    final ConfigRenderOptions options = ConfigRenderOptions.defaults()
            .setComments(comments)
            .setOriginComments(orginComments)
            .setJson(json)
            .setFormatted(true);
    return config.root().render(options);
}
项目:runrightfast-vertx    文件:ConfigUtils.java   
static String renderConfigAsJson(final Config config, final boolean formatted) {
    checkNotNull(config);
    final ConfigRenderOptions options = ConfigRenderOptions.defaults()
            .setComments(false)
            .setOriginComments(false)
            .setJson(true)
            .setFormatted(formatted);
    return config.root().render(options);
}
项目:incubator-gobblin    文件:ConfigurableCleanableDataset.java   
private void initWithSelectionPolicy(Config config, Properties jobProps) {

    String selectionPolicyKey = StringUtils.substringAfter(SELECTION_POLICY_CLASS_KEY, CONFIGURATION_KEY_PREFIX);
    String versionFinderKey = StringUtils.substringAfter(VERSION_FINDER_CLASS_KEY, CONFIGURATION_KEY_PREFIX);
    Preconditions.checkArgument(
        config.hasPath(versionFinderKey),
        String.format("Version finder class is required at %s in config %s", versionFinderKey,
            config.root().render(ConfigRenderOptions.concise())));

    VersionFinderAndPolicyBuilder<T> builder = VersionFinderAndPolicy.builder();
    builder.versionFinder(createVersionFinder(config.getString(versionFinderKey), config, jobProps));
    if (config.hasPath(selectionPolicyKey)) {
      builder.versionSelectionPolicy(createSelectionPolicy(
          ConfigUtils.getString(config, selectionPolicyKey, SelectNothingPolicy.class.getName()), config, jobProps));
    }

    for (Class<? extends RetentionActionFactory> factoryClass : RETENTION_ACTION_TYPES) {
      try {
        RetentionActionFactory factory = factoryClass.newInstance();
        if (factory.canCreateWithConfig(config)) {
          builder.retentionAction((RetentionAction) factory.createRetentionAction(config, this.fs,
              ConfigUtils.propertiesToConfig(jobProps)));
        }
      } catch (InstantiationException | IllegalAccessException e) {
        Throwables.propagate(e);
      }
    }

    this.versionFindersAndPolicies.add(builder.build());

  }
项目:incubator-gobblin    文件:ConfigurableCleanableDataset.java   
@SuppressWarnings("unchecked")
private VersionSelectionPolicy<T> createSelectionPolicy(String className, Config config, Properties jobProps) {
  try {
    this.log.debug(String.format("Configuring selection policy %s for %s with %s", className, this.datasetRoot,
        config.root().render(ConfigRenderOptions.concise())));
    return (VersionSelectionPolicy<T>) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(className),
        ImmutableList.<Object> of(config), ImmutableList.<Object> of(config, jobProps),
        ImmutableList.<Object> of(jobProps));
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
      | ClassNotFoundException e) {
    throw new IllegalArgumentException(e);
  }
}
项目:incubator-gobblin    文件:CleanableHiveDataset.java   
public CleanableHiveDataset(FileSystem fs, HiveMetastoreClientPool clientPool, Table table, Properties jobProps,
    Config config) throws IOException {
  super(fs, clientPool, table, jobProps, config);

  try {
    this.hiveSelectionPolicy =
        (VersionSelectionPolicy) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(ConfigUtils.getString(
            this.datasetConfig, SELECTION_POLICY_CLASS_KEY, DEFAULT_SELECTION_POLICY_CLASS)), ImmutableList.<Object> of(
            this.datasetConfig, jobProps), ImmutableList.<Object> of(this.datasetConfig), ImmutableList.<Object> of(jobProps));

    log.info(String.format("Configured selection policy %s for dataset:%s with config %s",
        ConfigUtils.getString(this.datasetConfig, SELECTION_POLICY_CLASS_KEY, DEFAULT_SELECTION_POLICY_CLASS),
        datasetURN(), this.datasetConfig.root().render(ConfigRenderOptions.concise())));

    this.hiveDatasetVersionFinder =
        (AbstractHiveDatasetVersionFinder) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(ConfigUtils
            .getString(this.datasetConfig, VERSION_FINDER_CLASS_KEY, DEFAULT_VERSION_FINDER_CLASS)), ImmutableList
            .<Object> of(this.fs, this.datasetConfig), ImmutableList.<Object> of(this.fs, jobProps));
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
      | ClassNotFoundException e) {
    log.error("Failed to instantiate CleanableHiveDataset", e);
    throw new IllegalArgumentException(e);
  }

  this.fsCleanableHelper = new FsCleanableHelper(fs, jobProps, this.datasetConfig, log);

  this.shouldDeleteData = Boolean.valueOf(jobProps.getProperty(SHOULD_DELETE_DATA_KEY, SHOULD_DELETE_DATA_DEFAULT));
  this.simulate = Boolean.valueOf(jobProps.getProperty(FsCleanableHelper.SIMULATE_KEY, FsCleanableHelper.SIMULATE_DEFAULT));
}
项目:incubator-gobblin    文件:MultiAccessControlAction.java   
@Override
public MultiAccessControlAction createRetentionAction(Config config, FileSystem fs, Config jobConfig) {
  Preconditions.checkArgument(this.canCreateWithConfig(config),
      "Can not create MultiAccessControlAction with config " + config.root().render(ConfigRenderOptions.concise()));
  if (config.hasPath(LEGACY_ACCESS_CONTROL_KEY)) {
    return new MultiAccessControlAction(config.getConfig(LEGACY_ACCESS_CONTROL_KEY), fs, jobConfig);
  } else if (config.hasPath(ACCESS_CONTROL_KEY)) {
    return new MultiAccessControlAction(config.getConfig(ACCESS_CONTROL_KEY), fs, jobConfig);
  }
  throw new IllegalStateException(
      "RetentionActionFactory.canCreateWithConfig returned true but could not create MultiAccessControlAction");
}
项目:incubator-gobblin    文件:ConfigBasedMultiDatasets.java   
public ConfigBasedMultiDatasets (Config c, Properties props,
    Optional<List<String>> blacklistPatterns){
  this.props = props;
  blacklist = patternListInitHelper(blacklistPatterns);

  try {
    FileSystem executionCluster = FileSystem.get(new Configuration());
    URI executionClusterURI = executionCluster.getUri();

    ReplicationConfiguration rc = ReplicationConfiguration.buildFromConfig(c);

    // push mode
    if(this.props.containsKey(REPLICATION_PUSH_MODE) && Boolean.parseBoolean(this.props.getProperty(REPLICATION_PUSH_MODE))){
      generateDatasetInPushMode(rc, executionClusterURI);
    }
    // default pull mode
    else{
      generateDatasetInPullMode(rc, executionClusterURI);
    }
  } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    log.error("Can not create Replication Configuration from raw config "
        + c.root().render(ConfigRenderOptions.defaults().setComments(false).setOriginComments(false)), e);
  } catch (IOException ioe) {
    log.error("Can not decide current execution cluster ", ioe);

  }
}
项目:incubator-gobblin    文件:SimpleHDFSStoreMetadata.java   
/**
 * Writes the <code>config</code> to {@link #storeMetadataFilePath}. Creates a backup file at
 * <code>storeMetadataFilePath + ".bkp"</code> to recover old metadata in case of unexpected deployment failures
 *
 * @param config to be serialized
 * @throws IOException if there was any problem writing the <code>config</code> to the store metadata file.
 */
void writeMetadata(Config config) throws IOException {

  Path storeMetadataFileBkpPath =
      new Path(this.storeMetadataFilePath.getParent(), this.storeMetadataFilePath.getName() + ".bkp");

  // Delete old backup file if exists
  HadoopUtils.deleteIfExists(this.fs, storeMetadataFileBkpPath, true);

  // Move current storeMetadataFile to backup
  if (this.fs.exists(this.storeMetadataFilePath)) {
    HadoopUtils.renamePath(this.fs, this.storeMetadataFilePath, storeMetadataFileBkpPath);
  }

  // Write new storeMetadataFile
  try (FSDataOutputStream outputStream =
      FileSystem.create(this.fs, this.storeMetadataFilePath, FsDeploymentConfig.DEFAULT_STORE_PERMISSIONS);) {
    outputStream.write(config.root().render(ConfigRenderOptions.concise()).getBytes(Charsets.UTF_8));
  } catch (Exception e) {
    // Restore from backup
    HadoopUtils.deleteIfExists(this.fs, this.storeMetadataFilePath, true);
    HadoopUtils.renamePath(this.fs, storeMetadataFileBkpPath, this.storeMetadataFilePath);
    throw new IOException(
        String.format("Failed to write store metadata at %s. Restored existing store metadata file from backup",
            this.storeMetadataFilePath),
        e);
  }
}
项目:incubator-gobblin    文件:FSJobCatalog.java   
/**
 * Used for shadow copying in the process of updating a existing job configuration file,
 * which requires deletion of the pre-existed copy of file and create a new one with the same name.
 * Steps:
 *  Create a new one in /tmp.
 *  Safely deletion of old one.
 *  copy the newly created configuration file to jobConfigDir.
 *  Delete the shadow file.
 */
synchronized void materializedJobSpec(Path jobSpecPath, JobSpec jobSpec, FileSystem fs)
    throws IOException, JobSpecNotFoundException {
  Path shadowDirectoryPath = new Path("/tmp");
  Path shadowFilePath = new Path(shadowDirectoryPath, UUID.randomUUID().toString());
  /* If previously existed, should delete anyway */
  if (fs.exists(shadowFilePath)) {
    fs.delete(shadowFilePath, false);
  }

  ImmutableMap.Builder mapBuilder = ImmutableMap.builder();
  mapBuilder.put(ImmutableFSJobCatalog.DESCRIPTION_KEY_IN_JOBSPEC, jobSpec.getDescription())
      .put(ImmutableFSJobCatalog.VERSION_KEY_IN_JOBSPEC, jobSpec.getVersion());

  if (jobSpec.getTemplateURI().isPresent()) {
    mapBuilder.put(ConfigurationKeys.JOB_TEMPLATE_PATH, jobSpec.getTemplateURI().get().toString());
  }

  Map<String, String> injectedKeys = mapBuilder.build();
  String renderedConfig = ConfigFactory.parseMap(injectedKeys).withFallback(jobSpec.getConfig())
      .root().render(ConfigRenderOptions.defaults());
  try (DataOutputStream os = fs.create(shadowFilePath);
      Writer writer = new OutputStreamWriter(os, Charsets.UTF_8)) {
    writer.write(renderedConfig);
  }

  /* (Optionally:Delete oldSpec) and copy the new one in. */
  if (fs.exists(jobSpecPath)) {
    if (! fs.delete(jobSpecPath, false)) {
      throw new IOException("Unable to delete existing job file: " + jobSpecPath);
    }
  }
  if (!fs.rename(shadowFilePath, jobSpecPath)) {
    throw new IOException("Unable to rename job file: " + shadowFilePath + " to " + jobSpecPath);
  }
}
项目:concrete-java    文件:AbstractConcreteRedisSubConfig.java   
protected AbstractConcreteRedisSubConfig(Config cfg, String key) {
  ConfigRenderOptions rOpts = ConfigRenderOptions.defaults()
      .setOriginComments(false)
      .setComments(false)
      .setJson(false);
  cfg.checkValid(ConfigFactory.defaultReference(), key);
  this.cfg = cfg.getConfig(key);
  LOGGER.debug("Running with config: {}", this.cfg.root().render(rOpts));
  this.wrapper = new RedisWrapper(this.getHost(), this.getPort());
}
项目:cdk    文件:PrettyPrinter.java   
public static void main(String[] args) {
  if (args.length ==0) {
    System.err.println("Usage: java -cp ... " + PrettyPrinter.class.getName() + " <morphlineConfigFile>");
    return;
  }

  Config config = ConfigFactory.parseFile(new File(args[0]));
  String str = config.root().render(
      ConfigRenderOptions.concise().setFormatted(true).setJson(false).setComments(true));

  System.out.println(str);
}
项目:oryx    文件:GenerationRunner.java   
private void storeConfig(Config config) throws IOException {
  String outputKey = Namespaces.getInstanceGenerationPrefix(instanceDir, generationID) + "computation.conf";
  String configString = config.root().render(ConfigRenderOptions.concise());
  Writer writer = new OutputStreamWriter(Store.get().streamTo(outputKey), Charsets.UTF_8);
  try {
    writer.write(configString);
  } finally {
    writer.close();
  }
}
项目:bench    文件:ActorBootstrapTest.java   
private String clusterConfig() {
    return ConfigFactory.parseString("{\"" + ClusterClients.FACTORY_CLASS + "\":\"" + ClusterClientsTest.DummyClusterClientFactory.class.getName() + "\"," + //
                                             "\"" + ClusterClients.FACTORY_CONFIG + "\":{}}").root().render(
            ConfigRenderOptions.concise());
}
项目:bench    文件:JMSClusterConfigs.java   
private static String jmsFactoryConfigJson(final JMSEndpoint endpoint) {
    return endpoint.toConfig().root().render(ConfigRenderOptions.concise());
}
项目:bench    文件:JMSAgentCluster.java   
private static String jmsFactoryConfigJson(final JMSEndpoint endpoint) {
    return endpoint.toConfig().root().render(ConfigRenderOptions.concise());
}
项目:bench    文件:AgentConfig.java   
public String clusterConfigJson() {
    return clusterConfig.root().render(ConfigRenderOptions.concise());
}