Search in sources :

Example 26 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project atomix by atomix.

the class AtomixAgent method main.

public static void main(String[] args) throws Exception {
    ArgumentType<Node> nodeArgumentType = (ArgumentParser argumentParser, Argument argument, String value) -> {
        String[] address = parseAddress(value);
        return Node.builder(parseNodeId(address)).withType(Node.Type.CORE).withEndpoint(parseEndpoint(address)).build();
    };
    ArgumentType<Node.Type> typeArgumentType = (ArgumentParser argumentParser, Argument argument, String value) -> Node.Type.valueOf(value.toUpperCase());
    ArgumentType<File> fileArgumentType = (ArgumentParser argumentParser, Argument argument, String value) -> new File(value);
    ArgumentParser parser = ArgumentParsers.newArgumentParser("AtomixServer").defaultHelp(true).description("Atomix server");
    parser.addArgument("node").type(nodeArgumentType).nargs("?").metavar("NAME:HOST:PORT").setDefault(Node.builder("local").withType(Node.Type.CORE).withEndpoint(new Endpoint(InetAddress.getByName("127.0.0.1"), NettyMessagingService.DEFAULT_PORT)).build()).help("The local node info");
    parser.addArgument("--type", "-t").type(typeArgumentType).metavar("TYPE").choices("core", "data", "client").setDefault(Node.Type.CORE).help("Indicates the local node type");
    parser.addArgument("--bootstrap", "-b").nargs("*").type(nodeArgumentType).metavar("NAME:HOST:PORT").required(false).help("Bootstraps a new cluster");
    parser.addArgument("--http-port", "-p").type(Integer.class).metavar("PORT").required(false).setDefault(5678).help("An optional HTTP server port");
    parser.addArgument("--data-dir", "-dd").type(fileArgumentType).metavar("FILE").required(false).setDefault(new File(System.getProperty("user.dir"), "data")).help("The server data directory");
    parser.addArgument("--core-partitions", "-cp").type(Integer.class).metavar("NUM").required(false).setDefault(7).help("The number of core partitions");
    parser.addArgument("--data-partitions", "-dp").type(Integer.class).metavar("NUM").required(false).setDefault(71).help("The number of data partitions");
    Namespace namespace = null;
    try {
        namespace = parser.parseArgs(args);
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        System.exit(1);
    }
    Node localNode = namespace.get("node");
    Node.Type type = namespace.get("type");
    localNode = Node.builder(localNode.id()).withType(type).withEndpoint(localNode.endpoint()).build();
    List<Node> bootstrap = namespace.getList("bootstrap");
    if (bootstrap == null) {
        bootstrap = Collections.singletonList(localNode);
    }
    File dataDir = namespace.get("data_dir");
    Integer httpPort = namespace.getInt("http_port");
    Integer corePartitions = namespace.getInt("core_partitions");
    Integer dataPartitions = namespace.getInt("data_partitions");
    LOGGER.info("node: {}", localNode);
    LOGGER.info("bootstrap: {}", bootstrap);
    LOGGER.info("data-dir: {}", dataDir);
    Atomix atomix = Atomix.builder().withLocalNode(localNode).withBootstrapNodes(bootstrap).withDataDirectory(dataDir).withCorePartitions(corePartitions).withDataPartitions(dataPartitions).build();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        atomix.stop().join();
    }));
    atomix.start().join();
    LOGGER.info("Atomix listening at {}:{}", localNode.endpoint().host().getHostAddress(), localNode.endpoint().port());
    ManagedRestService rest = RestService.builder().withAtomix(atomix).withEndpoint(Endpoint.from(localNode.endpoint().host().getHostAddress(), httpPort)).build();
    rest.start().join();
    LOGGER.info("HTTP server listening at {}:{}", localNode.endpoint().host().getHostAddress(), httpPort);
    synchronized (Atomix.class) {
        while (atomix.isRunning()) {
            Atomix.class.wait();
        }
    }
}
Also used : Atomix(io.atomix.core.Atomix) Argument(net.sourceforge.argparse4j.inf.Argument) Node(io.atomix.cluster.Node) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace) ArgumentType(net.sourceforge.argparse4j.inf.ArgumentType) Endpoint(io.atomix.messaging.Endpoint) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) ManagedRestService(io.atomix.rest.ManagedRestService) File(java.io.File)

Example 27 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project uuusa by aghie.

the class Samulan method parseCommand.

private static Namespace parseCommand(String[] args) {
    ArgumentParser ap = ArgumentParsers.newArgumentParser("Samulan").defaultHelp(true).description("Apply Sentiment Analysis to files");
    ap.addArgument("-i", "--" + INPUT).required(false).help("Path to the conll file to be analyzed");
    ap.addArgument("-c", "--" + CONLL).required(false).help("Path to a conll file containing the parsed files. " + "You must specify an identifier just above the first conll graph of your text (such as ### IDENTIFIER");
    ap.addArgument("-s", "--" + SENTIDATA).required(true).help("Path to the Sentidata directory");
    ap.addArgument("-e", "--" + ENCODING).setDefault("utf-8").help("Encoding of input data");
    ap.addArgument("-f", "--" + FILTERING).required(false).help("sentistrength to use SentiStrength output. Omit otherwise");
    ap.addArgument("-r", "--" + RULES).help("Path to the .xml file containing the rules");
    ap.addArgument("-o", "--" + OUTPUT).required(false).help("Path to the output file with the predictions");
    ap.addArgument("-v", "--" + VERBOSE).type(Boolean.class).setDefault(false).required(false).help("Print explanation");
    ap.addArgument("-sc", "--" + SCALE).setDefault(TRINARY).help("Selects the type of classification");
    ap.addArgument("-p", "--" + PROPERTIES).required(true).help("Path to the properties file");
    ap.addArgument("-spf", "--" + PATH_SAVED_PARSED_FILE).required(false).help("Path to the file where to saved the parsed sentence in CoNLL format. Useful if you plan to run many experiments");
    Namespace ns = null;
    try {
        // TODO Improve command error checking
        ns = ap.parseArgs(args);
        if (!rawFilesProvided(ns) && !parsedCoNLLFileProvided(ns)) {
            throw new ArgumentParserException(INPUT + " or " + CONLL + " parameter is required", ap);
        }
        if (rawFilesProvided(ns) && parsedCoNLLFileProvided(ns)) {
            throw new ArgumentParserException(INPUT + " or " + CONLL + " cannot appear together required", ap);
        }
        if (ns.get(FILTERING) != null && !ns.get(FILTERING).equals(FILTERING_SENTISTRENGTH)) {
            throw new ArgumentParserException(FILTERING + " not valid", ap);
        }
        if (!ns.get(SCALE).equals(TRINARY) && !ns.get(SCALE).equals(SEMANTIC_ORIENTATION) && !ns.get(SCALE).equals(BINARY)) {
            throw new ArgumentParserException(SCALE + " is not a valid argument. Use: " + SEMANTIC_ORIENTATION + "|" + TRINARY + "|" + BINARY, ap);
        }
    } catch (ArgumentParserException e) {
        ap.handleError(e);
        System.exit(1);
    }
    return ns;
}
Also used : ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 28 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project helios by spotify.

the class CliParser method computeTargets.

private List<Target> computeTargets(final ArgumentParser parser, final List<String> explicitEndpoints, final List<String> domainsArguments, final String srvName) {
    if (explicitEndpoints != null && !explicitEndpoints.isEmpty()) {
        final List<Target> targets = Lists.newArrayListWithExpectedSize(explicitEndpoints.size());
        for (final String endpoint : explicitEndpoints) {
            targets.add(Target.from(URI.create(endpoint)));
        }
        return targets;
    } else if (domainsArguments != null && !domainsArguments.isEmpty()) {
        final Iterable<String> domains = parseDomains(domainsArguments);
        return Target.from(srvName, domains);
    } else if (!cliConfig.getMasterEndpoints().isEmpty()) {
        final List<URI> cliConfigMasterEndpoints = cliConfig.getMasterEndpoints();
        final List<Target> targets = Lists.newArrayListWithExpectedSize(cliConfigMasterEndpoints.size());
        for (final URI endpoint : cliConfigMasterEndpoints) {
            targets.add(Target.from(endpoint));
        }
        return targets;
    } else if (!cliConfig.getDomainsString().isEmpty()) {
        final Iterable<String> domains = parseDomainsString(cliConfig.getDomainsString());
        return Target.from(srvName, domains);
    }
    handleError(parser, new ArgumentParserException("no masters specified.  Use the -z or -d option to specify which helios " + "cluster/master to connect to", parser));
    return ImmutableList.of();
}
Also used : ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) URI(java.net.URI)

Example 29 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project cogcomp-nlp by CogComp.

the class ExternalAnnotatorsServer method startServer.

public static void startServer(String[] args, Logger logger) {
    Namespace parseResults;
    try {
        parseResults = argumentParser.parseArgs(args);
    } catch (HelpScreenException ex) {
        return;
    } catch (ArgumentParserException ex) {
        logger.error("Exception while parsing arguments", ex);
        return;
    }
    port(parseResults.getInt("port"));
    // create a hashmap to keep track of client ip addresses and their
    int rate = parseResults.getInt("rate");
    if (rate > 0) {
        clients = new HashMap<String, Integer>();
    }
    AnnotatorService finalPipeline = pipeline;
    get("/annotate", "application/json", (request, response) -> {
        logger.info("GET request . . . ");
        boolean canServe = true;
        if (rate > 0) {
            resetServer();
            String ip = request.ip();
            int callsSofar = (Integer) clients.getOrDefault(ip, 0);
            if (callsSofar > rate)
                canServe = false;
            clients.put(ip, callsSofar + 1);
        }
        if (canServe) {
            logger.info("request.body(): " + request.body());
            String text = request.queryParams("text");
            String views = request.queryParams("views");
            return annotateText(finalPipeline, text, views, logger);
        } else {
            response.status(429);
            return "You have reached your maximum daily query limit :-/ ";
        }
    });
    post("/annotate", (request, response) -> {
        logger.info("POST request . . . ");
        boolean canServe = true;
        if (rate > 0) {
            resetServer();
            String ip = request.ip();
            int callsSofar = (Integer) clients.getOrDefault(ip, 0);
            if (callsSofar > rate)
                canServe = false;
            clients.put(ip, callsSofar + 1);
        }
        if (canServe) {
            logger.info("request.body(): " + request.body());
            Map<String, String> map = splitQuery(request.body());
            System.out.println("POST body parameters parsed: " + map);
            String text = map.get("text");
            String views = map.get("views");
            return annotateText(finalPipeline, text, views, logger);
        } else {
            response.status(429);
            return "You have reached your maximum daily query limit :-/ ";
        }
    });
    // api to get name of the available views
    String viewsString = "";
    for (String view : pipeline.getAvailableViews()) {
        viewsString += ", " + view;
    }
    String finalViewsString = viewsString;
    enableCORS("*", "*", "*");
    get("/viewNames", (req, res) -> finalViewsString);
    post("/viewNames", (req, res) -> finalViewsString);
}
Also used : AnnotatorService(edu.illinois.cs.cogcomp.annotation.AnnotatorService) HelpScreenException(net.sourceforge.argparse4j.internal.HelpScreenException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 30 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project apache-kafka-on-k8s by banzaicloud.

the class VerifiableProducer method createFromArgs.

/**
 * Construct a VerifiableProducer object from command-line arguments.
 */
public static VerifiableProducer createFromArgs(ArgumentParser parser, String[] args) throws ArgumentParserException {
    Namespace res = parser.parseArgs(args);
    int maxMessages = res.getInt("maxMessages");
    String topic = res.getString("topic");
    int throughput = res.getInt("throughput");
    String configFile = res.getString("producer.config");
    Integer valuePrefix = res.getInt("valuePrefix");
    Long createTime = (long) res.getInt("createTime");
    if (createTime == -1L)
        createTime = null;
    Properties producerProps = new Properties();
    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, res.getString("brokerList"));
    producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
    producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
    producerProps.put(ProducerConfig.ACKS_CONFIG, Integer.toString(res.getInt("acks")));
    // No producer retries
    producerProps.put(ProducerConfig.RETRIES_CONFIG, "0");
    if (configFile != null) {
        try {
            producerProps.putAll(loadProps(configFile));
        } catch (IOException e) {
            throw new ArgumentParserException(e.getMessage(), parser);
        }
    }
    StringSerializer serializer = new StringSerializer();
    KafkaProducer<String, String> producer = new KafkaProducer<>(producerProps, serializer, serializer);
    return new VerifiableProducer(producer, topic, throughput, maxMessages, valuePrefix, createTime);
}
Also used : KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) IOException(java.io.IOException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Properties(java.util.Properties) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Aggregations

ArgumentParserException (net.sourceforge.argparse4j.inf.ArgumentParserException)42 Namespace (net.sourceforge.argparse4j.inf.Namespace)34 ArgumentParser (net.sourceforge.argparse4j.inf.ArgumentParser)30 Properties (java.util.Properties)13 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)6 MutuallyExclusiveGroup (net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup)6 ArgumentGroup (net.sourceforge.argparse4j.inf.ArgumentGroup)4 Platform (org.apache.kafka.trogdor.common.Platform)4 JsonRestServer (org.apache.kafka.trogdor.rest.JsonRestServer)4 AnnotatorService (edu.illinois.cs.cogcomp.annotation.AnnotatorService)3 File (java.io.File)3 Path (java.nio.file.Path)3 List (java.util.List)3 Random (java.util.Random)3 HelpScreenException (net.sourceforge.argparse4j.internal.HelpScreenException)3 KafkaProducer (org.apache.kafka.clients.producer.KafkaProducer)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2