Java Code Examples for net.sourceforge.argparse4j.inf.Namespace#getBoolean()

The following examples show how to use net.sourceforge.argparse4j.inf.Namespace#getBoolean() . 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: Game.java    From minecraft-world-downloader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parse arguments from the commandline.
 */
public static void init(Namespace args) {
    Game.args = args;

    Coordinate2D.setOffset(-args.getInt("center-x"), -args.getInt("center-z"));

    Palette.setMaskBedrock(args.getBoolean("mask-bedrock"));

    initFolders();

    WorldManager.setSaveServiceVariables(args.getBoolean("mark-new-chunks"), args.getBoolean("write-chunks"));
    if (args.getBoolean("gui")) {
        GuiManager.showGui();
    }
    enableWorldGen = args.getBoolean("enable-world-gen");

    versionHandler = VersionHandler.createVersionHandler();
}
 
Example 2
Source File: JobWatchCommand.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
int run(final Namespace options, final List<TargetAndClient> clients,
        final PrintStream out, final boolean json, final BufferedReader stdin)
    throws ExecutionException, InterruptedException, IOException {
  final boolean exact = options.getBoolean(exactArg.getDest());
  final List<String> prefixes = options.getList(prefixesArg.getDest());
  final String jobIdString = options.getString(jobsArg.getDest());
  final List<ListenableFuture<Map<JobId, Job>>> jobIdFutures = Lists.newArrayList();
  for (final TargetAndClient cc : clients) {
    jobIdFutures.add(cc.getClient().jobs(jobIdString));
  }

  final Set<JobId> jobIds = Sets.newHashSet();
  for (final ListenableFuture<Map<JobId, Job>> future : jobIdFutures) {
    jobIds.addAll(future.get().keySet());
  }

  watchJobsOnHosts(out, exact, prefixes, jobIds, options.getInt(intervalArg.getDest()),
      clients);
  return 0;
}
 
Example 3
Source File: RenderCommand.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<HelloWorldConfiguration> bootstrap,
                   Namespace namespace,
                   HelloWorldConfiguration configuration) throws Exception {
    final Template template = configuration.buildTemplate();

    if (namespace.getBoolean("include-default")) {
        LOGGER.info("DEFAULT => {}", template.render(Optional.<String>empty()));
    }

    for (String name : namespace.<String>getList("names")) {
        for (int i = 0; i < 1000; i++) {
            LOGGER.info("{} => {}", name, template.render(Optional.of(name)));
            Thread.sleep(1000);
        }
    }
}
 
Example 4
Source File: CreateKeyspacesCommand.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration emoConfiguration)
        throws Exception {
    _outputOnly = namespace.getBoolean("output_only");

    DdlConfiguration ddlConfiguration = parseDdlConfiguration(toFile(namespace.getString("config-ddl")));
    CuratorFramework curator = null;
    if (!_outputOnly) {
        curator = emoConfiguration.getZooKeeperConfiguration().newCurator();
        curator.start();
    }
    try {
        createKeyspacesIfNecessary(emoConfiguration, ddlConfiguration, curator, bootstrap.getMetricRegistry());

    } finally {
        Closeables.close(curator, true);
    }
}
 
Example 5
Source File: PrettyPrint.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

    try {
      Namespace ns = parse(args);
      long startTime = System.currentTimeMillis();
      TranslationUnit tu = ParseHelper.parse(new File(ns.getString("shader")));
      long endTime = System.currentTimeMillis();

      if (ns.getBoolean("add_braces")) {
        tu = AddBraces.transform(tu);
      }

      prettyPrintShader(ns, tu);

      System.err.println("Time for parsing: " + (endTime - startTime));
    } catch (Throwable exception) {
      exception.printStackTrace();
      System.exit(1);
    }

  }
 
Example 6
Source File: Main.java    From lancoder with GNU General Public License v3.0 6 votes vote down vote up
private static ConfigManager<? extends Config> getConfigManager(Container container, Namespace argsNamespace) {
	boolean promptInit = argsNamespace.getBoolean("init_prompt");
	boolean defaultInit = argsNamespace.getBoolean("init_default");
	boolean overwrite = argsNamespace.getBoolean("overwrite");
	String configPath = argsNamespace.getString("config");

	boolean isNewConfig = promptInit || defaultInit;

	// Initialize config factory from container's config type
	ConfigFactory<? extends Config> configFactory = new ConfigFactory<>(container.getConfigClass(), configPath);

	// Initialize config manager from factory
	ConfigManager<? extends Config> manager = isNewConfig ? configFactory.init(promptInit, overwrite)
			: configFactory.getManager();
	return manager;
}
 
Example 7
Source File: HostDeregisterCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
        final boolean json, final BufferedReader stdin)
    throws ExecutionException, InterruptedException, IOException {
  final String host = options.getString(hostArg.getDest());
  final boolean yes = options.getBoolean(yesArg.getDest());

  if (!yes) {
    out.printf("This will deregister the host %s%n", host);
    final boolean confirmed = Utils.userConfirmed(out, stdin);
    if (!confirmed) {
      return 1;
    }
  }

  out.printf("Deregistering host %s%n", host);

  int code = 0;

  final HostDeregisterResponse response = client.deregisterHost(host).get();
  out.printf("%s: ", host);
  if (response.getStatus() == HostDeregisterResponse.Status.OK) {
    out.printf("done%n");
  } else {
    out.printf("failed: %s%n", response);

    if (response.getStatus() == HostDeregisterResponse.Status.NOT_FOUND) {
      final HostResolver resolver = HostResolver.create(client);
      final List<String> resolved = resolver.getSortedMatches(host);
      if (!resolved.isEmpty()) {
        out.println("We didn't find your hostname, but we did find some possible matches for you:"
                    + "\n    " + Joiner.on("\n    ").join(resolved) + "\n");
      }
    }
    code = 1;
  }
  return code;
}
 
Example 8
Source File: ServiceParser.java    From helios with Apache License 2.0 5 votes vote down vote up
protected FastForwardConfig ffwdConfig(final Namespace options) {
  if (!options.getBoolean(ffwdEnabled.getDest())) {
    return null;
  }

  return new FastForwardConfig(
      Optional.ofNullable(options.getString(ffwdAddress.getDest())),
      options.getInt(ffwdInterval.getDest()),
      options.getString(ffwdMetricKey.getDest()));
}
 
Example 9
Source File: NewCommand.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
    try {
        final Path configPath = Paths.get(WORKSPACE_CONFIG_FILENAME);
        tryWriteFile(configPath, openResourceFile("config-template.yml"));

        final Path usersPath = Paths.get(WORKSPACE_USER_FILENAME);
        tryWriteFile(usersPath, toInputStream("", Charset.forName("UTF-8")));

        final Path specDir = Paths.get(WORKSPACE_SPECS_DIRNAME);
        tryCreateDir(specDir);

        if (namespace.getBoolean(DEMO_ARG_NAME)) {
            tryWriteDemoSpec(specDir);
        }

        final Path jobsDir = Paths.get(WORKSPACE_JOBS_DIRNAME);
        tryCreateDir(jobsDir);

        final Path wdsDir = Paths.get(WORKSPACE_WDS_DIRNAME);
        tryCreateDir(wdsDir);

        System.out.println("Deployment created. Remember to add users (`user add`, `user passwd`), specs (`generate spec`), and boot the server (`serve`)");
        System.exit(0);
    } catch (IOException ex) {
        System.err.println(ex.toString());
        System.err.println(
                "Error creating jobson files/directories. Do you have file permissions? " +
                "Could some of the files already exist (this app won't overwrite files)?");
        System.exit(1);
    }
}
 
Example 10
Source File: DeploymentGroupWatchCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
int run(Namespace options, HeliosClient client, PrintStream out, boolean json,
        BufferedReader stdin) throws ExecutionException, InterruptedException, IOException {
  final String name = options.getString(nameArg.getDest());
  final boolean full = options.getBoolean(fullArg.getDest());
  final Integer interval = options.getInt(intervalArg.getDest());
  final DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_TIME_PATTERN);

  if (!json) {
    out.println("Control-C to stop");
    out.println("STATUS               HOST                           STATE");
  }

  final int timestampLength = String.format("[%s UTC]", DATE_TIME_PATTERN).length();

  int rc = 0;
  while (rc == 0) {
    final Instant now = new Instant();
    if (!json) {
      out.printf(Strings.repeat("-", MAX_WIDTH - timestampLength - 1)
                 + " [%s UTC]%n", now.toString(formatter));
    }

    rc = DeploymentGroupStatusCommand.run0(client, out, json, name, full);
    if (out.checkError()) {
      break;
    }

    Thread.sleep(1000 * interval);
  }
  return 0;
}
 
Example 11
Source File: DeploymentGroupCreateCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
        final boolean json, final BufferedReader stdin)
    throws ExecutionException, InterruptedException, IOException {
  final String name = options.getString(nameArg.getDest());
  final List<HostSelector> hostSelectors = Utils.parseHostSelectors(options, hostSelectorsArg);
  final boolean quiet = options.getBoolean(quietArg.getDest());

  final DeploymentGroup deploymentGroup = DeploymentGroup.newBuilder()
      .setName(name)
      .setHostSelectors(hostSelectors)
      .build();

  if (!quiet && !json) {
    out.println("Creating deployment group: " + deploymentGroup.toJsonString());
  }

  final CreateDeploymentGroupResponse status =
      client.createDeploymentGroup(deploymentGroup).get();

  if (status == null) {
    throw new RuntimeException("The Helios master could not create a deployment group.");
  }

  if (status.getStatus() != CreateDeploymentGroupResponse.Status.CONFLICT) {
    out.println(status.toJsonString());
    return 0;
  } else {
    if (!quiet && !json) {
      out.println("Failed: " + status);
    } else if (json) {
      out.println(status.toJsonString());
    }
    return 1;
  }
}
 
Example 12
Source File: DbValidateCommand.java    From dropwizard-flyway with Apache License 2.0 5 votes vote down vote up
@Override
protected void setAdditionalOptions(FlywayFactory flywayFactory, Namespace namespace) {
    final Boolean outOfOrder = namespace.getBoolean(OUT_OF_ORDER);
    final Boolean cleanOnValidationError = namespace.getBoolean(CLEAN_ON_VALIDATION_ERROR);
    
    if (outOfOrder != null) {
        flywayFactory.setOutOfOrder(outOfOrder);
    }

    if (cleanOnValidationError != null) {
        flywayFactory.setCleanOnValidationError(cleanOnValidationError);
    }

}
 
Example 13
Source File: DiffyCliProcessor.java    From jolt with Apache License 2.0 5 votes vote down vote up
/**
 * Process the Diffy Subcommand
 *
 * @param ns Namespace which contains parsed commandline arguments
 * @return true if no differences are found, false if a difference is found or an error occurs
 */
@Override
public boolean process( Namespace ns ) {
    boolean suppressOutput = ns.getBoolean( "s" );

    Object jsonObject1 = JoltCliUtilities.createJsonObjectFromFile( (File) ns.get( "filePath1" ), suppressOutput );
    File file = ns.get( "filePath2" );
    Object jsonObject2 = JoltCliUtilities.readJsonInput( file, suppressOutput );

    Diffy diffy;
    if ( ns.getBoolean( "a" ) ) {
        diffy = new ArrayOrderObliviousDiffy();
    } else {
        diffy = new Diffy();
    }
    Diffy.Result result = diffy.diff( jsonObject1, jsonObject2 );

    if ( result.isEmpty() ) {
        JoltCliUtilities.printToStandardOut( "Diffy found no differences", suppressOutput );
        return true;
    } else {
        try {
            JoltCliUtilities.printToStandardOut( "Differences found. Input #1 contained this:\n" +
                    JsonUtils.toPrettyJsonString( result.expected ) + "\n" +
                    "Input #2 contained this:\n" +
                    JsonUtils.toPrettyJsonString( result.actual ), suppressOutput );

        }
        catch ( Exception e ) {
            JoltCliUtilities.printToStandardOut( "Differences found, but diffy encountered an error while writing the result.", suppressOutput );
        }
        return false;
    }
}
 
Example 14
Source File: DeploymentGroupStatusCommand.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
int run(final Namespace options, final HeliosClient client, final PrintStream out,
        final boolean json, final BufferedReader stdin)
    throws ExecutionException, InterruptedException {
  final String name = options.getString(nameArg.getDest());
  final boolean full = options.getBoolean(fullArg.getDest());

  return run0(client, out, json, name, full);
}
 
Example 15
Source File: EmoServiceWithZK.java    From emodb with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {

        // Remove all nulls and empty strings from the argument list.  This can happen as if the maven command
        // starts the service with no permission YAML files.
        args = Arrays.stream(args).filter(arg -> !Strings.isNullOrEmpty(arg)).toArray(String[]::new);

        // Start cassandra if necessary (cassandra.yaml is provided)
        ArgumentParser parser = ArgumentParsers.newArgumentParser("java -jar emodb-web-local*.jar");
        parser.addArgument("server").required(true).help("server");
        parser.addArgument("emo-config").required(true).help("config.yaml - EmoDB's config file");
        parser.addArgument("emo-config-ddl").required(true).help("config-ddl.yaml - EmoDB's cassandra schema file");
        parser.addArgument("cassandra-yaml").nargs("?").help("cassandra.yaml - Cassandra configuration file to start an" +
                " in memory embedded Cassandra.");
        parser.addArgument("-z","--zookeeper").dest("zookeeper").action(Arguments.storeTrue()).help("Starts zookeeper");
        parser.addArgument("-p","--permissions-yaml").dest("permissions").nargs("*").help("Permissions file(s)");

        // Get the path to cassandraYaml or if zookeeper is available
        Namespace result = parser.parseArgs(args);
        String cassandraYaml = result.getString("cassandra-yaml");
        boolean startZk = result.getBoolean("zookeeper");
        String emoConfigYaml = result.getString("emo-config");
        List<String> permissionsYamls = result.getList("permissions");

        String[] emoServiceArgs = args;

        // Start ZooKeeper
        TestingServer zooKeeperServer = null;
        if (startZk) {
            zooKeeperServer = isLocalZooKeeperRunning() ? null : startLocalZooKeeper();
            emoServiceArgs = (String[]) ArrayUtils.removeElement(args, "-z");
            emoServiceArgs = (String[]) ArrayUtils.removeElement(emoServiceArgs, "--zookeeper");

        }
        boolean success = false;


        if (cassandraYaml != null) {
            // Replace $DIR$ so we can correctly specify location during runtime
            File templateFile = new File(cassandraYaml);
            String baseFile = Files.toString(templateFile, Charset.defaultCharset());
            // Get the jar location
            String path = EmoServiceWithZK.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String parentDir = new File(path).getParent();
            String newFile = baseFile.replace("$DATADIR$", new File(parentDir, "data").getAbsolutePath());
            newFile = newFile.replace("$COMMITDIR$", new File(parentDir, "commitlog").getAbsolutePath());
            newFile = newFile.replace("$CACHEDIR$", new File(parentDir, "saved_caches").getAbsolutePath());
            File newYamlFile = new File(templateFile.getParent(), "emo-cassandra.yaml");
            Files.write(newFile, newYamlFile, Charset.defaultCharset());

            startLocalCassandra(newYamlFile.getAbsolutePath());
            emoServiceArgs = (String[]) ArrayUtils.removeElement(emoServiceArgs, cassandraYaml);
        }

        // If permissions files were configured remove them from the argument list
        int permissionsIndex = Math.max(ArrayUtils.indexOf(emoServiceArgs, "-p"), ArrayUtils.indexOf(emoServiceArgs, "--permissions-yaml"));
        if (permissionsIndex >= 0) {
            int permissionsArgCount = 1 + permissionsYamls.size();
            for (int i=0; i < permissionsArgCount; i++) {
                emoServiceArgs = (String[]) ArrayUtils.remove(emoServiceArgs, permissionsIndex);
            }
        }

        try {
            EmoService.main(emoServiceArgs);
            success = true;

            setPermissionsFromFiles(permissionsYamls, emoConfigYaml);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            // The main web server command returns immediately--don't stop ZooKeeper/Cassandra in that case.
            if (zooKeeperServer != null && !(success && args.length > 0 && "server".equals(args[0]))) {
                zooKeeperServer.stop();
                service.shutdown();
            }
        }
    }
 
Example 16
Source File: Main.java    From signal-cli with GNU General Public License v3.0 4 votes vote down vote up
private static Namespace parseArgs(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("signal-cli")
            .build()
            .defaultHelp(true)
            .description("Commandline interface for Signal.")
            .version(BaseConfig.PROJECT_NAME + " " + BaseConfig.PROJECT_VERSION);

    parser.addArgument("-v", "--version")
            .help("Show package version.")
            .action(Arguments.version());
    parser.addArgument("--config")
            .help("Set the path, where to store the config (Default: $XDG_DATA_HOME/signal-cli , $HOME/.local/share/signal-cli).");

    MutuallyExclusiveGroup mut = parser.addMutuallyExclusiveGroup();
    mut.addArgument("-u", "--username")
            .help("Specify your phone number, that will be used for verification.");
    mut.addArgument("--dbus")
            .help("Make request via user dbus.")
            .action(Arguments.storeTrue());
    mut.addArgument("--dbus-system")
            .help("Make request via system dbus.")
            .action(Arguments.storeTrue());

    Subparsers subparsers = parser.addSubparsers()
            .title("subcommands")
            .dest("command")
            .description("valid subcommands")
            .help("additional help");

    final Map<String, Command> commands = Commands.getCommands();
    for (Map.Entry<String, Command> entry : commands.entrySet()) {
        Subparser subparser = subparsers.addParser(entry.getKey());
        entry.getValue().attachToSubparser(subparser);
    }

    Namespace ns;
    try {
        ns = parser.parseArgs(args);
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        return null;
    }

    if ("link".equals(ns.getString("command"))) {
        if (ns.getString("username") != null) {
            parser.printUsage();
            System.err.println("You cannot specify a username (phone number) when linking");
            System.exit(2);
        }
    } else if (!ns.getBoolean("dbus") && !ns.getBoolean("dbus_system")) {
        if (ns.getString("username") == null) {
            parser.printUsage();
            System.err.println("You need to specify a username (phone number)");
            System.exit(2);
        }
        if (!PhoneNumberFormatter.isValidNumber(ns.getString("username"), null)) {
            System.err.println("Invalid username (phone number), make sure you include the country code.");
            System.exit(2);
        }
    }
    if (ns.getList("recipient") != null && !ns.getList("recipient").isEmpty() && ns.getString("group") != null) {
        System.err.println("You cannot specify recipients by phone number and groups at the same time");
        System.exit(2);
    }
    return ns;
}
 
Example 17
Source File: AtomixAgent.java    From atomix with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an Atomix configuration from the given namespace.
 *
 * @param namespace the namespace from which to create the configuration
 * @return the Atomix configuration for the given namespace
 */
static AtomixConfig createConfig(Namespace namespace) {
  final List<File> configFiles = namespace.getList("config");
  final String memberId = namespace.getString("member");
  final Address address = namespace.get("address");
  final String host = namespace.getString("host");
  final String rack = namespace.getString("rack");
  final String zone = namespace.getString("zone");
  final List<NodeConfig> bootstrap = namespace.getList("bootstrap");
  final boolean multicastEnabled = namespace.getBoolean("multicast");
  final String multicastGroup = namespace.get("multicast_group");
  final Integer multicastPort = namespace.get("multicast_port");

  System.setProperty("atomix.data", namespace.getString("data_dir"));

  // If a configuration was provided, merge the configuration's member information with the provided command line arguments.
  AtomixConfig config;
  if (configFiles != null && !configFiles.isEmpty()) {
    System.setProperty("atomix.config.resources", "");
    config = Atomix.config(configFiles);
  } else {
    config = Atomix.config();
  }

  if (memberId != null) {
    config.getClusterConfig().getNodeConfig().setId(memberId);
  }

  if (address != null) {
    config.getClusterConfig().getNodeConfig().setAddress(address);
  }

  if (host != null) {
    config.getClusterConfig().getNodeConfig().setHostId(host);
  }
  if (rack != null) {
    config.getClusterConfig().getNodeConfig().setRackId(rack);
  }
  if (zone != null) {
    config.getClusterConfig().getNodeConfig().setZoneId(zone);
  }

  if (bootstrap != null && !bootstrap.isEmpty()) {
    config.getClusterConfig().setDiscoveryConfig(new BootstrapDiscoveryConfig().setNodes(bootstrap));
  }

  if (multicastEnabled) {
    config.getClusterConfig().getMulticastConfig().setEnabled(true);
    if (multicastGroup != null) {
      config.getClusterConfig().getMulticastConfig().setGroup(multicastGroup);
    }
    if (multicastPort != null) {
      config.getClusterConfig().getMulticastConfig().setPort(multicastPort);
    }
    if (bootstrap == null || bootstrap.isEmpty()) {
      config.getClusterConfig().setDiscoveryConfig(new MulticastDiscoveryConfig());
    }
  }
  return config;
}
 
Example 18
Source File: KnownValueShaderGenerator.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public static void mainHelper(String[] args) throws ArgumentParserException, IOException {
  final Namespace ns = parse(args);
  final float rFloat = ns.getFloat("r");
  final float gFloat = ns.getFloat("g");
  final float bFloat = ns.getFloat("b");
  final float aFloat = ns.getFloat("a");
  final int maxUniforms = ns.getInt("max_uniforms");
  final boolean isVulkan = ns.getBoolean("vulkan");
  final IRandom generator = new RandomWrapper(ArgsUtil.getSeedArgument(ns));
  final String version = ns.getString("version");
  final File shaderJobFile = ns.get("output");
  final ShaderJobFileOperations fileOps = new ShaderJobFileOperations();

  final TranslationUnit tu =
      new TranslationUnit(Optional.of(ShadingLanguageVersion.fromVersionString(version)),
          Arrays.asList(
              new PrecisionDeclaration("precision highp float;"),
              new PrecisionDeclaration("precision highp int;"),
              new VariablesDeclaration(new QualifiedType(BasicType.VEC4,
                  Arrays.asList(new LayoutQualifierSequence(
                      new LocationLayoutQualifier(0)), TypeQualifier.SHADER_OUTPUT)),
                  new VariableDeclInfo("_GLF_color", null, null)),
              new FunctionDefinition(
                  new FunctionPrototype("main", VoidType.VOID, Collections.emptyList()),
                  new BlockStmt(new ArrayList<>(), false))));

  final PipelineInfo pipelineInfo = new PipelineInfo();
  final FactManager globalFactManager = new FactManager(null);

  // A placeholder statement for what will eventually be the color assignment.
  final Stmt placeholderForColorAssignment = new NullStmt();
  tu.getMainFunction().getBody().addStmt(placeholderForColorAssignment);

  LOGGER.info("About to generate the known value fragment shader"
      + " with the parameters R = " + rFloat + ", G = " + gFloat + ", B = " + bFloat + " and"
      + " A = " + aFloat + ".");

  final ExpressionGenerator expressionGenerator = new
      ExpressionGenerator(tu, pipelineInfo, generator, globalFactManager);
  final FactManager mainFactManager = globalFactManager.newScope();
  final Expr[] rgbaExprs = Stream.of(rFloat, gFloat, bFloat, aFloat)
      .map(item -> expressionGenerator.generateExpr(
          mainFactManager,
          tu.getMainFunction(),
          placeholderForColorAssignment,
          new NumericValue(BasicType.FLOAT, Optional.of(item)))).toArray(Expr[]::new);

  tu.getMainFunction().getBody().replaceChild(placeholderForColorAssignment,
      new ExprStmt(new BinaryExpr(new VariableIdentifierExpr("_GLF_color"),
          new TypeConstructorExpr("vec4", rgbaExprs), BinOp.ASSIGN)));

  final ShaderJob shaderJob = new GlslShaderJob(Optional.empty(), pipelineInfo, tu);

  if (maxUniforms > 0) {
    PruneUniforms.pruneIfNeeded(shaderJob, maxUniforms,
        Collections.singletonList(Constants.GLF_UNIFORM));
  }
  if (isVulkan) {
    shaderJob.makeUniformBindings(Optional.empty());
  }

  fileOps.writeShaderJobFile(shaderJob, shaderJobFile);
  LOGGER.info("Generation complete.");
}
 
Example 19
Source File: JobRemoveCommand.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
protected int runWithJob(final Namespace options, final HeliosClient client,
                         final PrintStream out, final boolean json, final Job job,
                         final BufferedReader stdin)
    throws IOException, ExecutionException, InterruptedException {
  final boolean yes = options.getBoolean(yesArg.getDest());
  final JobId jobId = job.getId();

  if (!yes) {
    out.printf("This will remove the job %s%n", jobId);
    final boolean confirmed = Utils.userConfirmed(out, stdin);
    if (!confirmed) {
      return 1;
    }
  }

  if (!json) {
    out.printf("Removing job %s%n", jobId);
  }

  int code = 0;

  final String token = options.getString(tokenArg.getDest());
  final JobDeleteResponse response = client.deleteJob(jobId, token).get();
  if (!json) {
    out.printf("%s: ", jobId);
  }
  if (response.getStatus() == JobDeleteResponse.Status.OK) {
    if (json) {
      out.print(response.toJsonString());
    } else {
      out.printf("done%n");
    }
  } else {
    if (json) {
      out.print(response.toJsonString());
    } else {
      out.printf("failed: %s%n", response);
    }
    code = 1;
  }
  return code;
}
 
Example 20
Source File: JobDeployCommand.java    From helios with Apache License 2.0 4 votes vote down vote up
@Override
protected int runWithJob(final Namespace options, final HeliosClient client,
                         final PrintStream out, final boolean json, final Job job,
                         final BufferedReader stdin)
    throws ExecutionException, InterruptedException {
  final JobId jobId = job.getId();
  final List<String> hosts = options.getList(hostsArg.getDest());
  final Deployment deployment = Deployment.of(jobId,
      options.getBoolean(noStartArg.getDest()) ? STOP : START);

  if (!json) {
    out.printf("Deploying %s on %s%n", deployment, hosts);
  }

  int code = 0;

  final HostResolver resolver = HostResolver.create(client);

  final List<String> resolvedHosts = Lists.newArrayList();
  for (final String candidateHost : hosts) {
    final String host = resolver.resolveName(candidateHost);
    resolvedHosts.add(host);
    if (!json) {
      out.printf("%s: ", host);
    }
    final String token = options.getString(tokenArg.getDest());
    final JobDeployResponse result = client.deploy(deployment, host, token).get();
    if (result.getStatus() == JobDeployResponse.Status.OK) {
      if (!json) {
        out.printf("done%n");
      } else {
        out.print(result.toJsonString());
      }
    } else {
      if (!json) {
        out.printf("failed: %s%n", result);
      } else {
        out.print(result.toJsonString());
      }
      code = 1;
    }
  }

  if (code == 0 && options.getBoolean(watchArg.getDest())) {
    JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
        options.getInt(intervalArg.getDest()), client);
  }
  return code;
}