List of usage examples for java.lang IllegalArgumentException IllegalArgumentException
public IllegalArgumentException(Throwable cause)
From source file:marytts.tools.analysis.CopySynthesis.java
/** * @param args//from w ww . j a va2 s. c o m */ public static void main(String[] args) throws Exception { String wavFilename = null; String labFilename = null; String pitchFilename = null; String textFilename = null; String locale = System.getProperty("locale"); if (locale == null) { throw new IllegalArgumentException("No locale given (-Dlocale=...)"); } for (String arg : args) { if (arg.endsWith(".txt")) textFilename = arg; else if (arg.endsWith(".wav")) wavFilename = arg; else if (arg.endsWith(".ptc")) pitchFilename = arg; else if (arg.endsWith(".lab")) labFilename = arg; else throw new IllegalArgumentException("Don't know how to treat argument: " + arg); } // The intonation contour double[] contour = null; double frameShiftTime = -1; if (pitchFilename == null) { // need to create pitch contour from wav file if (wavFilename == null) { throw new IllegalArgumentException("Need either a pitch file or a wav file"); } AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename)); AudioDoubleDataSource audio = new AudioDoubleDataSource(ais); PitchFileHeader params = new PitchFileHeader(); params.fs = (int) ais.getFormat().getSampleRate(); F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params); tracker.pitchAnalyze(audio); frameShiftTime = tracker.getSkipSizeInSeconds(); contour = tracker.getF0Contour(); } else { // have a pitch file -- ignore any wav file PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename); if (f0rw.contour == null) { throw new NullPointerException("Cannot read f0 contour from " + pitchFilename); } contour = f0rw.contour; frameShiftTime = f0rw.header.skipSizeInSeconds; } assert contour != null; assert frameShiftTime > 0; // The ALLOPHONES data and labels if (labFilename == null) { throw new IllegalArgumentException("No label file given"); } if (textFilename == null) { throw new IllegalArgumentException("No text file given"); } MaryTranscriptionAligner aligner = new MaryTranscriptionAligner(); aligner.SetEnsureInitialBoundary(false); String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(), aligner.getEnsureInitialBoundary(), labFilename); MaryHttpClient mary = new MaryHttpClient(); String text = FileUtils.readFileToString(new File(textFilename), "ASCII"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(bais); aligner.alignXmlTranscriptions(doc, labels); assert doc != null; // durations double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData(); assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length; // Now add durations and f0 targets to document double prevEnd = 0; NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY); for (int i = 0; i < endTimes.length; i++) { Element e = (Element) ni.nextNode(); if (e == null) throw new IllegalStateException("More durations than elements -- this should not happen!"); double durInSeconds = endTimes[i] - prevEnd; int durInMillis = (int) (1000 * durInSeconds); if (e.getTagName().equals(MaryXML.PHONE)) { e.setAttribute("d", String.valueOf(durInMillis)); e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString()); // f0 targets at beginning, mid, and end of phone StringBuilder f0String = new StringBuilder(); double startF0 = getF0(contour, frameShiftTime, prevEnd); if (startF0 != 0 && !Double.isNaN(startF0)) { f0String.append("(0,").append((int) startF0).append(")"); } double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds); if (midF0 != 0 && !Double.isNaN(midF0)) { f0String.append("(50,").append((int) midF0).append(")"); } double endF0 = getF0(contour, frameShiftTime, endTimes[i]); if (endF0 != 0 && !Double.isNaN(endF0)) { f0String.append("(100,").append((int) endF0).append(")"); } if (f0String.length() > 0) { e.setAttribute("f0", f0String.toString()); } } else { // boundary e.setAttribute("duration", String.valueOf(durInMillis)); } prevEnd = endTimes[i]; } if (ni.nextNode() != null) { throw new IllegalStateException("More elements than durations -- this should not happen!"); } // TODO: add pitch values String acoustparams = DomUtils.document2String(doc); System.out.println("ACOUSTPARAMS:"); System.out.println(acoustparams); }
From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java
public static void main(final String[] args) throws Exception { if (args == null || args.length != 2) { throw new IllegalArgumentException("AmazonS3Fixture <working directory> <property file>"); }/*from w ww . ja va2s .c om*/ final Properties properties = new Properties(); try (InputStream is = Files.newInputStream(PathUtils.get(args[1]))) { properties.load(is); } final AmazonS3Fixture fixture = new AmazonS3Fixture(args[0], properties); fixture.listen(); }
From source file:com.twitter.heron.healthmgr.HealthManager.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); Options slaManagerCliOptions = constructCliOptions(); // parse the help options first. Options helpOptions = constructHelpOptions(); CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(slaManagerCliOptions);/*ww w.j a va2 s.c om*/ return; } try { cmd = parser.parse(slaManagerCliOptions, args); } catch (ParseException e) { usage(slaManagerCliOptions); throw new RuntimeException("Error parsing command line options: ", e); } HealthManagerMode mode = HealthManagerMode.cluster; if (hasOption(cmd, CliArgs.MODE)) { mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE)); } Config config; switch (mode) { case cluster: config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig()) .putAll(commandLineConfigs(cmd)).build()); break; case local: if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) { throw new IllegalArgumentException("Missing heron_home or config_path argument"); } String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME); String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH); config = Config.toLocalMode( Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null)) .putAll(commandLineConfigs(cmd)).build()); break; default: throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE)); } setupLogging(cmd, config); LOG.info("Static Heron config loaded successfully "); LOG.fine(config.toString()); // load the default config value and override with any command line values String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key()); metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName); String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key()); metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl); AbstractModule module = buildMetricsProviderModule(metricsUrl, metricSourceClassName); HealthManager healthManager = new HealthManager(config, module); LOG.info("Initializing health manager"); healthManager.initialize(); LOG.info("Starting Health Manager metirc posting thread"); HealthManagerMetrics publishingMetricsRunnable = null; if (hasOption(cmd, CliArgs.METRICSMGR_PORT)) { publishingMetricsRunnable = new HealthManagerMetrics( Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT))); } LOG.info("Starting Health Manager"); PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies); ScheduledFuture<?> future = policyExecutor.start(); if (publishingMetricsRunnable != null) { new Thread(publishingMetricsRunnable).start(); } try { future.get(); } finally { policyExecutor.destroy(); if (publishingMetricsRunnable != null) { publishingMetricsRunnable.close(); } } }
From source file:dk.alexandra.fresco.demo.PrivateSetDemo.java
/** * The main method sets up application specific command line parameters, * parses command line arguments. Based on the command line arguments it * configures the SCE, instantiates the PrivateSetDemo and runs the PrivateSetDemo on the * SCE.//from ww w .j a va 2 s .c om * */ public static void main(String[] args) { CmdLineUtil util = new CmdLineUtil(); SCEConfiguration sceConf = null; boolean[] key = null; int[] inputs = null; try { util.addOption(Option.builder("key") .desc("The key to use for encryption. " + "A " + INPUT_LENGTH + " char hex string. Required for player 1 and 2. " + "For both players this is interpreted as the AES key. ") .longOpt("key").hasArg().build()); util.addOption(Option.builder("in") .desc("The list of integers to use as input for the set intersection problem. " + "A comma separated list of integers. Required for player 1 and 2. " + "The lists must be of equal length for each player. ") .longOpt("input").hasArg().build()); CommandLine cmd = util.parse(args); sceConf = util.getSCEConfiguration(); // Get and validate the AES specific input. if (sceConf.getMyId() == 1 || sceConf.getMyId() == 2) { if (!cmd.hasOption("in") && !cmd.hasOption("key")) { throw new ParseException("Player 1 and 2 must submit inputs and keys"); } else { if (cmd.getOptionValue("key").length() != INPUT_LENGTH) { throw new IllegalArgumentException( "bad key hex string: must be hex string of length " + INPUT_LENGTH); } key = ByteArithmetic.toBoolean(cmd.getOptionValue("key")); for (Option o : cmd.getOptions()) { System.out.println("option: " + o.getValue()); } inputs = arrayFromString(cmd.getOptionValue("in")); } } else { if (cmd.hasOption("in")) throw new ParseException("Only player 1 and 2 should submit input"); } } catch (ParseException | IllegalArgumentException e) { System.out.println("Error: " + e); System.out.println(); util.displayHelp(); System.exit(-1); } // Do the secure computation using config from property files. PrivateSetDemo privateSetDemo = new PrivateSetDemo(sceConf.getMyId(), key, inputs); SCE sce = SCEFactory.getSCEFromConfiguration(sceConf); try { sce.runApplication(privateSetDemo); } catch (MPCException e) { System.out.println("Error while doing MPC: " + e.getMessage()); System.exit(-1); } // Print result. System.out.println("The resulting ciphertexts are:"); boolean[][] res = new boolean[privateSetDemo.result.length][BLOCK_SIZE]; for (int j = 0; j < privateSetDemo.result.length; j++) { for (int i = 0; i < BLOCK_SIZE; i++) { res[j][i] = privateSetDemo.result[j][i].getValue(); } System.out.println("result(" + j + "): " + ByteArithmetic.toHex(res[j])); } }
From source file:edu.msu.cme.rdp.seqmatch.cli.SeqMatchMain.java
public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("USAGE: SeqMatchMain [train|seqmatch] <args>"); return;//from ww w .ja va 2 s .c om } String cmd = args[0]; args = Arrays.copyOfRange(args, 1, args.length); if (cmd.equals("train")) { if (args.length != 2) { System.err.println("USAGE: train <reference sequences> <trainee_out_file_prefix>" + "\nMultiple trainee output files might be created, each containing maximum " + Trainee.MAX_NUM_SEQ + " sequences"); return; } File refSeqs = new File(args[0]); File traineeFileOut = new File(args[1]); //maybe more than 1 trainee files need to be created, depending on the number of seqs CreateMultiMatchFromFile.getMultiTrainee(refSeqs, traineeFileOut); } else if (cmd.equals("seqmatch")) { File refFile = null; File queryFile = null; HashMap<String, String> descMap = new HashMap<String, String>(); PrintStream out = new PrintStream(System.out); int knn = 20; float minSab = .5f; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("knn")) { knn = Integer.parseInt(line.getOptionValue("knn")); } if (line.hasOption("sab")) { minSab = Float.parseFloat(line.getOptionValue("sab")); } if (line.hasOption("desc")) { descMap = readDesc(new File(line.getOptionValue("desc"))); } if (line.hasOption("outFile")) { out = new PrintStream(new File(line.getOptionValue("outFile"))); } args = line.getArgs(); if (args.length != 2) { throw new Exception("Unexpected number of command line arguments"); } refFile = new File(args[0]); queryFile = new File(args[1]); } catch (Exception e) { new HelpFormatter().printHelp("seqmatch <refseqs | trainee_file_or_dir> <query_file>\n" + " trainee_file_or_dir is a single trainee file or a directory containing multiple trainee files", options); System.err.println("Error: " + e.getMessage()); return; } SeqMatch seqmatch = null; if (refFile.isDirectory()) { // a directory of trainee files List<SeqMatch> engineList = new ArrayList<SeqMatch>(); for (File f : refFile.listFiles()) { if (!f.isHidden()) { TwowaySeqMatch match = new TwowaySeqMatch(new SeqMatchEngine(new StorageTrainee(f))); engineList.add(match); } } seqmatch = new MultiTraineeSeqMatch(engineList); } else { // a single fasta file or trainee file if (SeqUtils.guessFileFormat(refFile) == SequenceFormat.UNKNOWN) { seqmatch = CLISeqMatchFactory.trainTwowaySeqMatch(new StorageTrainee(refFile)); } else { seqmatch = CreateMultiMatchFromFile.getMultiMatch(refFile); } } out.println("query name\tmatch seq\torientation\tS_ab score\tunique oligomers\tdescription"); SeqReader reader = new SequenceReader(queryFile); Sequence seq; while ((seq = reader.readNextSequence()) != null) { SeqMatchResultSet resultSet = seqmatch.match(seq, knn); for (SeqMatchResult result : resultSet) { char r = '+'; if (result.isReverse()) { r = '-'; } if (result.getScore() > minSab) { out.println(seq.getSeqName() + "\t" + result.getSeqName() + "\t" + r + "\t" + result.getScore() + "\t" + resultSet.getQueryWordCount() + "\t" + descMap.get(result.getSeqName())); } } } out.close(); } else { throw new IllegalArgumentException("USAGE: SeqMatchMain [train|seqmatch] <args>"); } }
From source file:eu.itesla_project.offline.mpi.Master.java
public static void main(String[] args) throws Exception { try {//from w ww. j a v a2 s . c o m CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(OPTIONS, args); Mode mode = Mode.valueOf(line.getOptionValue("mode")); String simulationDbName = line.hasOption("simulation-db-name") ? line.getOptionValue("simulation-db-name") : OfflineConfig.DEFAULT_SIMULATION_DB_NAME; String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name") : OfflineConfig.DEFAULT_RULES_DB_NAME; String metricsDbName = line.hasOption("metrics-db-name") ? line.getOptionValue("metrics-db-name") : OfflineConfig.DEFAULT_METRICS_DB_NAME; Path tmpDir = Paths.get(line.getOptionValue("tmp-dir")); Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("statistics-factory-class")); Path statisticsDbDir = Paths.get(line.getOptionValue("statistics-db-dir")); String statisticsDbName = line.getOptionValue("statistics-db-name"); int coresPerRank = Integer.parseInt(line.getOptionValue("cores")); Path stdOutArchive = line.hasOption("stdout-archive") ? Paths.get(line.getOptionValue("stdout-archive")) : null; String workflowId = line.hasOption("workflow") ? line.getOptionValue("workflow") : null; MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext(); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); ExecutorService offlineExecutorService = MultiStateNetworkAwareExecutors .newSizeLimitedThreadPool("OFFLINE_POOL", 100); try { MpiStatisticsFactory statisticsFactory = statisticsFactoryClass .asSubclass(MpiStatisticsFactory.class).newInstance(); try (MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName)) { try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics, mpiExecutorContext, coresPerRank, false, stdOutArchive)) { OfflineConfig config = OfflineConfig.load(); try (LocalOfflineApplication application = new LocalOfflineApplication(config, computationManager, simulationDbName, rulesDbName, metricsDbName, scheduledExecutorService, offlineExecutorService)) { switch (mode) { case ui: application.await(); break; case simulations: { if (workflowId == null) { workflowId = application.createWorkflow(null, OfflineWorkflowCreationParameters.load()); } application.startWorkflowAndWait(workflowId, OfflineWorkflowStartParameters.load()); } break; case rules: { if (workflowId == null) { throw new RuntimeException("Workflow '" + workflowId + "' not found"); } application.computeSecurityRulesAndWait(workflowId); } break; default: throw new IllegalArgumentException("Invalid mode " + mode); } } } } } finally { mpiExecutorContext.shutdown(); offlineExecutorService.shutdown(); scheduledExecutorService.shutdown(); offlineExecutorService.awaitTermination(15, TimeUnit.MINUTES); scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES); } } catch (ParseException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("master", OPTIONS, true); System.exit(-1); } catch (Throwable t) { LOGGER.error(t.toString(), t); System.exit(-1); } }
From source file:edu.msu.cme.rdp.classifier.train.ClassifierTraineeMaker.java
/** This is the main method to create training files from raw taxonomic information. * <p>// w w w .j a va 2 s .c o m * Usage: java ClassifierTraineeMaker tax_file rawseq.fa trainsetNo version version_modification output_directory. * See the ClassifierTraineeMaker constructor for more detail. * @param args * @throws FileNotFoundException * @throws IOException */ public static void main(String[] args) throws FileNotFoundException, IOException { String taxFile; String cnFile = null; String seqFile; int trainset_no = 1; String version = null; String modification = null; String outdir = null; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("t")) { taxFile = line.getOptionValue("t"); } else { throw new Exception("taxon file must be specified"); } if (line.hasOption("c")) { cnFile = line.getOptionValue("c"); } if (line.hasOption("s")) { seqFile = line.getOptionValue("s"); } else { throw new Exception("seq file must be specified"); } if (line.hasOption("n")) { try { trainset_no = Integer.parseInt(line.getOptionValue("n")); } catch (NumberFormatException ex) { throw new IllegalArgumentException("trainset_no needs to be an integer."); } } if (line.hasOption("o")) { outdir = line.getOptionValue("o"); } else { throw new Exception("output directory must be specified"); } if (line.hasOption("v")) { version = line.getOptionValue("v"); } if (line.hasOption("m")) { modification = line.getOptionValue("m"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "train", "", options, "", true); return; } ClassifierTraineeMaker maker = new ClassifierTraineeMaker(taxFile, seqFile, cnFile, trainset_no, version, modification, outdir); }
From source file:ViewImageTest.java
/** * Test image(s) (default : JPEG_example_JPG_RIP_100.jpg) are parsed and * rendered to an output foler. Result can then be checked with program of * your choice./*from w w w.ja va 2s . c o m*/ * * @param args * may be empty or contain parameters to override defaults : * <ul> * <li>args[0] : input image file URL or folder containing image * files URL. Default : * viewImageTest/test/JPEG_example_JPG_RIP_100.jpg</li> * <li>args[1] : output format name (for example : "jpg") for * rendered image</li> * <li>args[2] : ouput folder URL</li> * <li>args[3] : max width (in pixels) for rendered image. * Default : no value.</li> * <li>args[4] : max height (in pixels) for rendered image. * Default : no value.</li> * </ul> * @throws IOException * when a read/write error occured */ public static void main(String args[]) throws IOException { File inURL = getInputURL(args); String ext = getEncodingExt(args); File outDir = getOuputDir(args); serverObjects post = makePostParams(args); outDir.mkdirs(); File[] inFiles; if (inURL.isFile()) { inFiles = new File[1]; inFiles[0] = inURL; System.out.println("Testing ViewImage rendering with input file : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else if (inURL.isDirectory()) { FileFilter filter = FileFileFilter.FILE; inFiles = inURL.listFiles(filter); System.out.println("Testing ViewImage rendering with input files in folder : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else { inFiles = new File[0]; } if (inFiles.length == 0) { throw new IllegalArgumentException(inURL.getAbsolutePath() + " is not a valid file or folder url."); } System.out.println("Rendered images will be written in dir : " + outDir.getAbsolutePath()); Map<String, Exception> failures = new HashMap<String, Exception>(); try { for (File inFile : inFiles) { /* Delete eventual previous result file */ File outFile = new File(outDir, inFile.getName() + "." + ext); if (outFile.exists()) { outFile.delete(); } byte[] resourceb = getBytes(inFile); String urlString = inFile.getAbsolutePath(); EncodedImage img = null; Exception error = null; try { img = ViewImage.parseAndScale(post, true, urlString, ext, false, resourceb); } catch (Exception e) { error = e; } if (img == null) { failures.put(urlString, error); } else { FileOutputStream outFileStream = null; try { outFileStream = new FileOutputStream(outFile); img.getImage().writeTo(outFileStream); } finally { if (outFileStream != null) { outFileStream.close(); } img.getImage().close(); } } } displayResults(inFiles, failures); } finally { ConcurrentLog.shutdown(); } }
From source file:com.github.ambry.store.DiskReformatter.java
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ServerConfig serverConfig = new ServerConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj( serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry()); StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" + config.datanodePort); }//w w w. j a v a 2s .c om DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(), storeKeyConverterFactory.getStoreKeyConverter()); AtomicInteger exitStatus = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length); for (int i = 0; i < config.diskMountPaths.length; i++) { int finalI = i; Runnable runnable = () -> { try { reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI])); latch.countDown(); } catch (Exception e) { throw new IllegalStateException(e); } }; Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true); thread.setUncaughtExceptionHandler((t, e) -> { exitStatus.set(1); logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e); latch.countDown(); }); thread.start(); } latch.await(); System.exit(exitStatus.get()); } }
From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java
public static void main(String[] args) { if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) { System.err.println("PokerFace requires at least Java v8 to run."); return;// w ww . j a va2 s. co m } // Configure the command line options parser Options options = new Options(); options.addOption("h", false, "help"); options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https."); options.addOption("keystore", true, "Filepath for PokerFace certificate keystore."); options.addOption("storepass", true, "The store password of the keystore."); options.addOption("keypass", true, "The key password of the keystore."); options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target options.addOption("servercpu", true, "Number of cores the server should use."); options.addOption("targetcpu", true, "Number of cores the http targets should use."); options.addOption("trustany", false, "Ignore certificate identity errors from target servers."); options.addOption("files", true, "Filepath to a directory of static files."); options.addOption("config", true, "Path for XML Configuration file."); options.addOption("scripts", true, "Filepath for root scripts directory."); options.addOption("library", true, "JavaScript library to load into global context."); options.addOption("watch", false, "Dynamically watch scripts directory for changes."); options.addOption("dynamicTargetScripting", false, "WARNING! This option allows scripts to redirect requests to *any* other remote server."); CommandLine cmdLine = null; // parse the command line. try { CommandLineParser parser = new PosixParser(); cmdLine = parser.parse(options, args); if (args.length == 0 || cmdLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(PokerFaceApp.class.getSimpleName(), options); return; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } catch (Exception ex) { ex.printStackTrace(System.err); return; } XMLConfiguration config = new XMLConfiguration(); try { if (cmdLine.hasOption("config")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("config")); if (!Files.exists(tmp)) throw new FileNotFoundException("Configuration file does not exist."); if (Files.isDirectory(tmp)) throw new FileNotFoundException("'config' path is not a file."); // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it. config.setEntityResolver(new DefaultEntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputSource retVal = super.resolveEntity(publicId, systemId); if ((retVal == null) && (systemId != null)) { try { URL entityURL; if (systemId.endsWith("/PokerFace_v1Config.xsd")) entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd"); else entityURL = new URL(systemId); URLConnection connection = entityURL.openConnection(); connection.setUseCaches(false); InputStream stream = connection.getInputStream(); retVal = new InputSource(stream); retVal.setSystemId(entityURL.toExternalForm()); } catch (Throwable e) { return retVal; } } return retVal; } }); config.setSchemaValidation(true); config.setURL(tmp.toUri().toURL()); config.load(); if (cmdLine.hasOption("listen")) System.out.println("IGNORING 'listen' option because a configuration file was supplied."); if (cmdLine.hasOption("target")) System.out.println("IGNORING 'target' option(s) because a configuration file was supplied."); if (cmdLine.hasOption("scripts")) System.out.println("IGNORING 'scripts' option because a configuration file was supplied."); if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option(s) because a configuration file was supplied."); } else { String[] serverStrs; String[] addr = { null }; String[] port = { null }; serverStrs = cmdLine.getOptionValues("listen"); if (serverStrs == null) throw new MissingOptionException("No listening addresses specified specified"); for (int i = 0; i < serverStrs.length; i++) { String addrStr; String alias = null; String protocol = null; Boolean https = null; int addrPos = serverStrs[i].indexOf('='); if (addrPos >= 0) { if (addrPos < 2) throw new IllegalArgumentException("Invalid http argument."); else if (addrPos + 1 >= serverStrs[i].length()) throw new IllegalArgumentException("Invalid http argument."); addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length()); String[] types = serverStrs[i].substring(0, addrPos).split(","); for (String type : types) { if (type.equalsIgnoreCase("http")) break; else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure")) https = true; else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl")) protocol = type.toUpperCase(); else alias = type; } } else addrStr = serverStrs[i]; ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80); config.addProperty("server.listen(" + i + ")[@address]", addr[0]); config.addProperty("server.listen(" + i + ")[@port]", port[0]); if (alias != null) config.addProperty("server.listen(" + i + ")[@alias]", alias); if (protocol != null) config.addProperty("server.listen(" + i + ")[@protocol]", protocol); if (https != null) config.addProperty("server.listen(" + i + ")[@secure]", https); } String servercpu = cmdLine.getOptionValue("servercpu"); if (servercpu != null) config.setProperty("server[@cpu]", servercpu); String clientcpu = cmdLine.getOptionValue("targetcpu"); if (clientcpu != null) config.setProperty("targets[@cpu]", clientcpu); // Configure static files if (cmdLine.hasOption("files")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("files")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri()); } // Configure scripting if (cmdLine.hasOption("scripts")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri()); config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch")); String[] libraries = cmdLine.getOptionValues("library"); if (libraries != null) { for (int i = 0; i < libraries.length; i++) { Path lib = Utils.MakePath(libraries[i]); if (!Files.exists(lib)) throw new FileNotFoundException( "Script library does not exist [" + libraries[i] + "]."); if (Files.isDirectory(lib)) throw new FileNotFoundException( "Script library is not a file [" + libraries[i] + "]."); config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri()); } } } else if (cmdLine.hasOption("watch")) System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified."); else if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option as no 'scripts' directory was specified."); } String keyStorePath = cmdLine.getOptionValue("keystore"); if (keyStorePath != null) config.setProperty("keystore", keyStorePath); String keypass = cmdLine.getOptionValue("keypass"); if (keypass != null) config.setProperty("keypass", keypass); String storepass = cmdLine.getOptionValue("storepass"); if (storepass != null) config.setProperty("storepass", keypass); if (cmdLine.hasOption("trustany")) config.setProperty("targets[@trustAny]", true); config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting")); String[] targetStrs = cmdLine.getOptionValues("target"); if (targetStrs != null) { for (int i = 0; i < targetStrs.length; i++) { int uriPos = targetStrs[i].indexOf('='); if (uriPos < 2) throw new IllegalArgumentException("Invalid target argument."); else if (uriPos + 1 >= targetStrs[i].length()) throw new IllegalArgumentException("Invalid target argument."); String patternStr = targetStrs[i].substring(0, uriPos); String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length()); String alias; try { URL url = new URL(urlStr); alias = url.getUserInfo(); String scheme = url.getProtocol(); if ((!"http".equals(scheme)) && (!"https".equals(scheme))) throw new IllegalArgumentException("Invalid target uri scheme."); int port = url.getPort(); if (port < 0) port = url.getDefaultPort(); urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath(); String ref = url.getRef(); if (ref != null) urlStr += "#" + ref; } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed target uri"); } config.addProperty("targets.target(" + i + ")[@pattern]", patternStr); config.addProperty("targets.target(" + i + ")[@url]", urlStr); if (alias != null) config.addProperty("targets.target(" + i + ")[@alias]", alias); } } // config.save(System.out); } catch (Throwable e) { e.printStackTrace(System.err); return; } // If we get here, we have a possibly valid configuration. try { final PokerFace p = new PokerFace(); p.config(config); if (p.start()) { PokerFace.Logger.warn("Started!"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PokerFace.Logger.warn("Initiating shutdown..."); p.stop(); PokerFace.Logger.warn("Shutdown completed!"); } catch (Throwable e) { PokerFace.Logger.error("Failed to shutdown cleanly!"); e.printStackTrace(System.err); } } }); } else { PokerFace.Logger.error("Failed to start!"); System.exit(-1); } } catch (Throwable e) { e.printStackTrace(System.err); } }