Search in sources :

Example 21 with ArgumentParserException

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

the class MainServer method startServer.

public static void startServer(String[] args) {
    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 :-/ ";
        }
    });
    get("/addviews", "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 jsonStrTA = request.queryParams("jsonstr");
            String views = request.queryParams("views");
            return addAdditionalViewToTA(finalPipeline, jsonStrTA, 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 :-/ ";
        }
    });
    post("/addviews", (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 jsonStrTA = map.get("jsonstr");
            String views = map.get("views");
            return addAdditionalViewToTA(finalPipeline, jsonStrTA, 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);
    get("/version", "application/json", (request, response) -> {
        logger.info("GET request to retrieve version numbers . . . ");
        final Properties properties = new Properties();
        properties.load(pipeline.getClass().getClassLoader().getResourceAsStream("project.properties"));
        System.out.println(properties.getProperty("version"));
        System.out.println(properties.getProperty("artifactId"));
        return properties.getProperty("version");
    });
}
Also used : AnnotatorService(edu.illinois.cs.cogcomp.annotation.AnnotatorService) HelpScreenException(net.sourceforge.argparse4j.internal.HelpScreenException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Properties(java.util.Properties) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 22 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class ProducerPerformance method main.

public static void main(String[] args) throws Exception {
    ArgumentParser parser = argParser();
    try {
        Namespace res = parser.parseArgs(args);
        /* parse args */
        String topicName = res.getString("topic");
        long numRecords = res.getLong("numRecords");
        Integer recordSize = res.getInt("recordSize");
        int throughput = res.getInt("throughput");
        List<String> producerProps = res.getList("producerConfig");
        String producerConfig = res.getString("producerConfigFile");
        String payloadFilePath = res.getString("payloadFile");
        // since default value gets printed with the help text, we are escaping \n there and replacing it with correct value here.
        String payloadDelimiter = res.getString("payloadDelimiter").equals("\\n") ? "\n" : res.getString("payloadDelimiter");
        if (producerProps == null && producerConfig == null) {
            throw new ArgumentParserException("Either --producer-props or --producer.config must be specified.", parser);
        }
        List<byte[]> payloadByteList = new ArrayList<>();
        if (payloadFilePath != null) {
            Path path = Paths.get(payloadFilePath);
            System.out.println("Reading payloads from: " + path.toAbsolutePath());
            if (Files.notExists(path) || Files.size(path) == 0) {
                throw new IllegalArgumentException("File does not exist or empty file provided.");
            }
            String[] payloadList = new String(Files.readAllBytes(path), "UTF-8").split(payloadDelimiter);
            System.out.println("Number of messages read: " + payloadList.length);
            for (String payload : payloadList) {
                payloadByteList.add(payload.getBytes(StandardCharsets.UTF_8));
            }
        }
        Properties props = new Properties();
        if (producerConfig != null) {
            props.putAll(Utils.loadProps(producerConfig));
        }
        if (producerProps != null)
            for (String prop : producerProps) {
                String[] pieces = prop.split("=");
                if (pieces.length != 2)
                    throw new IllegalArgumentException("Invalid property: " + prop);
                props.put(pieces[0], pieces[1]);
            }
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        KafkaProducer<byte[], byte[]> producer = new KafkaProducer<byte[], byte[]>(props);
        /* setup perf test */
        byte[] payload = null;
        Random random = new Random(0);
        if (recordSize != null) {
            payload = new byte[recordSize];
            for (int i = 0; i < payload.length; ++i) payload[i] = (byte) (random.nextInt(26) + 65);
        }
        ProducerRecord<byte[], byte[]> record;
        Stats stats = new Stats(numRecords, 5000);
        long startMs = System.currentTimeMillis();
        ThroughputThrottler throttler = new ThroughputThrottler(throughput, startMs);
        for (int i = 0; i < numRecords; i++) {
            if (payloadFilePath != null) {
                payload = payloadByteList.get(random.nextInt(payloadByteList.size()));
            }
            record = new ProducerRecord<>(topicName, payload);
            long sendStartMs = System.currentTimeMillis();
            Callback cb = stats.nextCompletion(sendStartMs, payload.length, stats);
            producer.send(record, cb);
            if (throttler.shouldThrottle(i, sendStartMs)) {
                throttler.throttle();
            }
        }
        /* print final results */
        producer.close();
        stats.printTotal();
    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            Exit.exit(0);
        } else {
            parser.handleError(e);
            Exit.exit(1);
        }
    }
}
Also used : Path(java.nio.file.Path) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) ArrayList(java.util.ArrayList) Properties(java.util.Properties) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace) Callback(org.apache.kafka.clients.producer.Callback) Random(java.util.Random) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException)

Example 23 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class VerifiableProducer method createFromArgs.

/** Construct a VerifiableProducer object from command-line arguments. */
public static VerifiableProducer createFromArgs(String[] args) {
    ArgumentParser parser = argParser();
    VerifiableProducer producer = null;
    try {
        Namespace res;
        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");
        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("retries", "0");
        if (configFile != null) {
            try {
                producerProps.putAll(loadProps(configFile));
            } catch (IOException e) {
                throw new ArgumentParserException(e.getMessage(), parser);
            }
        }
        producer = new VerifiableProducer(producerProps, topic, throughput, maxMessages, valuePrefix);
    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            Exit.exit(0);
        } else {
            parser.handleError(e);
            Exit.exit(1);
        }
    }
    return producer;
}
Also used : IOException(java.io.IOException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Properties(java.util.Properties) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 24 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project java-docs-samples by GoogleCloudPlatform.

the class SynthesizeFile method main.

// [END tts_synthesize_ssml_file]
public static void main(String... args) throws Exception {
    ArgumentParser parser = ArgumentParsers.newFor("SynthesizeFile").build().defaultHelp(true).description("Synthesize a text file or ssml file.");
    MutuallyExclusiveGroup group = parser.addMutuallyExclusiveGroup().required(true);
    group.addArgument("--text").help("The text file from which to synthesize speech.");
    group.addArgument("--ssml").help("The ssml file from which to synthesize speech.");
    try {
        Namespace namespace = parser.parseArgs(args);
        if (namespace.get("text") != null) {
            synthesizeTextFile(namespace.getString("text"));
        } else {
            synthesizeSsmlFile(namespace.getString("ssml"));
        }
    } catch (ArgumentParserException e) {
        parser.handleError(e);
    }
}
Also used : MutuallyExclusiveGroup(net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 25 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project ASCIIGenome by dariober.

the class InteractiveInput method processInput.

/**
 * Parse the input list of commands to print information or modify the input TrackProcessor.
 * @throws IOException
 * @throws InvalidGenomicCoordsException
 * @throws InvalidCommandLineException
 * @throws SQLException
 * @throws InvalidRecordException
 * @throws ClassNotFoundException
 */
protected TrackProcessor processInput(String cmdConcatInput, TrackProcessor proc, int debug) throws InvalidGenomicCoordsException, IOException, ClassNotFoundException, InvalidRecordException, SQLException, InvalidCommandLineException {
    cmdConcatInput = cmdConcatInput.replaceAll("//.*", "").trim();
    int terminalWidth = Utils.getTerminalWidth();
    // cmdInputList: List of individual commands in tokens to be issued.
    // E.g.: [ ["zi"],
    // ["-F", "16"],
    // ["mapq", "10"] ]
    // Don't check the validity of each cmd now. Execute one by one and if anything goes wrong
    // reset interactiveInputExitCode = 1 (or else other than 0) so that console input is asked again. Of course, what is executed is not
    // rolled back.
    List<String> cmdInputChainList = new ArrayList<String>();
    // For splitting at delimiter (&&) and ignore delimiters inside single quotes.
    for (String cmd : Splitter.on(Pattern.compile("&&(?=([^']*'[^']*')*[^']*$)")).trimResults().omitEmptyStrings().split(cmdConcatInput)) {
        cmdInputChainList.add(cmd);
    }
    if (cmdInputChainList.size() >= 2 && cmdInputChainList.get(0).startsWith("setConfig ")) {
        // This is to refresh the screen and actually set the new color
        cmdInputChainList.add("+0");
    }
    String fasta = proc.getGenomicCoordsHistory().current().getFastaFile();
    SAMSequenceDictionary samSeqDict = proc.getGenomicCoordsHistory().current().getSamSeqDict();
    // Messages that may be sent from the various methods.
    String messages = "";
    for (String cmdString : cmdInputChainList) {
        List<String> cmdTokens = Utils.tokenize(cmdString, " ");
        // If something goes wrong this will change
        this.interactiveInputExitCode = ExitCode.CLEAN;
        try {
            // * These commands only print info or do stuff without editing the GenomicCoordinates or the Tracks:
            if (cmdTokens.get(0).equals("h") || cmdTokens.get(0).equals("-h")) {
                System.err.println(Utils.padEndMultiLine(CommandList.briefHelp(), proc.getWindowSize()));
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.size() >= 2 && cmdTokens.get(1).equals("-h")) {
                // Help on this command
                String help = Utils.padEndMultiLine("\n" + CommandList.getHelpForCommand(cmdTokens.get(0)), proc.getWindowSize());
                System.err.println(help);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("posHistory")) {
                this.posHistory(cmdTokens, proc.getGenomicCoordsHistory().getCurrentSessionHistory(), proc.getWindowSize());
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("history")) {
                String hist = Utils.padEndMultiLine(this.cmdHistoryToString(cmdTokens), proc.getWindowSize());
                System.err.println(hist);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("show")) {
                this.interactiveInputExitCode = this.show(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("explainSamFlag")) {
                this.interactiveInputExitCode = this.explainSamFlag(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("sys")) {
                this.execSysCmd(cmdString, proc.getWindowSize());
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("recentlyOpened")) {
                String opened = Utils.padEndMultiLine(proc.getTrackSet().showRecentlyOpened(cmdTokens), proc.getWindowSize());
                System.out.println(opened);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("setConfig")) {
                try {
                    this.setConfigOpt(cmdTokens);
                    this.interactiveInputExitCode = ExitCode.CLEAN;
                } catch (Exception e) {
                    System.err.println(Utils.padEndMultiLine("Unable to set configuration", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    if (debug > 0) {
                        e.printStackTrace();
                    }
                }
            } else if (cmdTokens.get(0).equals("save")) {
                List<String> args = new ArrayList<String>(cmdTokens);
                proc.setStripAnsi(!Utils.argListContainsFlag(args, "-color"));
                // Default: do not append
                proc.setAppendToSnapshotFile(false);
                if (args.contains(">>")) {
                    proc.setAppendToSnapshotFile(true);
                    args.remove(">>");
                } else if (args.contains(">")) {
                    proc.setAppendToSnapshotFile(false);
                    args.remove(">");
                }
                proc.setSnapshotFile(Utils.parseCmdinputToGetSnapshotFile(Joiner.on(" ").join(args), proc.getGenomicCoordsHistory().current()));
            } else if (cmdTokens.get(0).equals("q")) {
                System.out.print("\033[0m");
                console.clearScreen();
                console.flush();
                System.exit(0);
            // * These commands change the GenomicCoordinates (navigate) but do not touch the tracks.
            } else if (cmdTokens.get(0).equals("f") || cmdTokens.get(0).equals("b") || cmdTokens.get(0).equals("ff") || cmdTokens.get(0).equals("bb") || cmdTokens.get(0).matches("^\\-\\d+.*") || cmdTokens.get(0).matches("^\\+\\d+.*")) {
                // No cmd line args either f/b ops or ints
                String newRegion = Utils.parseConsoleInput(cmdTokens, proc.getGenomicCoordsHistory().current()).trim();
                proc.getGenomicCoordsHistory().add(new GenomicCoords(newRegion, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).matches("^\\d+.*") || cmdTokens.get(0).matches("^\\.\\d+.*")) {
                String newRegion;
                try {
                    newRegion = this.gotoOnCurrentChrom(cmdTokens, proc.getGenomicCoordsHistory().current());
                } catch (IndexOutOfBoundsException e) {
                    System.err.append("Column coordinates must be >= 1 and <= the screen width");
                    throw new InvalidCommandLineException();
                }
                proc.getGenomicCoordsHistory().add(new GenomicCoords(newRegion, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).equals("goto") || cmdTokens.get(0).startsWith(":")) {
                String reg = Joiner.on(" ").join(cmdTokens).replaceFirst("goto|:", "").trim();
                proc.getGenomicCoordsHistory().add(new GenomicCoords(reg, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).equals("p")) {
                proc.getGenomicCoordsHistory().previous();
            } else if (cmdTokens.get(0).equals("n")) {
                proc.getGenomicCoordsHistory().next();
            } else if (cmdTokens.get(0).equals("zo")) {
                int nz = Utils.parseZoom(Joiner.on(" ").join(cmdTokens), 1);
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                for (int i = 0; i < nz; i++) {
                    gc.zoomOut();
                }
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("zi")) {
                int nz = Utils.parseZoom(Joiner.on(" ").join(cmdTokens), 1);
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                for (int i = 0; i < nz; i++) {
                    gc.zoomIn();
                }
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("extend")) {
                if (cmdTokens.size() == 1) {
                    System.err.println(Utils.padEndMultiLine("Expected at least one argument.", proc.getWindowSize()));
                }
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.cmdInputExtend(cmdTokens);
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("trim")) {
                GenomicCoords gc = proc.getTrackSet().trimCoordsForTrack(cmdTokens);
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("l")) {
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.left();
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("r")) {
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.right();
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("setGenome")) {
                this.setGenome(cmdTokens, proc);
            // * These commands change the Tracks but do not touch the GenomicCoordinates.
            } else if (cmdTokens.get(0).equals("dataCol")) {
                try {
                    proc.getTrackSet().setDataColForRegex(cmdTokens);
                } catch (Exception e) {
                    String msg = Utils.padEndMultiLine("Error processing " + cmdTokens + ". Perhaps a non-numeric column was selected?", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
            } else if (cmdTokens.get(0).equals("ylim")) {
                proc.getTrackSet().setTrackYlimitsForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("trackHeight")) {
                proc.getTrackSet().setTrackHeightForRegex(cmdTokens);
            } else if ((cmdTokens.get(0).equals("colorTrack") || cmdTokens.get(0).equals("colourTrack"))) {
                proc.getTrackSet().setTrackColourForRegex(cmdTokens);
            } else if ((cmdTokens.get(0).equals("featureColorForRegex"))) {
                proc.getTrackSet().setFeatureColorForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("hideTitle")) {
                proc.getTrackSet().setHideTitleForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.BSseq.getCmdDescr())) {
                if (proc.getGenomicCoordsHistory().current().getFastaFile() == null) {
                    String msg = Utils.padEndMultiLine("Cannot set BSseq mode without reference sequence", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                proc.getTrackSet().setBisulfiteModeForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("squash") || cmdTokens.get(0).equals(Command.featureDisplayMode.toString())) {
                proc.getTrackSet().setFeatureDisplayModeForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("gap")) {
                proc.getTrackSet().setFeatureGapForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("readsAsPairs")) {
                proc.getTrackSet().setReadsAsPairsForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("gffNameAttr")) {
                proc.getTrackSet().setAttributeForGFFName(cmdTokens);
            } else if (cmdTokens.get(0).equals("open") || cmdTokens.get(0).equals("addTracks")) {
                cmdTokens.remove(0);
                List<String> globbed = Utils.globFiles(cmdTokens);
                if (globbed.size() == 0) {
                    globbed = this.openFilesFromIndexes(proc.getTrackSet().getOpenedFiles(), cmdTokens);
                }
                if (globbed.size() == 0) {
                    String msg = Utils.padEndMultiLine(cmdTokens + ": No file found.", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                } else {
                    for (String sourceName : globbed) {
                        String msg = Utils.padEndMultiLine("Adding: " + sourceName, proc.getWindowSize());
                        System.err.println(msg);
                        try {
                            proc.getTrackSet().addTrackFromSource(sourceName, proc.getGenomicCoordsHistory().current(), null);
                        } catch (Exception e) {
                            try {
                                // It may be that you are in position that doesn't exist in the sequence dictionary that
                                // came with this new file. To recover, find an existing position, move there and try to reload the
                                // file. This fixes issue#23
                                String region = Main.initRegion(globbed, null, null, debug);
                                proc.getGenomicCoordsHistory().add(new GenomicCoords(region, terminalWidth, samSeqDict, fasta));
                                proc.getTrackSet().addTrackFromSource(sourceName, proc.getGenomicCoordsHistory().current(), null);
                            } catch (Exception x) {
                                x.printStackTrace();
                                msg = Utils.padEndMultiLine("Failed to add: " + sourceName, proc.getWindowSize());
                                System.err.println(msg);
                            }
                        }
                        if (proc.getGenomicCoordsHistory().current().getSamSeqDict() == null || proc.getGenomicCoordsHistory().current().getSamSeqDict().size() == 0) {
                            GenomicCoords testSeqDict = new GenomicCoords("default", Utils.getTerminalWidth(), null, null);
                            List<String> candidateSourceGenome = new ArrayList<String>();
                            candidateSourceGenome.add(sourceName);
                            testSeqDict.setGenome(candidateSourceGenome, false);
                            if (testSeqDict.getSamSeqDict() != null) {
                                candidateSourceGenome.add(0, "cmd");
                                proc.getGenomicCoordsHistory().setGenome(candidateSourceGenome);
                            }
                        }
                    }
                }
            } else if (cmdTokens.get(0).equals("reload")) {
                proc.getTrackSet().reload(cmdTokens);
            } else if (cmdTokens.get(0).equals("dropTracks")) {
                if (cmdTokens.size() <= 1) {
                    System.err.println(Utils.padEndMultiLine("List one or more tracks to drop or `dropTracks -h` for help.", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                messages += proc.getTrackSet().dropTracksWithRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("orderTracks")) {
                cmdTokens.remove(0);
                proc.getTrackSet().orderTracks(cmdTokens);
            } else if (cmdTokens.get(0).equals("editNames")) {
                messages += proc.getTrackSet().editNamesForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.print.toString())) {
                proc.getTrackSet().setPrintModeAndPrintFeaturesForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("grep")) {
                proc.getTrackSet().setFilterForTrackIntervalFeature(cmdTokens);
            } else if (cmdTokens.get(0).equals("awk")) {
                proc.getTrackSet().setAwkForTrack(cmdTokens);
            } else if (cmdTokens.get(0).equals("filterVariantReads")) {
                proc.getTrackSet().setFilterVariantReads(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.rpm.getCmdDescr())) {
                proc.getTrackSet().setRpmForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("samtools")) {
                proc.getTrackSet().setSamFilterForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("genotype")) {
                proc.getTrackSet().setGenotypeMatrix(cmdTokens);
            // * These commands change both the Tracks and the GenomicCoordinates
            } else if (cmdTokens.get(0).equals("next")) {
                this.next(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("find")) {
                boolean all = Utils.argListContainsFlag(cmdTokens, "-all");
                boolean fixedPattern = Utils.argListContainsFlag(cmdTokens, "-F");
                boolean caseIns = Utils.argListContainsFlag(cmdTokens, "-c");
                if (cmdTokens.size() < 2) {
                    System.err.println(Utils.padEndMultiLine("Error in find command. Expected at least 1 argument got: " + cmdTokens, proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                if (cmdTokens.size() == 2) {
                    // If track arg is missing use this placeholder.
                    cmdTokens.add("");
                }
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                int flag = 0;
                if (fixedPattern) {
                    flag |= Pattern.LITERAL;
                }
                if (!caseIns) {
                    flag |= Pattern.CASE_INSENSITIVE;
                }
                Pattern pattern;
                try {
                    pattern = Pattern.compile(cmdTokens.get(1), flag);
                } catch (PatternSyntaxException e) {
                    System.err.println("Invalid regex");
                    throw new InvalidCommandLineException();
                }
                GenomicCoords nextGc = proc.getTrackSet().findNextMatchOnTrack(pattern, cmdTokens.get(2), gc, all);
                if (nextGc.equalCoords(gc)) {
                    System.err.println("No match found outside of this window for query '" + cmdTokens.get(1) + "'");
                    this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
                } else {
                    proc.getGenomicCoordsHistory().add(nextGc);
                }
            } else if (cmdTokens.get(0).equals("seqRegex")) {
                try {
                    proc.getTrackSet().setRegexForTrackSeqRegex(cmdTokens, proc.getGenomicCoordsHistory().current());
                } catch (InvalidCommandLineException e) {
                    System.err.println(Utils.padEndMultiLine("Cannot find regex in sequence without fasta reference!", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
            } else if (cmdTokens.get(0).equals("bookmark")) {
                messages += proc.getTrackSet().bookmark(proc.getGenomicCoordsHistory().current(), cmdTokens);
            } else {
                System.err.println(Utils.padEndMultiLine("Unrecognized command: " + cmdTokens.get(0), proc.getWindowSize()));
                String suggestions = Joiner.on(" or ").join(Utils.suggestCommand(cmdTokens.get(0).trim(), CommandList.cmds()));
                if (!suggestions.isEmpty()) {
                    System.err.println(Utils.padEndMultiLine("Maybe you mean " + suggestions + "?", proc.getWindowSize()));
                }
                this.interactiveInputExitCode = ExitCode.ERROR;
            // throw new InvalidCommandLineException();
            }
        } catch (ArgumentParserException e) {
            this.interactiveInputExitCode = ExitCode.ERROR;
        } catch (Exception e) {
            // You shouldn't catch anything! Be more specific.
            System.err.println(Utils.padEndMultiLine("\nError processing input: " + cmdTokens, proc.getWindowSize()));
            System.err.println(Utils.padEndMultiLine("For help on command \"cmd\" execute 'cmd -h' or '-h' for list of commands.\n", proc.getWindowSize()));
            this.interactiveInputExitCode = ExitCode.ERROR;
            if (debug == 1) {
                e.printStackTrace();
            } else if (debug == 2) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        if (this.interactiveInputExitCode.equals(ExitCode.CLEAN) || this.interactiveInputExitCode.equals(ExitCode.CLEAN_NO_FLUSH)) {
            // Command has been parsed ok. Let's see if we can execute it without exceptions.
            try {
                if (this.interactiveInputExitCode.equals(ExitCode.CLEAN)) {
                    console.clearScreen();
                    console.flush();
                    proc.iterateTracks();
                } else {
                // 
                }
            } catch (InvalidGenomicCoordsException e) {
                String region = Main.initRegion(proc.getTrackSet().getFilenameList(), null, null, debug);
                proc.getGenomicCoordsHistory().add(new GenomicCoords(region, terminalWidth, samSeqDict, fasta));
                System.err.println(Utils.padEndMultiLine("Invalid genomic coordinates found. Resetting to " + region, proc.getWindowSize()));
                if (debug > 0) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                System.err.println(Utils.padEndMultiLine("Error processing tracks with input " + cmdTokens, proc.getWindowSize()));
                this.interactiveInputExitCode = ExitCode.ERROR;
                if (debug > 0) {
                    e.printStackTrace();
                }
            }
        }
        if (this.interactiveInputExitCode.equals(ExitCode.ERROR)) {
            // Unless we are in non-interactive mode
            if (nonInteractive) {
                System.exit(1);
            }
            break;
        }
    }
    // END OF LOOP THROUGH CHAIN OF INPUT COMMANDS
    if (!messages.isEmpty()) {
        System.err.println(Utils.padEndMultiLine(messages.trim(), proc.getWindowSize()));
    }
    messages = "";
    return proc;
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidColourException(exceptions.InvalidColourException) InvalidRecordException(exceptions.InvalidRecordException) SQLException(java.sql.SQLException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) InvalidConfigException(exceptions.InvalidConfigException) PatternSyntaxException(java.util.regex.PatternSyntaxException) IOException(java.io.IOException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) ArrayList(java.util.ArrayList) CommandList(commandHelp.CommandList) List(java.util.List) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

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