public static Expr parse(Query query, String s, boolean checkAllUsed) { try { Reader in = new StringReader(s); ARQParser parser = new ARQParser(in); parser.setQuery(query); Expr expr = parser.Expression(); if (checkAllUsed) { Token t = parser.getNextToken(); if (t.kind != ARQParserTokenManager.EOF) throw new QueryParseException( "Extra tokens beginning \"" + t.image + "\" starting line " + t.beginLine + ", column " + t.beginColumn, t.beginLine, t.beginColumn); } return expr; } catch (ParseException ex) { throw new QueryParseException( ex.getMessage(), ex.currentToken.beginLine, ex.currentToken.beginLine); } catch (TokenMgrError tErr) { throw new QueryParseException(tErr.getMessage(), -1, -1); } catch (Error err) { // The token stream can throw java.lang.Error's String tmp = err.getMessage(); if (tmp == null) throw new QueryParseException(err, -1, -1); throw new QueryParseException(tmp, -1, -1); } }
public static Node parse(String ref) throws ELException { try { return (new ELParser(new StringReader(ref))).CompositeExpression(); } catch (ParseException pe) { throw new ELException(pe.getMessage()); } }
@Override public OWLOntologyFormat parse( OWLOntologyDocumentSource documentSource, OWLOntology ontology, OWLOntologyLoaderConfiguration configuration) throws OWLParserException, IOException, OWLOntologyChangeException, UnloadableImportException { Reader reader = null; InputStream is = null; try { OWLFunctionalSyntaxParser parser; if (documentSource.isReaderAvailable()) { reader = documentSource.getReader(); parser = new OWLFunctionalSyntaxParser(reader); } else if (documentSource.isInputStreamAvailable()) { is = documentSource.getInputStream(); parser = new OWLFunctionalSyntaxParser(is); } else { is = getInputStream(documentSource.getDocumentIRI(), configuration); parser = new OWLFunctionalSyntaxParser(is); } parser.setUp(ontology, configuration); return parser.parse(); } catch (ParseException e) { throw new OWLParserException( e.getMessage(), e, e.currentToken.beginLine, e.currentToken.beginColumn); } finally { if (is != null) { is.close(); } else if (reader != null) { reader.close(); } } }
/** * Evaluate a function at a specific point for one single variable. Evaluation is done between * xmin and xmax. It is assumed that there are no any other variable involved * * @param indvars Define independent variable, like 'x' Only one variable is allowed * @param xmin xmin value for independent varible * @param xmax xmax value for independent varible * @return true if no errors */ public boolean eval(String indvars, double xmin, double xmax) { boolean suc = true; String name = proxy.getName(); int points = proxy.getPoints(); double min = xmin; double max = xmax; x = new double[points]; y = new double[points]; for (int i = 0; i < points; i++) { x[i] = min + i * (max - min) / (points - 1); jep.addVariable(indvars.trim(), x[i]); try { Object result = jep.evaluate(node); if (result instanceof Double) { y[i] = ((Double) jep.evaluate(node)).doubleValue(); } } catch (ParseException e) { jhplot.utils.Util.ErrorMessage( "Failed to parse function " + name + " Error:" + e.toString()); suc = false; } } if (suc) isEvaluated = true; return suc; } // end 1-D evaluation
public void init(String[] args) throws UserError { Context.reset(); CommandLineParser globalParser = new GnuParser(); List<String> globalArgs = new ArrayList<String>(); boolean inGlobal = true; for (String arg : args) { if (inGlobal) { if (arg.startsWith("--")) { globalArgs.add(arg); } else { this.command = arg; inGlobal = false; } } else { commandArgs.add(arg); } } try { this.globalArguments = globalParser.parse(globalOptions, globalArgs.toArray(new String[globalArgs.size()])); } catch (ParseException e) { throw new UserError("Error parsing global command line argument: " + e.getMessage()); } }
private void assertErrorContains(boolean squareTags, String ftl, String... expectedSubstrings) { try { if (squareTags) { ftl = ftl.replace('<', '[').replace('>', ']'); } new Template("adhoc", ftl, cfg); fail("The tempalte had to fail"); } catch (ParseException e) { String msg = e.getMessage(); for (String needle : expectedSubstrings) { if (needle.startsWith("\\!")) { String netNeedle = needle.substring(2); if (msg.contains(netNeedle)) { fail( "The message shouldn't contain substring " + StringUtil.jQuote(netNeedle) + ":\n" + msg); } } else if (!msg.contains(needle)) { fail("The message didn't contain substring " + StringUtil.jQuote(needle) + ":\n" + msg); } } showError(e); } catch (IOException e) { // Won't happen throw new RuntimeException(e); } }
private FromHeader getFromHeader() throws IOException { if (fromHeader != null) { return fromHeader; } try { SipURI fromURI = (SipURI) addressFactory.createURI("sip:" + proxyCredentials.getUserName() + "@" + registrar); fromURI.setTransportParam(sipProvider.getListeningPoint().getTransport()); fromURI.setPort(sipProvider.getListeningPoint().getPort()); Address fromAddress = addressFactory.createAddress(fromURI); fromAddress.setDisplayName(proxyCredentials.getUserDisplay()); fromHeader = headerFactory.createFromHeader(fromAddress, Integer.toString(hashCode())); } catch (ParseException e) { throw new IOException( "A ParseException occurred while creating From Header! " + e.getMessage()); } return fromHeader; }
/** * Processing the input command line arguments * * @param args a list of pride db accessions */ private void processCmdArgs(String[] args) { try { // parse command line input CommandLine cmd = cmdParser.parse(cmdOptions, args); // get accessions java.util.List<Comparable> accs = null; if (cmd.hasOption(ACCESSION_CMD)) { String accStr = cmd.getOptionValue(ACCESSION_CMD); accs = new ArrayList<Comparable>(AccessionUtils.expand(accStr)); } // get user name String username = null; if (cmd.hasOption(USER_NAME_CMD)) { username = cmd.getOptionValue(USER_NAME_CMD); } // get password String password = null; if (cmd.hasOption(PASSWORD_CMD)) { password = cmd.getOptionValue(PASSWORD_CMD); } if (accs != null || username != null) { OpenValidPrideExperimentTask task = new OpenValidPrideExperimentTask(accs, username, password); task.setGUIBlocker(new DefaultGUIBlocker(task, GUIBlocker.Scope.NONE, null)); getDesktopContext().addTask(task); } } catch (ParseException e) { System.err.println("Parsing command line option failed. Reason: " + e.getMessage()); } }
@Override public void parse(String line, ParseState state) throws ParseException { super.parse(line, state); final Matcher matcher = match(Constants.EXT_X_VERSION_PATTERN, line); if (state.getCompatibilityVersion() != ParseState.NONE) { throw ParseException.create( ParseExceptionType.MULTIPLE_EXT_TAG_INSTANCES, getTag(), line); } final int compatibilityVersion = ParseUtil.parseInt(matcher.group(1), getTag()); if (compatibilityVersion < Playlist.MIN_COMPATIBILITY_VERSION) { throw ParseException.create( ParseExceptionType.INVALID_COMPATIBILITY_VERSION, getTag(), line); } if (compatibilityVersion > Constants.MAX_COMPATIBILITY_VERSION) { throw ParseException.create( ParseExceptionType.UNSUPPORTED_COMPATIBILITY_VERSION, getTag(), line); } state.setCompatibilityVersion(compatibilityVersion); }
private ArrayList getLocalViaHeaders() throws IOException { /* * We can't keep a cached copy because the callers * of this method change the viaHeaders. In particular * a branch may be added which causes INVITES to fail. */ if (viaHeaders != null) { return viaHeaders; } ListeningPoint lp = sipProvider.getListeningPoint(); viaHeaders = new ArrayList(); try { String addr = lp.getIPAddress(); ViaHeader viaHeader = headerFactory.createViaHeader(addr, lp.getPort(), lp.getTransport(), null); viaHeader.setRPort(); viaHeaders.add(viaHeader); return viaHeaders; } catch (ParseException e) { throw new IOException( "A ParseException occurred while creating Via Headers! " + e.getMessage()); } catch (InvalidArgumentException e) { throw new IOException( "Unable to create a via header for port " + lp.getPort() + " " + e.getMessage()); } }
public void testCDate() throws ParseException { Date date = new Date(); assertEquals(date, Vba.cDate(date)); assertNull(Vba.cDate(null)); // CInt rounds to the nearest even number try { assertEquals(DateFormat.getDateInstance().parse("Jan 12, 1952"), Vba.cDate("Jan 12, 1952")); assertEquals( DateFormat.getDateInstance().parse("October 19, 1962"), Vba.cDate("October 19, 1962")); assertEquals(DateFormat.getTimeInstance().parse("4:35:47 PM"), Vba.cDate("4:35:47 PM")); assertEquals( DateFormat.getDateTimeInstance().parse("October 19, 1962 4:35:47 PM"), Vba.cDate("October 19, 1962 4:35:47 PM")); } catch (ParseException e) { e.printStackTrace(); fail(); } try { Vba.cDate("Jan, 1952"); fail(); } catch (InvalidArgumentException e) { assertTrue(e.getMessage().indexOf("Jan, 1952") >= 0); } }
public static void main(String args[]) { JJTDotParser parser; if (args.length == 0) { System.out.println("JJT Dot Parser: Reading from standard input . . ."); parser = new JJTDotParser(System.in); } else if (args.length == 1) { System.out.println("JJT Dot Parser: Reading from file " + args[0] + " . . ."); try { parser = new JJTDotParser(new java.io.FileInputStream(args[0])); parser.setInFname(args[0]); } catch (java.io.FileNotFoundException e) { System.out.println("JJT Dot Parser: File " + args[0] + " not found."); return; } } else { System.out.println("JJT Dot Parser: Usage is one of:"); System.out.println(" java JJTDotParser < inputfile"); System.out.println("OR"); System.out.println(" java JJTDotParser inputfile"); return; } try { parser.dotGraph(); System.out.println("JJT Dot Parser: Dot program parsed successfully."); } catch (ParseException e) { System.out.println(e.getMessage()); System.out.println("JJT Dot Parser: Encountered errors during parse."); } }
public Document doXmlFetch(InputStream inputStream, Config<ResultType> config) throws IOException, ParseException, InterruptedException { try { // now get the system XML parser using JAXP DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance(); // namespaces won't work at ALL if this isn't enabled. docBuildFactory.setNamespaceAware(true); DocumentBuilder parser = docBuildFactory.newDocumentBuilder(); // parse the document into a DOM.... I'd like to use JDOM here but // it's yet another lib to support and we want to keep things thin // and lightweight. // // Another advantage to DOM is that it's very portable. Document doc = parser.parse(inputStream); return doc; } catch (IOException ioe) { throw ioe; } catch (Exception e) { String message = String.format("Unable to parse %s: %s", getLastRequestURL(), e.getMessage()); ParseException pe = new ParseException(message); pe.initCause(e); throw pe; } }
public void test11456() { // Posix Options options = new Options(); options.addOption(OptionBuilder.hasOptionalArg().create('a')); options.addOption(OptionBuilder.hasArg().create('b')); String[] args = new String[] {"-a", "-bvalue"}; CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); assertEquals(cmd.getOptionValue('b'), "value"); } catch (ParseException exp) { fail("Unexpected Exception: " + exp.getMessage()); } // GNU options = new Options(); options.addOption(OptionBuilder.hasOptionalArg().create('a')); options.addOption(OptionBuilder.hasArg().create('b')); args = new String[] {"-a", "-b", "value"}; parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); assertEquals(cmd.getOptionValue('b'), "value"); } catch (ParseException exp) { fail("Unexpected Exception: " + exp.getMessage()); } }
public static Options parseArgs(String cmdArgs[]) { CommandLineParser parser = new GnuParser(); CmdLineOptions options = getCmdLineOptions(); try { CommandLine cmd = parser.parse(options, cmdArgs, false); if (cmd.hasOption(HELP_OPTION)) { printUsage(options); System.exit(0); } String[] args = cmd.getArgs(); if (args.length == 0) { System.err.println("No sstables to split"); printUsage(options); System.exit(1); } Options opts = new Options(Arrays.asList(args)); opts.debug = cmd.hasOption(DEBUG_OPTION); opts.verbose = cmd.hasOption(VERBOSE_OPTION); opts.snapshot = !cmd.hasOption(NO_SNAPSHOT_OPTION); opts.sizeInMB = DEFAULT_SSTABLE_SIZE; if (cmd.hasOption(SIZE_OPTION)) opts.sizeInMB = Integer.valueOf(cmd.getOptionValue(SIZE_OPTION)); return opts; } catch (ParseException e) { errorMsg(e.getMessage(), options); return null; } }
public static String body(String[] args) { LexicalAnalyzer lex = new LexicalAnalyzer(); String str = ""; try { BufferedReader in = null; if (args.length == 0) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(args[0])); } lex.tokenize(in); } catch (IOException e) { System.out.println("IO Error"); } try { DatalogProgram datalogProgram = new DatalogProgram(lex); str += "Success!\n"; str += datalogProgram.toString(); } catch (ParseException e) { str += "Failure!\n " + e.getToken().toString(); } return str; }
public static Options parseArgs(String cmdArgs[]) { CommandLineParser parser = new GnuParser(); CmdLineOptions options = getCmdLineOptions(); try { CommandLine cmd = parser.parse(options, cmdArgs, false); if (cmd.hasOption(HELP_OPTION)) { printUsage(options); System.exit(0); } String[] args = cmd.getArgs(); if (args.length >= 4 || args.length < 2) { String msg = args.length < 2 ? "Missing arguments" : "Too many arguments"; errorMsg(msg, options); System.exit(1); } String keyspace = args[0]; String cf = args[1]; String snapshot = null; if (args.length == 3) snapshot = args[2]; Options opts = new Options(keyspace, cf, snapshot); opts.debug = cmd.hasOption(DEBUG_OPTION); opts.keepSource = cmd.hasOption(KEEP_SOURCE); return opts; } catch (ParseException e) { errorMsg(e.getMessage(), options); return null; } }
/** Invoked by the HTTPClient. */ public int requestHandler(Request req, Response[] resp) throws ModuleException { // parse Accept-Encoding header int idx; NVPair[] hdrs = req.getHeaders(); for (idx = 0; idx < hdrs.length; idx++) if (hdrs[idx].getName().equalsIgnoreCase("Accept-Encoding")) break; Vector pae; if (idx == hdrs.length) { hdrs = Util.resizeArray(hdrs, idx + 1); req.setHeaders(hdrs); pae = new Vector(); } else { try { pae = Util.parseHeader(hdrs[idx].getValue()); } catch (ParseException pe) { throw new ModuleException(pe.toString()); } } // done if "*;q=1.0" present HttpHeaderElement all = Util.getElement(pae, "*"); if (all != null) { NVPair[] params = all.getParams(); for (idx = 0; idx < params.length; idx++) if (params[idx].getName().equalsIgnoreCase("q")) break; if (idx == params.length) // no qvalue, i.e. q=1.0 return REQ_CONTINUE; if (params[idx].getValue() == null || params[idx].getValue().length() == 0) throw new ModuleException("Invalid q value for \"*\" in " + "Accept-Encoding header: "); try { if (Float.valueOf(params[idx].getValue()).floatValue() > 0.) return REQ_CONTINUE; } catch (NumberFormatException nfe) { throw new ModuleException( "Invalid q value for \"*\" in " + "Accept-Encoding header: " + nfe.getMessage()); } } // Add gzip, deflate and compress tokens to the Accept-Encoding header if (!pae.contains(new HttpHeaderElement("deflate"))) pae.addElement(new HttpHeaderElement("deflate")); if (!pae.contains(new HttpHeaderElement("gzip"))) pae.addElement(new HttpHeaderElement("gzip")); if (!pae.contains(new HttpHeaderElement("x-gzip"))) pae.addElement(new HttpHeaderElement("x-gzip")); if (!pae.contains(new HttpHeaderElement("compress"))) pae.addElement(new HttpHeaderElement("compress")); if (!pae.contains(new HttpHeaderElement("x-compress"))) pae.addElement(new HttpHeaderElement("x-compress")); hdrs[idx] = new NVPair("Accept-Encoding", Util.assembleHeader(pae)); return REQ_CONTINUE; }
@Override public void seeCommand(String cmd) { try { parser.parseSeeCommand(cmd, controller, action); } catch (ParseException ex) { Assert.fail(ex.getMessage()); } }
// TODO add exception for invalid options private void loadCLO(String[] args) { Options options = new Options(); String[][] clolist = { // {"variable/optionname", "description"}, {"genConfig", "general configuration file location"}, {"inWeightsLoc", "input weights configuration file location"}, {"inDBLoc", "input database file location"}, {"outWeightsLoc", "output weights configuration file location"}, {"outDBLoc", "output database file location"}, {"p3pLocation", "adding to DB: single policy file location"}, {"p3pDirLocation", "adding to DB: multiple policy directory location"}, {"newDB", "create new database in place of old one (doesn't check for existence of old one"}, {"newPolicyLoc", "the policy object to process"}, {"userResponse", "response to specified policy"}, {"userIO", "user interface"}, {"userInit", "initialization via user interface"}, {"policyDB", "PolicyDatabase backend"}, {"cbrV", "CBR to use"}, {"blanketAccept", "automatically accept the user suggestion"}, {"loglevel", "level of things save to the log- see java logging details"}, {"policyDB", "PolicyDatabase backend"}, {"NetworkRType", "Network Resource type"}, {"NetworkROptions", "Network Resource options"}, {"confidenceLevel", "Confidence threshold for consulting a networked resource"}, {"useNet", "use networking options"}, {"loglocation", "where to save the log file"}, {"loglevel", "the java logging level to use. See online documentation for enums."} }; for (String[] i : clolist) { options.addOption(i[0], true, i[1]); } CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error parsing commandline arguments."); e.printStackTrace(); System.exit(3); } /* for(String i : args) { System.err.println(i); } */ for (String[] i : clolist) { if (cmd.hasOption(i[0])) { System.err.println("found option i: " + i); genProps.setProperty(i[0], cmd.getOptionValue(i[0])); } } System.err.println(genProps); }
public static String[] getExpectedTokenSet(ParseException e) { String[] expected; if (e.getExpected() < 0) { expected = getTokenSet(-e.getState()); } else { expected = new String[] {TOKEN[e.getExpected()]}; } return expected; }
@Test public void shouldThrowIfMissingTitle() throws Exception { try { MovieListParser.parse( makeMovieListJson(MOVIE_1.replace("\"original_title\":\"Jurassic World\",", ""))); fail("Should have thrown"); } catch (ParseException e) { assertThat(e.getMessage(), containsString("Failed to parse movie result")); } }
public Segment(ByteBuf bb, int len, IParse<T> sjparse) { this.len = len; this.sjparse = sjparse; try { value = sjparse.parse(bb, len); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void readBad(String wkt) throws IOException { boolean threwParseEx = false; try { Geometry g = rdr.read(wkt); } catch (ParseException ex) { System.out.println(ex.getMessage()); threwParseEx = true; } assertTrue(threwParseEx); }
@Test public void failureTooManyValues() { try { String data = "columnA,columnB\nvalue1A,value1B\nvalue2A,value2B,value2C"; underTest.parse(data); fail("no exception thrown"); } catch (ParseException e) { assertEquals(3, e.getLineNumber()); } }
public static void main(String[] args) { try { Node root = new MiniRAParser(System.in).Goal(); // System.out.println("Program parsed successfully"); Object a = root.accept(new GJDepthFirst(), null); // root.accept(new GJNoArgu(a)); } catch (ParseException e) { System.out.println(e.toString()); } }
/** * Creates a SessionDescription populated with the information contained within the string * parameter. * * <p>Note: unknown field types should not cause exceptions. * * @param s s - the sdp message that is to be parsed. * @throws SdpParseException SdpParseException - if there is a problem parsing the String. * @return a populated SessionDescription object. */ public SessionDescription createSessionDescription(String s) throws SdpParseException { try { SDPAnnounceParser sdpParser = new SDPAnnounceParser(s); return sdpParser.parse(); } catch (ParseException e) { e.printStackTrace(); throw new SdpParseException(0, 0, "Could not parse message"); } }
@Test public void failureNoData() { try { String data = ""; underTest.parse(data); fail("no exception thrown"); } catch (ParseException e) { assertEquals(-1, e.getLineNumber()); } }
private int run(String[] args) { // DECODE ARGS try { if (args.length == 0) { usage(); return 0; } for (int i = 0; i < args.length; ) { int j = decodeArg(args, i); if (j == 0) { throw new ParseException(lookup("main.err.unrecognizedarg", args[i])); } i += j; } } catch (ParseException e) { System.err.println(e.getMessage()); return 1; } // CHECK ARGUMENTS if (helpFlag) { usage(); return 0; } if (urlList.size() == 0) { System.err.println(lookup("main.err.inputfile")); return 1; } if (debugFlag) { // START A DEBUG SESSION // Given the current architecture, we will end up decoding the // arguments again, but at least we are guaranteed to have // arguments which are valid. return invokeDebugger(args); } // INSTALL THE SECURITY MANAGER (if necessary) if (!noSecurityFlag && (System.getSecurityManager() == null)) init(); // LAUNCH APPLETVIEWER FOR EACH URL for (int i = 0; i < urlList.size(); i++) { try { // XXX 5/17 this parsing method should be changed/fixed so that // it doesn't do both parsing of the html file and launching of // the AppletPanel AppletViewer.parse((URL) urlList.elementAt(i), encoding); } catch (IOException e) { System.err.println(lookup("main.err.io", e.getMessage())); return 1; } } return 0; }
public void run() { if (telephony == null) return; Call createdCall = null; if (contacts != null) { Contact contact = (Contact) contacts.get(0); // NOTE: The multi user call is not yet implemented! // We just get the first contact and create a call for him. try { createdCall = telephony.createCall(contact); } catch (OperationFailedException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(contact.getDisplayName()).setState(e.getMessage()); removeCallPanelWait(callPanel); } // If the call is successfully created we set the created // Call instance to the already existing CallPanel and we // add this call to the active calls. if (createdCall != null) { callPanel.setCall(createdCall, GuiCallParticipantRecord.OUTGOING_CALL); activeCalls.put(createdCall, callPanel); } } else { try { createdCall = telephony.createCall(stringContact); } catch (ParseException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(stringContact).setState(e.getMessage()); removeCallPanelWait(callPanel); } catch (OperationFailedException e) { logger.error("The call could not be created: " + e); callPanel.getParticipantPanel(stringContact).setState(e.getMessage()); removeCallPanelWait(callPanel); } // If the call is successfully created we set the created // Call instance to the already existing CallPanel and we // add this call to the active calls. if (createdCall != null) { callPanel.setCall(createdCall, GuiCallParticipantRecord.OUTGOING_CALL); activeCalls.put(createdCall, callPanel); } } }