List of usage examples for java.lang Exception getMessage
public String getMessage()
From source file:edu.mit.lib.mama.Mama.java
public static void main(String[] args) { Properties props = findConfig(args); DBI dbi = new DBI(props.getProperty("dburl"), props); // Advanced instrumentation/metrics if requested if (System.getenv("MAMA_DB_METRICS") != null) { dbi.setTimingCollector(new InstrumentedTimingCollector(metrics)); }/*from ww w .j a v a2 s .c om*/ // reassign default port 4567 if (System.getenv("MAMA_SVC_PORT") != null) { port(Integer.valueOf(System.getenv("MAMA_SVC_PORT"))); } // if API key given, use exception monitoring service if (System.getenv("HONEYBADGER_API_KEY") != null) { reporter = new HoneybadgerReporter(); } get("/ping", (req, res) -> { res.type("text/plain"); res.header("Cache-Control", "must-revalidate,no-cache,no-store"); return "pong"; }); get("/metrics", (req, res) -> { res.type("application/json"); res.header("Cache-Control", "must-revalidate,no-cache,no-store"); ObjectMapper objectMapper = new ObjectMapper() .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true)); try (ServletOutputStream outputStream = res.raw().getOutputStream()) { objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics); } return ""; }); get("/shutdown", (req, res) -> { boolean auth = false; try { if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key")) && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) { auth = true; return "Shutting down"; } else { res.status(401); return "Not authorized"; } } finally { if (auth) { stop(); } } }); get("/item", (req, res) -> { if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) { halt(400, "Must supply field and value query parameters 'qf' and 'qv'"); } itemReqs.mark(); Timer.Context context = respTime.time(); try (Handle hdl = dbi.open()) { if (findFieldId(hdl, req.queryParams("qf")) != -1) { List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"), req.queryParamsValues("rf")); if (results.size() > 0) { res.type("application/json"); return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n" + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items", results.stream().collect(Collectors.joining(",", "[", "]")), false) + "\n" + " }"; } else { res.status(404); return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv"); } } else { res.status(404); return "No such field: " + req.queryParams("qf"); } } catch (Exception e) { if (null != reporter) reporter.reportError(e); res.status(500); return "Internal system error: " + e.getMessage(); } finally { context.stop(); } }); awaitInitialization(); }
From source file:com.ms.commons.test.tool.ExportDatabaseData.java
public static void main(String[] args) { printWelcomeMessage();/* w w w . j a v a2 s . c o m*/ try { List<DatabaseConfigItem> confItems = DatabasePropertiesLoader.getDatabaseConfigItems(); DatabaseConfigItem item = selectDatabaseConfigItem(confItems); if (item != null) { JdbcTemplate jdbcTemplate = getJdbcTemplate(item); if (jdbcTemplate != null) { doRun(jdbcTemplate); } } } catch (Exception e) { if (e instanceof MessageException) { System.out.println(e.getMessage()); } else { System.out.println("Unknow error: " + e.getMessage()); } } System.out.println("Ended!"); }
From source file:amulet.appbuilder.AppBuilder.java
public static void main(String[] args) { try {/*w w w . j a va 2s .c o m*/ if (args.length != 1) { System.out.println("ERROR: Provide filename that needs to be translated"); return; } String inputFile = args[0]; if (inputFile.length() < 1) { System.out.println("ERROR: Provide filename that needs to be translated"); return; } ResourceProfiler resourceProfiler = new ResourceProfiler(); resourceProfiler.add(inputFile); new AppBuilder(inputFile, true, true, resourceProfiler); } catch (Exception exp) { System.err.println("Unexpected exception:" + exp.getMessage()); exp.printStackTrace(); return; } }
From source file:importer.filters.CceFilter.java
public static void main(String[] args) { String input = readFile(args[0]); Archive cortex = new Archive("Nostromo", "Joseph Conrad", "TEI/default", "UTF-8"); Archive corcode = new Archive("Nostromo", "Joseph Conrad", "TEI/default", "UTF-8"); try {/*w w w .j a v a2 s. com*/ String log = new CceFilter().convert(input, "A1", cortex, corcode); System.out.println(log); writeFile(new String(cortex.get("A1")), "cortex.txt"); writeFile(new String(corcode.get("A1")), "corcode.txt"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:co.cask.cdap.cli.CLIMain.java
public static void main(String[] args) { final PrintStream output = System.out; Options options = getOptions();//from www .j ava2 s. c om CLIMainArgs cliMainArgs = CLIMainArgs.parse(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine command = parser.parse(options, cliMainArgs.getOptionTokens()); if (command.hasOption(HELP_OPTION.getOpt())) { usage(); System.exit(0); } LaunchOptions launchOptions = LaunchOptions.builder() .setUri(command.getOptionValue(URI_OPTION.getOpt(), getDefaultURI().toString())) .setDebug(command.hasOption(DEBUG_OPTION.getOpt())) .setVerifySSL(parseBooleanOption(command, VERIFY_SSL_OPTION, DEFAULT_VERIFY_SSL)) .setAutoconnect(parseBooleanOption(command, AUTOCONNECT_OPTION, DEFAULT_AUTOCONNECT)).build(); String scriptFile = command.getOptionValue(SCRIPT_OPTION.getOpt(), ""); boolean hasScriptFile = command.hasOption(SCRIPT_OPTION.getOpt()); String[] commandArgs = cliMainArgs.getCommandTokens(); try { ClientConfig clientConfig = ClientConfig.builder().setConnectionConfig(null).build(); final CLIConfig cliConfig = new CLIConfig(clientConfig, output, new AltStyleTableRenderer()); CLIMain cliMain = new CLIMain(launchOptions, cliConfig); CLI cli = cliMain.getCLI(); cliMain.tryAutoconnect(); CLIConnectionConfig connectionConfig = new CLIConnectionConfig( cliConfig.getClientConfig().getConnectionConfig(), Id.Namespace.DEFAULT, null); cliMain.updateCLIPrompt(connectionConfig); if (hasScriptFile) { File script = cliMain.getFilePathResolver().resolvePathToFile(scriptFile); if (!script.exists()) { output.println("ERROR: Script file '" + script.getAbsolutePath() + "' does not exist"); System.exit(1); } List<String> scriptLines = Files.readLines(script, Charsets.UTF_8); for (String scriptLine : scriptLines) { output.print(cliMain.getPrompt(connectionConfig)); output.println(scriptLine); cli.execute(scriptLine, output); output.println(); } } else if (commandArgs.length == 0) { cli.startInteractiveMode(output); } else { cli.execute(Joiner.on(" ").join(commandArgs), output); } } catch (Exception e) { e.printStackTrace(output); } } catch (ParseException e) { output.println(e.getMessage()); usage(); } }
From source file:com.aestel.chemistry.openEye.fp.Fingerprinter.java
public static void main(String... args) throws IOException { long start = System.currentTimeMillis(); long iCounter = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);//from w ww . j a va 2 s . c o m options.addOption(opt); opt = new Option("out", true, "output file .tsv or oe-supported"); opt.setRequired(true); options.addOption(opt); opt = new Option("idTag", true, "field with ID (default title)"); opt.setRequired(false); options.addOption(opt); opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4|HashLinear7*4\n" + " maccs: generate maccs keys\n" + " linear7 generate 7 bonds long linear fingerprints (210k known rest hashed)\n" + " linear7*4 linear 7 bonds if more than 4 atoms code atoms as * (5.1k known rest hashed)\n" + " HashLinear7*4: as linear7*4 but hashed to 16k"); opt.setRequired(true); options.addOption(opt); opt = new Option("format", true, "folded512|folded2048|bitList|fragList|none\n" + " folded512/2048: hex encoded 512/2048 bits\n" + " bitList: list of bitpositions\n" + " none: no fp output for use with writeCodeMap"); opt.setRequired(true); options.addOption(opt); opt = new Option("writeCodeMap", false, "Overwrite the codeMap file at the end of processing"); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String idTag = null; if (cmd.hasOption("idTag")) idTag = cmd.getOptionValue("idTag"); String outformat = cmd.getOptionValue("format").toLowerCase().intern(); if (args.length != 0) { exitWithHelp(options); } String type = cmd.getOptionValue("fpType"); boolean updateDictionaryFile = cmd.hasOption("writeCodeMap"); boolean hashUnknownFrag = true; if (type.equals("HashLinear7*4")) hashUnknownFrag = false; if (type.equals("maccs")) hashUnknownFrag = false; if (updateDictionaryFile) hashUnknownFrag = false; Fingerprinter fprinter = createFingerprinter(type, updateDictionaryFile, hashUnknownFrag); OEMolBase mol = new OEGraphMol(); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); oemolistream ifs = new oemolistream(inFile); Runtime rt = Runtime.getRuntime(); Outputter out; if (outFile.endsWith(".txt") || outFile.endsWith(".tab")) out = new TabOutputter(fprinter.getMapper(), outFile, outformat); else out = new OEOutputter(fprinter.getMapper(), outFile, type, outformat); while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; Fingerprint fp = fprinter.getFingerprint(mol); String id; if (idTag == null) id = mol.GetTitle(); else id = oechem.OEGetSDData(mol, idTag); if (iCounter % 100 == 0) System.err.print("."); if (iCounter % 4000 == 0) { System.err.printf(" %d %dsec\tt=%d f=%d u=%d m=%d tf=%d\n", iCounter, (System.currentTimeMillis() - start) / 1000, rt.totalMemory() / 1024, rt.freeMemory() / 1024, (rt.totalMemory() - rt.freeMemory()) / 1024, rt.maxMemory() / 1024, (rt.freeMemory() + (rt.maxMemory() - rt.totalMemory())) / 1024); } out.output(id, mol, fp); } System.err.printf("Fingerprinter: Read %d structures in %d sec\n", iCounter, (System.currentTimeMillis() - start) / 1000); if (updateDictionaryFile) fprinter.writeDictionary(); out.close(); fprinter.close(); }
From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java
public static void main(String[] args) throws Exception { log.debug("starting"); // uses pin 6 for the red Led final Led redLed = new Led(6); // uses pin 26 for the green Led final Led greenLed = new Led(26); // turns the red led on initially redLed.on();//from w ww . j a va 2s . com // turns the green led off initially greenLed.off(); // loads properties from danbo.properties file - make sure this file is // available on the pi's home directory InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties"); Properties properties = new Properties(); properties.load(input); endpoint = properties.getProperty("awsiot.endpoint"); rootCA = properties.getProperty("awsiot.rootCA"); privateKey = properties.getProperty("awsiot.privateKey"); certificate = properties.getProperty("awsiot.certificate"); url = protocol + endpoint + ":" + port; log.debug("properties loaded"); // turns off both eyes RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0), new Color(0, 0, 0), 0, 100); new Thread(rgbLed).start(); // resets servo to initial positon Servo servo = new Servo("Servo", 1); new Thread(servo).start(); // gets the Pi serial number and uses it as part of the thing // registration name clientId = clientId + getSerialNumber(); // AWS IoT things shadow topics updateTopic = "$aws/things/" + clientId + "/shadow/update"; deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta"; rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected"; // AWS IoT controller things shadow topic (used to register new things) controllerUpdateTopic = "$aws/things/Controller/shadow/update"; // defines an empty danbo shadow POJO final DanboShadow danboShadow = new DanboShadow(); DanboShadow.State state = danboShadow.new State(); final DanboShadow.State.Reported reported = state.new Reported(); reported.setEyes("readyToBlink"); reported.setHead("readyToMove"); reported.setMouth("readyToSing"); reported.setName(clientId); state.setReported(reported); danboShadow.setState(state); // defines an empty controller shadow POJO final ControllerShadow controllerShadow = new ControllerShadow(); ControllerShadow.State controllerState = controllerShadow.new State(); final ControllerShadow.State.Reported controllerReported = controllerState.new Reported(); controllerReported.setThingName(clientId); controllerState.setReported(controllerReported); controllerShadow.setState(controllerState); try { log.debug("registering"); // registers the thing (creates a new thing) by updating the // controller String message = gson.toJson(controllerShadow); MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url, clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate); new Thread(controllerUpdatePublisher).start(); log.debug("registered"); // clears the thing status (in case the thing already existed) Danbo.deleteStatus("initialDelete"); // creates an MQTT subscriber to the things shadow delta topic // (command execution notification) MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos, url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate); new Thread(deltaSubscriber).start(); // creates an MQTT subscriber to the things shadow error topic MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic, qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate); new Thread(errorSubscriber).start(); // turns the red LED off redLed.off(); ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() { @Override public void run() { // turns the green LED on greenLed.on(); log.debug("running publish state thread"); int temp = -300; int humid = -300; reported.setTemperature(new Integer(temp).toString()); reported.setHumidity(new Integer(humid).toString()); try { // reads the temperature and humidity data Set<Sensor> sensors = Sensors.getSensors(); log.debug(sensors.size()); for (Sensor sensor : sensors) { log.debug(sensor.getPhysicalQuantity()); log.debug(sensor.getValue()); if (sensor.getPhysicalQuantity().toString().equals("Temperature")) { temp = sensor.getValue().intValue(); } if (sensor.getPhysicalQuantity().toString().equals("Humidity")) { humid = sensor.getValue().intValue(); } } log.debug("temperature: " + temp); log.debug("humidity: " + humid); reported.setTemperature(new Integer(temp).toString()); reported.setHumidity(new Integer(humid).toString()); } catch (Exception e) { log.error("an error has ocurred: " + e.getMessage()); e.printStackTrace(); } try { // reports current state - last temperature and humidity // read String message = gson.toJson(danboShadow); MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url, clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate); new Thread(updatePublisher).start(); } catch (Exception e) { log.error("an error has ocurred: " + e.getMessage()); e.printStackTrace(); } // turns the green LED off greenLed.off(); } }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds, // with an initial delay of 5 seconds } catch (MqttException me) { // Display full details of any exception that occurs log.error("reason " + me.getReasonCode()); log.error("msg " + me.getMessage()); log.error("loc " + me.getLocalizedMessage()); log.error("cause " + me.getCause()); log.error("excep " + me); me.printStackTrace(); } catch (Throwable th) { log.error("msg " + th.getMessage()); log.error("loc " + th.getLocalizedMessage()); log.error("cause " + th.getCause()); log.error("excep " + th); th.printStackTrace(); } }
From source file:com.github.s4ke.moar.cli.Main.java
public static void main(String[] args) throws ParseException, IOException { // create Options object Options options = new Options(); options.addOption("rf", true, "file containing the regexes to test against (multiple regexes are separated by one empty line)"); options.addOption("r", true, "regex to test against"); options.addOption("mf", true, "file/folder to read the MOA from"); options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)"); options.addOption("sf", true, "file to read the input string(s) from"); options.addOption("s", true, "string to test the MOA/Regex against"); options.addOption("m", false, "multiline matching mode (search in string for regex)"); options.addOption("ls", false, "treat every line of the input string file as one string"); options.addOption("t", false, "trim lines if -ls is set"); options.addOption("d", false, "only do determinism check"); options.addOption("help", false, "prints this dialog"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("moar-cli", options); return;/* ww w . j a v a2 s.c o m*/ } List<String> patternNames = new ArrayList<>(); List<MoaPattern> patterns = new ArrayList<>(); List<String> stringsToCheck = new ArrayList<>(); if (cmd.hasOption("r")) { String regexStr = cmd.getOptionValue("r"); try { patterns.add(MoaPattern.compile(regexStr)); patternNames.add(regexStr); } catch (Exception e) { System.out.println(e.getMessage()); } } if (cmd.hasOption("rf")) { String fileName = cmd.getOptionValue("rf"); List<String> regexFileContents = readFileContents(new File(fileName)); int emptyLineCountAfterRegex = 0; StringBuilder regexStr = new StringBuilder(); for (String line : regexFileContents) { if (emptyLineCountAfterRegex >= 1) { if (regexStr.length() > 0) { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } regexStr.setLength(0); emptyLineCountAfterRegex = 0; } if (line.trim().equals("")) { if (regexStr.length() > 0) { ++emptyLineCountAfterRegex; } } else { regexStr.append(line); } } if (regexStr.length() > 0) { try { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } catch (Exception e) { System.out.println(e.getMessage()); return; } regexStr.setLength(0); } } if (cmd.hasOption("mf")) { String fileName = cmd.getOptionValue("mf"); File file = new File(fileName); if (file.isDirectory()) { System.out.println(fileName + " is a directory, using all *.moar files as patterns"); File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar")); for (File moar : moarFiles) { String jsonString = readWholeFile(moar); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(moar.getAbsolutePath()); } } else { System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)"); String jsonString = readWholeFile(file); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(fileName); } } if (cmd.hasOption("s")) { String str = cmd.getOptionValue("s"); stringsToCheck.add(str); } if (cmd.hasOption("sf")) { boolean treatLineAsString = cmd.hasOption("ls"); boolean trim = cmd.hasOption("t"); String fileName = cmd.getOptionValue("sf"); StringBuilder stringBuilder = new StringBuilder(); boolean firstLine = true; for (String str : readFileContents(new File(fileName))) { if (treatLineAsString) { if (trim) { str = str.trim(); if (str.length() == 0) { continue; } } stringsToCheck.add(str); } else { if (!firstLine) { stringBuilder.append("\n"); } if (firstLine) { firstLine = false; } stringBuilder.append(str); } } if (!treatLineAsString) { stringsToCheck.add(stringBuilder.toString()); } } if (cmd.hasOption("d")) { //at this point we have already built the Patterns //so just give the user a short note. System.out.println("All Regexes seem to be deterministic."); return; } if (patterns.size() == 0) { System.out.println("no patterns to check"); return; } if (cmd.hasOption("mo")) { String folder = cmd.getOptionValue("mo"); File folderFile = new File(folder); if (!folderFile.exists()) { System.out.println(folder + " does not exist. creating..."); if (!folderFile.mkdirs()) { System.out.println("folder " + folder + " could not be created"); } } int cnt = 0; for (MoaPattern pattern : patterns) { String patternAsJSON = MoarJSONSerializer.toJSON(pattern); try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) { writer.write(patternAsJSON); } } System.out.println("stored " + cnt + " patterns in " + folder); } if (stringsToCheck.size() == 0) { System.out.println("no strings to check"); return; } boolean multiline = cmd.hasOption("m"); for (String string : stringsToCheck) { int curPattern = 0; for (MoaPattern pattern : patterns) { MoaMatcher matcher = pattern.matcher(string); if (!multiline) { if (matcher.matches()) { System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\""); } else { System.out.println( "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\""); } } else { StringBuilder buffer = new StringBuilder(string); int additionalCharsPerMatch = ("<match>" + "</match>").length(); int matchCount = 0; while (matcher.nextMatch()) { buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch, matcher.getEnd() + matchCount * additionalCharsPerMatch, "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>"); ++matchCount; } System.out.println(buffer.toString()); } } ++curPattern; } }
From source file:eionet.rod.countrysrv.Extractor.java
/** * Called when script is run from the command-line. Takes one optional argument. The mode, which can be 0-3. Assumes 0 if not * provided./* w w w . j a v a 2s. c o m*/ * * @param args * command-line arguments */ public static void main(String[] args) { try { String mode = null; String userName = SYSTEM_USER; if (args.length == 1) { mode = args[0]; } else if (args.length > 1) { //this is feedback to the user not debugging as this class is executed in the cmd line //also log to file for other applications System.out.println("Usage: Extractor [mode]"); LOGGER.error("Usage: Extractor [mode]"); return; } else { mode = String.valueOf(ALL_DATA); } /* if (extractor == null) { extractor = new Extractor(); } extractor.harvest(Integer.parseInt(mode), userName); */ execute(Integer.parseInt(mode), userName); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
From source file:cli.Main.java
public static void main(String[] args) { // Workaround for BKS truststore Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); Namespace ns = parseArgs(args); if (ns == null) { System.exit(1);/*from w w w. j ava 2 s .c o m*/ } final String username = ns.getString("username"); final Manager m = new Manager(username); if (m.userExists()) { try { m.load(); } catch (Exception e) { System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage()); System.exit(2); } } switch (ns.getString("command")) { case "register": if (!m.userHasKeys()) { m.createNewIdentity(); } try { m.register(ns.getBoolean("voice")); } catch (IOException e) { System.err.println("Request verify error: " + e.getMessage()); System.exit(3); } break; case "verify": if (!m.userHasKeys()) { System.err.println("User has no keys, first call register."); System.exit(1); } if (m.isRegistered()) { System.err.println("User registration is already verified"); System.exit(1); } try { m.verifyAccount(ns.getString("verificationCode")); } catch (IOException e) { System.err.println("Verify error: " + e.getMessage()); System.exit(3); } break; case "send": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } String messageText = ns.getString("message"); if (messageText == null) { try { messageText = IOUtils.toString(System.in); } catch (IOException e) { System.err.println("Failed to read message from stdin: " + e.getMessage()); System.exit(1); } } final List<String> attachments = ns.getList("attachment"); List<TextSecureAttachment> textSecureAttachments = null; if (attachments != null) { textSecureAttachments = new ArrayList<>(attachments.size()); for (String attachment : attachments) { try { File attachmentFile = new File(attachment); InputStream attachmentStream = new FileInputStream(attachmentFile); final long attachmentSize = attachmentFile.length(); String mime = Files.probeContentType(Paths.get(attachment)); textSecureAttachments .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null)); } catch (IOException e) { System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } } List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size()); for (String recipient : ns.<String>getList("recipient")) { try { recipients.add(m.getPushAddress(recipient)); } catch (InvalidNumberException e) { System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } sendMessage(m, messageText, textSecureAttachments, recipients); break; case "receive": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } try { m.receiveMessages(5, true, new ReceiveMessageHandler(m)); } catch (IOException e) { System.err.println("Error while receiving message: " + e.getMessage()); System.exit(3); } catch (AssertionError e) { System.err.println("Failed to receive message (Assertion): " + e.getMessage()); System.err.println(e.getStackTrace()); System.err.println( "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); System.exit(1); } break; } m.save(); System.exit(0); }