List of usage examples for java.lang IllegalArgumentException IllegalArgumentException
public IllegalArgumentException(Throwable cause)
From source file:org.opcfoundation.ua.examples.BigCertificateExample.java
public static void main(String[] args) throws Exception { // Create Logger Logger myLogger = LoggerFactory.getLogger(BigCertificateExample.class); ///// Server Application ///////////// Application serverApplication = new Application(); MyServerExample2 myServer = new MyServerExample2(serverApplication); // Attach listener (debug logger) to each binding DebugLogger debugLogger = new DebugLogger(myLogger); for (EndpointServer b : myServer.getEndpointBindings().getEndpointServers()) b.addConnectionListener(debugLogger); ////////////////////////////////////// ////////////// CLIENT ////////////// // Load Client's Application Instance Certificate from file KeyPair myClientOpcTcpKeyPair = ExampleKeys.getKeyPair("client", CLIENT_KEY_SIZE); KeyPair myClientHttpsKeyPair = ExampleKeys.getKeyPair("https_client", CLIENT_KEY_SIZE); // Create Client Application Application myClientApplication = new Application(); myClientApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); myClientApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL); myClientApplication.getHttpsSettings().setKeyPair(myClientHttpsKeyPair); myClientApplication.addApplicationInstanceCertificate(myClientOpcTcpKeyPair); // Create Client Client myClient = new Client(myClientApplication); ////////////////////////////////////// // Get Endpoints like this SecureChannel secureChannel = myClient.createSecureChannel(URL, URL, SecurityMode.NONE, null); ChannelService chan = new ChannelService(secureChannel); EndpointDescription[] endpoints;//from www. ja va 2 s.c om try { GetEndpointsRequest req = new GetEndpointsRequest(null, URL, new String[0], new String[0]); GetEndpointsResponse res = chan.GetEndpoints(req); endpoints = res.getEndpoints(); } finally { secureChannel.close(); secureChannel.dispose(); } SessionChannel myChannel = null; try { // Select policy according to initial parameters String proto = UriUtil.getTransportProtocol(URL); endpoints = EndpointUtil.select(endpoints, CLIENT_KEY_SIZE, CLIENT_KEY_SIZE); endpoints = EndpointUtil.select(endpoints, null, proto, null, null, null); if (proto.equals("https")) { endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.None); myClient.getApplicationHttpsSettings().setHttpsSecurityPolicies(httpsSecurityPolicies); } else endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.SignAndEncrypt); if (endpoints.length == 0) { throw new IllegalArgumentException("No suitable endpoint found from " + URL); } ///////// DISCOVER SERVERS ///////// // Discover server applications // ApplicationDescription[] servers = myClient.discoverApplications( new URI("https://localhost:6001/") ); // // Choose one application // ApplicationDescription server = servers[0]; // Connect the application myChannel = myClient.createSessionChannel(endpoints[0]); // myChannel = myClient.createSessionChannel( server ); // Activate session myChannel.activate(); ////////////////////////////////////// ///////////// EXECUTE ////////////// CallRequest callRequest = new CallRequest(); CallMethodRequest methodRequest = new CallMethodRequest(); callRequest.setMethodsToCall(new CallMethodRequest[] { methodRequest }); methodRequest.setMethodId(MyServerExample2.LIST_SOLVERS); CallResponse res = myChannel.Call(callRequest); System.out.println(res); ////////////////////////////////////// } finally { ///////////// SHUTDOWN ///////////// // Close client's channel if (myChannel != null) myChannel.close(); // Close the server by unbinding all endpoints myServer.getApplication().close(); ////////////////////////////////////// } }
From source file:examples.mail.IMAPExportMbox.java
public static void main(String[] args) throws IOException { int connect_timeout = CONNECT_TIMEOUT; int read_timeout = READ_TIMEOUT; int argIdx = 0; String eol = EOL_DEFAULT;/* w w w . jav a 2s.c om*/ boolean printHash = false; boolean printMarker = false; int retryWaitSecs = 0; for (argIdx = 0; argIdx < args.length; argIdx++) { if (args[argIdx].equals("-c")) { connect_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-r")) { read_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-R")) { retryWaitSecs = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-LF")) { eol = LF; } else if (args[argIdx].equals("-CRLF")) { eol = CRLF; } else if (args[argIdx].equals("-.")) { printHash = true; } else if (args[argIdx].equals("-X")) { printMarker = true; } else { break; } } final int argCount = args.length - argIdx; if (argCount < 2) { System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]" + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]"); System.err.println( "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)"); System.err.println("\t-c connect timeout in seconds (default 10)"); System.err.println("\t-r read timeout in seconds (default 10)"); System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)"); System.err.println("\t-. print a . for each complete message received"); System.err.println("\t-X print the X-IMAP line for each complete message received"); System.err.println( "\tthe mboxfile is where the messages are stored; use '-' to write to standard output."); System.err.println( "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite."); System.err.println( "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*"); System.err .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]" + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])"); System.exit(1); } final URI uri = URI.create(args[argIdx++]); final String file = args[argIdx++]; String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*"; final String itemNames; // Handle 0, 1 or multiple item names if (argCount > 3) { if (argCount > 4) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 4; i <= argCount; i++) { if (i > 4) { sb.append(" "); } sb.append(args[argIdx++]); } sb.append(")"); itemNames = sb.toString(); } else { itemNames = args[argIdx++]; } } else { itemNames = "(INTERNALDATE BODY.PEEK[])"; } final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence? final MboxListener chunkListener; if (file.equals("-")) { chunkListener = null; } else if (file.startsWith("+")) { final File mbox = new File(file.substring(1)); System.out.println("Appending to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash, printMarker, checkSequence); } else if (file.startsWith("-")) { final File mbox = new File(file.substring(1)); System.out.println("Writing to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash, printMarker, checkSequence); } else { final File mbox = new File(file); if (mbox.exists()) { throw new IOException("mailbox file: " + mbox + " already exists!"); } System.out.println("Creating file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker, checkSequence); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / // suppress login details final PrintCommandListener listener = new PrintCommandListener(System.out, true) { @Override public void protocolReplyReceived(ProtocolCommandEvent event) { if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener super.protocolReplyReceived(event); } } }; // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener); String maxIndexInFolder = null; try { imap.setSoTimeout(read_timeout * 1000); if (!imap.select(folder)) { throw new IOException("Could not select folder: " + folder); } for (String line : imap.getReplyStrings()) { maxIndexInFolder = matches(line, PATEXISTS, 1); if (maxIndexInFolder != null) { break; } } if (chunkListener != null) { imap.setChunkListener(chunkListener); } // else the command listener displays the full output without processing while (true) { boolean ok = imap.fetch(sequenceSet, itemNames); // If the fetch failed, can we retry? if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) { final String replyString = imap.getReplyString(); //includes EOL if (startsWith(replyString, PATTEMPFAIL)) { System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds"); sequenceSet = (chunkListener.lastSeq + 1) + ":*"; try { Thread.sleep(retryWaitSecs * 1000); } catch (InterruptedException e) { // ignored } } else { throw new IOException( "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString); } } else { break; } } } catch (IOException ioe) { String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total); System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count + " complete messages "); if (chunkListener != null) { System.err.println("Last complete response seen: " + chunkListener.lastFetched); } throw ioe; } finally { if (printHash) { System.err.println(); } if (chunkListener != null) { chunkListener.close(); final Iterator<String> missingIds = chunkListener.missingIds.iterator(); if (missingIds.hasNext()) { StringBuilder sb = new StringBuilder(); for (;;) { sb.append(missingIds.next()); if (!missingIds.hasNext()) { break; } sb.append(","); } System.err.println("*** Missing ids: " + sb.toString()); } } imap.logout(); imap.disconnect(); } if (chunkListener != null) { System.out.println("Processed " + chunkListener.total + " messages."); } if (maxIndexInFolder != null) { System.out.println("Folder contained " + maxIndexInFolder + " messages."); } }
From source file:com.linkedin.helix.controller.HelixControllerMain.java
public static void main(String[] args) throws Exception { // read the config; // check if the this process is the master wait indefinitely // other approach is always process the events but when updating the zk // check if this is master. // This is difficult to get right // get the clusters to manage // for each cluster create a manager // add the respective listeners for each manager CommandLine cmd = processCommandLineArgs(args); String zkConnectString = cmd.getOptionValue(zkServerAddress); String clusterName = cmd.getOptionValue(cluster); String controllerMode = STANDALONE; String controllerName = null; int propertyTransServicePort = -1; if (cmd.hasOption(mode)) { controllerMode = cmd.getOptionValue(mode); }/*w w w.j av a2 s. co m*/ if (cmd.hasOption(propertyTransferServicePort)) { propertyTransServicePort = Integer.parseInt(cmd.getOptionValue(propertyTransferServicePort)); } if (controllerMode.equalsIgnoreCase(DISTRIBUTED) && !cmd.hasOption(name)) { throw new IllegalArgumentException("A unique cluster controller name is required in DISTRIBUTED mode"); } controllerName = cmd.getOptionValue(name); // Espresso_driver.py will consume this logger.info("Cluster manager started, zkServer: " + zkConnectString + ", clusterName:" + clusterName + ", controllerName:" + controllerName + ", mode:" + controllerMode); if (propertyTransServicePort > 0) { ZKPropertyTransferServer.getInstance().init(propertyTransServicePort, zkConnectString); } HelixManager manager = startHelixController(zkConnectString, clusterName, controllerName, controllerMode); try { Thread.currentThread().join(); } catch (InterruptedException e) { logger.info("controller:" + controllerName + ", " + Thread.currentThread().getName() + " interrupted"); } finally { manager.disconnect(); ZKPropertyTransferServer.getInstance().shutdown(); } }
From source file:io.anserini.search.SearchWebCollection.java
public static void main(String[] args) throws Exception { SearchArgs searchArgs = new SearchArgs(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try {/*from ww w. j a v a 2s.com*/ parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example: SearchWebCollection" + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } LOG.info("Reading index at " + searchArgs.index); Directory dir; if (searchArgs.inmem) { LOG.info("Using MMapDirectory with preload"); dir = new MMapDirectory(Paths.get(searchArgs.index)); ((MMapDirectory) dir).setPreload(true); } else { LOG.info("Using default FSDirectory"); dir = FSDirectory.open(Paths.get(searchArgs.index)); } Similarity similarity = null; if (searchArgs.ql) { LOG.info("Using QL scoring model"); similarity = new LMDirichletSimilarity(searchArgs.mu); } else if (searchArgs.bm25) { LOG.info("Using BM25 scoring model"); similarity = new BM25Similarity(searchArgs.k1, searchArgs.b); } else { LOG.error("Error: Must specify scoring model!"); System.exit(-1); } RerankerCascade cascade = new RerankerCascade(); boolean useQueryParser = false; if (searchArgs.rm3) { cascade.add(new Rm3Reranker(new EnglishAnalyzer(), FIELD_BODY, "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt")); useQueryParser = true; } else { cascade.add(new IdentityReranker()); } FeatureExtractors extractors = null; if (searchArgs.extractors != null) { extractors = FeatureExtractors.loadExtractor(searchArgs.extractors); } if (searchArgs.dumpFeatures) { PrintStream out = new PrintStream(searchArgs.featureFile); Qrels qrels = new Qrels(searchArgs.qrels); cascade.add(new WebCollectionLtrDataGenerator(out, qrels, extractors)); } Path topicsFile = Paths.get(searchArgs.topics); if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) { throw new IllegalArgumentException( "Topics file : " + topicsFile + " does not exist or is not a (readable) file."); } TopicReader tr = (TopicReader) Class .forName("io.anserini.search.query." + searchArgs.topicReader + "TopicReader") .getConstructor(Path.class).newInstance(topicsFile); SortedMap<Integer, String> topics = tr.read(); final long start = System.nanoTime(); SearchWebCollection searcher = new SearchWebCollection(searchArgs.index); searcher.search(topics, searchArgs.output, similarity, searchArgs.hits, cascade, useQueryParser, searchArgs.keepstop); searcher.close(); final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); LOG.info("Total " + topics.size() + " topics searched in " + DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss")); }
From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java
/** Starts a StrategyPlotter. * @param parameters// w w w.j a v a 2s. c om * <pre> * Optional Parameters and default values: * -initialCash $10,000.00 * -perTradeFee $1.00 * -perShareTradeCommission $0.02 * -strategy com.zigabyte.stock.strategy.SundayPeaks(0.2,0.08) * -metastock (default path: current directory) * -serialized (default path: current directory) * -serializedgz (default path: current directory) * Values may need to be quoted '$1' or 'pkg.MyStrategy(0.1)'. * Use only one -metastock, -serialized, or -serializedgz to specify data. * </pre> **/ public static void main(String... parameters) { double initialCash = DEFAULT_INITIAL_CASH; double initialPerTradeFee = DEFAULT_PER_TRADE_FEE; double initialPerShareTradeCommission = DEFAULT_PER_SHARE_TRADE_COMMISSION; String initialStrategy = DEFAULT_STRATEGY; String initialDataFormat = DEFAULT_DATA_FORMAT; String initialDataPath = DEFAULT_DATA_PATH; // parse parameters int parameterIndex = 0; try { for (; parameterIndex < parameters.length; parameterIndex++) { String parameter = parameters[parameterIndex]; if ("-initialCash".equalsIgnoreCase(parameter) || "-perTradeFee".equalsIgnoreCase(parameter) || "-perShareTradeCommission".equalsIgnoreCase(parameter)) { double value = DOLLAR_FORMAT.parse(parameters[++parameterIndex]).doubleValue(); if ("-initialCash".equalsIgnoreCase(parameter)) { initialCash = value; } else if ("-perTradeFee".equalsIgnoreCase(parameter)) { initialPerTradeFee = value; } else if ("-perShareTradeCommission".equalsIgnoreCase(parameter)) { initialPerShareTradeCommission = value; } else assert false; } else if ("-strategy".equalsIgnoreCase(parameter) || "-metastock".equalsIgnoreCase(parameter) || "-serialized".equalsIgnoreCase(parameter) || "-serializedgz".equalsIgnoreCase(parameter)) { StringBuffer buf = new StringBuffer(); String part; while (++parameterIndex < parameters.length && !(part = parameters[parameterIndex]).startsWith("-")) { if (buf.length() > 0) buf.append(' '); buf.append(part); } --parameterIndex; String value = buf.toString(); if ("-strategy".equalsIgnoreCase(parameter)) { initialStrategy = value; } else if ("-metastock".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "Metastock"; } else if ("-serialized".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "Serialized"; } else if ("-serializedgz".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "SerializedGZ"; } else assert false; } else if ("-help".equalsIgnoreCase(parameter)) { parameterExit(0); } else throw new IllegalArgumentException(parameter); } } catch (Exception e) { System.err.println(e); int indent = 0; for (int i = 0; i < parameters.length; i++) { String parameter = parameters[i]; if (i < parameterIndex) indent += parameter.length() + 1; System.err.print(parameter); System.err.print(' '); } System.err.println(); for (int i = 0; i < indent; i++) System.err.print('_'); System.err.println('^'); parameterExit(-1); } // set up plotter StrategyPlotter plotter = new StrategyPlotter(initialCash, initialPerTradeFee, initialPerShareTradeCommission, initialStrategy, initialDataFormat, initialDataPath); plotter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); plotter.setSize(1024, 768); plotter.setLocationRelativeTo(null); // center on screen plotter.setVisible(true); }
From source file:Main.java
static void checkSpeed(float speed) { if (speed <= 0f) { throw new IllegalArgumentException("Speed must be >= 0"); }// w w w . j a v a 2 s . c o m }
From source file:Main.java
public static void checkSpeed(float speed) { if (speed <= 0f) throw new IllegalArgumentException("Speed must be >= 0"); }
From source file:Main.java
public static void checkNotNull(Object o, String name) { if (o == null) throw new IllegalArgumentException(String.format("%s must be not null", name)); }
From source file:Main.java
public static void checkPositive(int number, String name) { if (number <= 0) throw new IllegalArgumentException(String.format("%s must not be null", name)); }
From source file:Main.java
public static String validateId(final String id) { if (!id.matches("^\\d+$")) throw new IllegalArgumentException("Not correct _ID: " + id); return id;//from w ww. j av a 2 s . c o m }