@Override public Response toResponse(Exception exception) { logError(exception); Error error; int httpCode = isRuntimeClass(exception.getClass()) ? defaultRuntimeExceptionHttpCode : defaultCheckedExceptionHttpCode; try { Integer code = findCode(exception); if (code != null) { httpCode = code; } error = buildError(exception); if (hideExceptionClass) { error.setException(null); } if (hideMessage) { error.setMessage(null); } } catch (Exception e) { httpCode = 500; error = new Error(e); logError(e); } return Response.status(httpCode).entity(error).type(findMediaType()).build(); }
private void TypesOfSchool() throws IOException { // Click Type of School driver.findElement(By.cssSelector("strong")).click(); // Click Private driver.findElement(By.id("edit-public-private-private")).click(); // Move School Size Slider // TODO Slider not working properly WebElement Slider1 = driver.findElement(By.id("population_jq_slider")); Actions moveSlider1 = new Actions(driver); Action action1 = moveSlider1.dragAndDropBy(Slider1, 0, 10).build(); action1.perform(); // Select Religious Affiliation new Select(driver.findElement(By.id("edit-religious-affiliation"))) .selectByVisibleText("Church of Christ"); // Move Tuition Range Slider // TODO Slider not working properly WebElement Slider2 = driver.findElement(By.id("tuition_range_jq_slider")); Actions moveSlider2 = new Actions(driver); Action action2 = moveSlider2.dragAndDropBy(Slider2, 0, 10).build(); action2.perform(); // Click Apply driver.findElement(By.id("edit-type-of-school-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
public static BufferedImage doFilter(BufferedImage img) { BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // img.getSubimage(0, 0, img.getWidth(), img.getHeight()); for (int i = 0; i < img2.getWidth(); i++) { for (int j = 0; j < img2.getHeight(); j++) { img2.setRGB(i, j, img.getRGB(i, j)); // img2.setRGB(i, j, Color.BLACK.getRGB()); } } int a = 32; for (int j = 0; j < img2.getHeight(); j++) { for (int i = 0; i < img2.getWidth(); i++) { int c = img.getRGB(i, j); Color c2 = new Color(c); Error er = new Error(); er.r = (int) (a * matrix[i % 2][j % 2]); er.g = er.r; er.b = er.r; c2 = addToPixel(c2, er, 1); Color c3 = getClosestPixel(c2); setPixel(img2, i, j, c3); // oldpixel := pixel[x][y] + threshold_map_4x4[x mod 4][y mod 4] // newpixel := find_closest_palette_color(oldpixel) // pixel[x][y] := newpixel } } return img2; }
@Override public void runFile(String filename, ScriptRunner runner) throws InternalScriptingException { if (!inContext()) { enterContext(); } File fullPath = new File(_scriptsDirectory, filename); FileReader fr = null; try { fr = new FileReader(fullPath); } catch (FileNotFoundException e) { throw new InternalScriptingException("Could not find file"); } try { setScriptRunner(runner); mcJavascriptContext.evaluateReader(mcJavascriptScope, fr, fullPath.getName(), 0, null); setScriptRunner(null); } catch (IOException e) { throw new InternalScriptingException("Error Running file"); } catch (EcmaError e) { throw new InternalScriptingException(e.getMessage()); } catch (EvaluatorException e) { throw new InternalScriptingException(e.getMessage()); } catch (Error e) { throw new InternalScriptingException(e.getMessage()); } if (!inContext()) { exitContext(); } }
private void ActivitiesOfInterest() throws IOException { // Click Activities of Interest driver .findElement( By.xpath( "//ul[@class='vertical-tabs-list']/li/a/strong[contains(text(), \"Activities of Interest\")]")) .click(); // Click Student Newspaper Checkbox // TODO Do not use number in locator driver.findElement(By.xpath("//div[11]/input")).click(); // Click TV Station Checkbox // TODO Do not use number in locator driver.findElement(By.xpath("//div[13]/input")).click(); // Click Apply driver.findElement(By.id("edit-activities-interests-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
@Override public void rollback( PlatformTransactionManager platformTransactionManager, Throwable throwable, TransactionAttribute transactionAttribute, TransactionStatus transactionStatus) throws Throwable { if (transactionAttribute.rollbackOn(throwable)) { try { platformTransactionManager.rollback(transactionStatus); } catch (RuntimeException re) { re.addSuppressed(throwable); _log.error("Application exception overridden by rollback exception", re); throw re; } catch (Error e) { e.addSuppressed(throwable); _log.error("Application exception overridden by rollback error", e); throw e; } } else { commit(platformTransactionManager, transactionAttribute, transactionStatus); } throw throwable; }
public void evaluate() { try { // clear problems and console messages problemsView.setText(""); consoleView.setText(""); // update status view statusView.setText(" Parsing ..."); tabbedPane.setSelectedIndex(0); LispExpr root = Parser.parse(textView.getText()); statusView.setText(" Running ..."); tabbedPane.setSelectedIndex(1); // update run button runButton.setIcon(stopImage); runButton.setActionCommand("Stop"); // start run thread runThread = new RunThread(root); runThread.start(); } catch (SyntaxError e) { tabbedPane.setSelectedIndex(0); System.err.println( "Syntax Error at " + e.getLine() + ", " + e.getColumn() + " : " + e.getMessage()); } catch (Error e) { // parsing error System.err.println(e.getMessage()); statusView.setText(" Errors."); } }
/** * JSON fragment representation of this object * * @return JSON fragment for this object. Name for outer object expected to be set by calling * method. This fragment returns inner properties representation only */ protected String toJSONFragment() { StringBuffer json = new StringBuffer(); boolean first = true; if (isSetAllOfferListingsConsidered()) { if (!first) json.append(", "); json.append(quoteJSON("AllOfferListingsConsidered")); json.append(" : "); json.append(quoteJSON(isAllOfferListingsConsidered() + "")); first = false; } if (isSetProduct()) { if (!first) json.append(", "); json.append("\"Product\" : {"); Product product = getProduct(); json.append(product.toJSONFragment()); json.append("}"); first = false; } if (isSetError()) { if (!first) json.append(", "); json.append("\"Error\" : {"); Error error = getError(); json.append(error.toJSONFragment()); json.append("}"); first = false; } return json.toString(); }
private boolean runPolling() { try { // to make sure that the log file contains up-to-date text, // don't do buffering. StreamTaskListener listener = new StreamTaskListener(getLogFile()); try { PrintStream logger = listener.getLogger(); long start = System.currentTimeMillis(); logger.println("Started on " + DateFormat.getDateTimeInstance().format(new Date())); boolean result = job.poll(listener).hasChanges(); logger.println( "Done. Took " + Util.getTimeSpanString(System.currentTimeMillis() - start)); if (result) logger.println("Changes found"); else logger.println("No changes"); return result; } catch (Error e) { e.printStackTrace(listener.error("Failed to record SCM polling")); LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e); throw e; } catch (RuntimeException e) { e.printStackTrace(listener.error("Failed to record SCM polling")); LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e); throw e; } finally { listener.close(); } } catch (IOException e) { LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e); return false; } }
public void init() { Bus oldbus = BusFactory.getThreadDefaultBus(); BusFactory.setThreadDefaultBus(bus); try { GreeterService service = new GreeterService(GreeterTargetBean.class.getResource("/wsdl/hello_world.wsdl")); greeter = service.getGreeterPort(); if (address != null) { ((BindingProvider) greeter) .getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address); } client = ClientProxy.getClient(greeter); System.out.println("Greeter endpoint: " + client.getEndpoint().getEndpointInfo()); } catch (RuntimeException e) { e.printStackTrace(); throw e; } catch (Error e) { e.printStackTrace(); throw e; } finally { BusFactory.setThreadDefaultBus(oldbus); } }
@ChromeDevtoolsMethod public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) { ExecuteSQLRequest request = mObjectMapper.convertValue(params, ExecuteSQLRequest.class); try { return mDatabasePeerManager.executeSQL( request.databaseId, request.query, new DatabasePeerManager.ExecuteResultHandler<ExecuteSQLResponse>() { @Override public ExecuteSQLResponse handleResult(Cursor result) throws SQLiteException { ExecuteSQLResponse response = new ExecuteSQLResponse(); response.columnNames = Arrays.asList(result.getColumnNames()); response.values = flattenRows(result, MAX_EXECUTE_RESULTS); return response; } }); } catch (SQLiteException e) { Error error = new Error(); error.code = 0; error.message = e.getMessage(); ExecuteSQLResponse response = new ExecuteSQLResponse(); response.sqlError = error; return response; } }
public void testExceptionHandling() { final ComponentAdapter componentAdapter = new ThreadLocalizing.ThreadLocalized( new ConstructorInjection.ConstructorInjector( TargetInvocationExceptionTester.class, ThrowingComponent.class, null)); final TargetInvocationExceptionTester tester = (TargetInvocationExceptionTester) componentAdapter.getComponentInstance(null, ComponentAdapter.NOTHING.class); try { tester.throwsCheckedException(); fail("ClassNotFoundException expected"); } catch (final ClassNotFoundException e) { assertEquals("junit", e.getMessage()); } try { tester.throwsRuntimeException(); fail("RuntimeException expected"); } catch (final RuntimeException e) { assertEquals("junit", e.getMessage()); } try { tester.throwsError(); fail("Error expected"); } catch (final Error e) { assertEquals("junit", e.getMessage()); } }
// All throwable handling. private static void perform(Query query, String string, Action action) { Reader in = new StringReader(string); ARQParser parser = new ARQParser(in); try { query.setStrict(true); parser.setQuery(query); action.exec(parser); } catch (com.hp.hpl.jena.sparql.lang.arq.ParseException ex) { throw new QueryParseException( ex.getMessage(), ex.currentToken.beginLine, ex.currentToken.beginColumn); } catch (com.hp.hpl.jena.sparql.lang.arq.TokenMgrError tErr) { // Last valid token : not the same as token error message - but this should not happen int col = parser.token.endColumn; int line = parser.token.endLine; throw new QueryParseException(tErr.getMessage(), line, col); } catch (QueryException ex) { throw ex; } catch (JenaException ex) { throw new QueryException(ex.getMessage(), ex); } catch (Error err) { // The token stream can throw errors. throw new QueryParseException(err.getMessage(), err, -1, -1); } catch (Throwable th) { Log.warn(ParserSPARQL11.class, "Unexpected throwable: ", th); throw new QueryException(th.getMessage(), th); } }
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 Error error( String symbName, String version, String message, String[][] list, String... headers) { Error error = error(symbName, version, message); error.list = list; error.headers = headers; return error; }
public void run() { ResolvedModuleRevision rmr = null; for (int i = 0; i < loop; i++) { try { rmr = resolveModule(settings, resolver, module); if (rmr == null) { throw new RuntimeException("module not found: " + module); } synchronized (this) { // Message.info(this.toString() + " count = " + count); count++; } } catch (ParseException e) { Message.info("parse exception " + e); } catch (RuntimeException e) { Message.info("exception " + e); e.printStackTrace(); throw e; } catch (Error e) { Message.info("exception " + e); e.printStackTrace(); throw e; } } synchronized (this) { finalResult = rmr; } }
@Test public void testGotoFinalReview() throws Exception { // Goto Final Review page driver.findElement(By.xpath("//a[contains(text(), 'Final Review')]")).click(); try { assertEquals( "Final Review", driver.findElement(By.xpath("//*[@id='container']/h3")).getText()); } catch (Error e) { screenShots.takeScreenShot("gotoFinalReview"); verificationErrors.append(e.toString()); } Thread.sleep(300); // Find where the warning is displayed and scroll it into view, then screenshot it. // We look for 'Scholarship and Sponsorship' since the warning is in the 'Qualifications' area // and the scrolling is causing a heading right where we scroll to and covers it. WebElement elem = driver.findElement(By.xpath("//h4[contains(text(), 'Scholarship and Sponsorship')]")); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elem); Thread.sleep(300); screenShots.takeScreenShot("FinalReviewWarnMsgNoQualifEntrd"); // Go back to application driver.findElement(By.cssSelector("#link_to_application > span")).click(); }
@Override public ReferenceNumberType getByCode(String code) { ReferenceNumberType org = null; try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<ReferenceNumberType> query = builder.createQuery(ReferenceNumberType.class); Root<ReferenceNumberType> rootEntity = query.from(ReferenceNumberType.class); ParameterExpression<String> p = builder.parameter(String.class); query.select(rootEntity).where(builder.equal(rootEntity.get("code"), p)); TypedQuery<ReferenceNumberType> typedQuery = em.createQuery(query); typedQuery.setParameter(p, code); org = typedQuery.getSingleResult(); // TypedQuery<ReferenceNumberType> q = em.createQuery("select o from // com.conx.logistics.mdm.domain.referencenumber.ReferenceNumberType o WHERE o.code = // :code",ReferenceNumberType.class); // q.setParameter("code", code); // org = q.getSingleResult(); } catch (NoResultException e) { } catch (Exception e) { e.printStackTrace(); } catch (Error e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String stacktrace = sw.toString(); logger.error(stacktrace); } return org; }
@Override public void write(final DataOutput out) throws IOException { WritableUtils.writeVInt(out, getNumberOfPointers()); try { this.forEachTerm( new TObjectIntProcedure<String>() { public boolean execute(String term, int freq) { try { Text.writeString(out, term); WritableUtils.writeVInt(out, freq); final int[] blocks = term_blocks.get(term).toArray(); Arrays.sort(blocks); final int bf = blocks.length; WritableUtils.writeVInt(out, bf); if (bf == 0) return true; WritableUtils.writeVInt(out, blocks[0] + 1); for (int i = 1; i < bf; i++) WritableUtils.writeVInt(out, blocks[i] - blocks[i - 1]); } catch (IOException e) { throw new Error(e); } return true; } }); } catch (Error e) { throw (IOException) e.getCause(); } }
private static void writeConfigForTable(BufferedWriter writer, Class<?> clazz) throws SQLException, IOException { String tableName = DatabaseTableConfig.extractTableName(clazz); List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>(); // walk up the classes finding the fields try { for (Class<?> working = clazz; working != null; working = working.getSuperclass()) { for (Field field : working.getDeclaredFields()) { DatabaseFieldConfig fieldConfig = DatabaseFieldConfig.fromField(databaseType, tableName, field); if (fieldConfig != null) { fieldConfigs.add(fieldConfig); } } } } catch (Error e) { System.err.println( "Skipping " + clazz + " because we got an error finding its definition: " + e.getMessage()); return; } if (fieldConfigs.isEmpty()) { System.out.println("Skipping " + clazz + " because no annotated fields found"); return; } @SuppressWarnings({"rawtypes", "unchecked"}) DatabaseTableConfig<?> tableConfig = new DatabaseTableConfig(clazz, tableName, fieldConfigs); DatabaseTableConfigLoader.write(writer, tableConfig); writer.append("#################################"); writer.newLine(); System.out.println("Wrote config for " + clazz); }
@Override public Object runFunction(ScriptRunner runner, IFunction func, Object... args) throws InternalScriptingException { Object ret = null; try { enterContext(); setScriptRunner(runner); if (func instanceof JSFunction) { ((JSFunction) func) .getFunction() .call(mcJavascriptContext, mcJavascriptScope, mcJavascriptScope, args); } else { throw new InternalScriptingException("Invalid Function"); } setScriptRunner(null); } catch (EcmaError e) { throw new InternalScriptingException(e.getMessage()); } catch (EvaluatorException e) { throw new InternalScriptingException(e.getMessage()); } catch (Error e) { throw new InternalScriptingException(e.getMessage()); } finally { exitContext(); } return ret; }
/** * Parses given String str and tries to evaluate it to a GeoFunction Returns null if something * went wrong. Michael Borcherds 2008-04-04 */ public GeoFunction evaluateToFunction(String str, boolean suppressErrors) { boolean oldMacroMode = cons.isSuppressLabelsActive(); cons.setSuppressLabelCreation(true); GeoFunction func = null; try { ValidExpression ve = parser.parseGeoGebraExpression(str); GeoElement[] temp = processValidExpression(ve); if (temp[0].isGeoFunctionable()) { GeoFunctionable f = (GeoFunctionable) temp[0]; func = f.getGeoFunction(); } else if (!suppressErrors) app.showError("InvalidInput", str); } catch (CircularDefinitionException e) { Application.debug("CircularDefinition"); if (!suppressErrors) app.showError("CircularDefinition"); } catch (Exception e) { e.printStackTrace(); if (!suppressErrors) app.showError("InvalidInput", str); } catch (MyError e) { e.printStackTrace(); if (!suppressErrors) app.showError(e); } catch (Error e) { e.printStackTrace(); if (!suppressErrors) app.showError("InvalidInput", str); } cons.setSuppressLabelCreation(oldMacroMode); return func; }
private void SpecialNeeds() throws IOException { // Click Special Needs driver .findElement( By.xpath( "//ul[@class='vertical-tabs-list']/li/a/strong[contains(text(), \"Special Needs\")]")) .click(); // Select Special Needs Select SpecialNeeds = new Select(driver.findElement(By.id("edit-special-needs"))); // Select Learning Center SpecialNeeds.selectByVisibleText("Learning Center"); // Select Early Syllabus SpecialNeeds.selectByVisibleText("Early syllabus"); // Click Apply driver.findElement(By.id("edit-special-needs-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
/** * Parses given String str and tries to evaluate it to a GeoImplicitPoly object. Returns null if * something went wrong. * * @param str * @boolean showErrors if false, only stacktraces are printed * @return implicit polygon or null */ public GeoElement evaluateToGeoElement(String str, boolean showErrors) { boolean oldMacroMode = cons.isSuppressLabelsActive(); cons.setSuppressLabelCreation(true); GeoElement geo = null; try { ValidExpression ve = parser.parseGeoGebraExpression(str); GeoElement[] temp = processValidExpression(ve); geo = temp[0]; } catch (CircularDefinitionException e) { Application.debug("CircularDefinition"); app.showError("CircularDefinition"); } catch (Exception e) { e.printStackTrace(); if (showErrors) app.showError("InvalidInput", str); } catch (MyError e) { e.printStackTrace(); if (showErrors) app.showError(e); } catch (Error e) { e.printStackTrace(); if (showErrors) app.showError("InvalidInput", str); } cons.setSuppressLabelCreation(oldMacroMode); return geo; }
private void Location() throws IOException { // Click Location driver .findElement( By.xpath( "//ul[@class='vertical-tabs-list']/li/a/strong[contains(text(), \"Location\")]")) .click(); // Click West Checkbox // TODO Do not use number in Locator driver.findElement(By.xpath("//fieldset[6]/div/div[4]/div/div[3]/input")).click(); // Click South Checkbox // TODO Do not use number in Locator driver.findElement(By.xpath("//fieldset[6]/div/div[4]/div/div[6]/input")).click(); // Click Apply driver.findElement(By.id("edit-location-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
public static void main(String args[]) throws ParseException { EG1 parser = new EG1(System.in); while (true) { System.out.println("Reading from standard input..."); System.out.print("Enter an expression like \u005c"1+(2+3)*4;\u005c" :"); try { switch (EG1.one_line()) { case 0: System.out.println("OK."); break; case 1: System.out.println("Goodbye."); break; default: break; } } catch (Exception e) { System.out.println("NOK."); System.out.println(e.getMessage()); EG1.ReInit(System.in); } catch (Error e) { System.out.println("Oops."); System.out.println(e.getMessage()); break; } } }
private void AreaOfStudy() throws IOException, InterruptedException { // Click Area of School driver .findElement( By.xpath( "//ul[@class='vertical-tabs-list']/li/a/strong[contains(text(), \"Area of Study\")]")) .click(); // Select One Area Study new Select(driver.findElement(By.id("edit-area-of-study-parent"))) .selectByVisibleText("Area, Ethnic, Cultural, and Gender Studies"); // Wait For Another Select List To Load Thread.sleep(5000); // Select Subareas of Study new Select(driver.findElement(By.xpath("//div[@id='child-area-of-study-wrapper']//select"))) .selectByVisibleText("Area, Ethnic, Cultural, and Gender Studies, Other"); // Click Apply driver.findElement(By.id("edit-area-of-study-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
/** * Returns the bytecode for the specified class. * * @param className the class for which bytecode is to be fetched/generated. * @return the bytecode for the specified class. * @throws ClassNotFoundException */ private byte[] getBytecodeForClassInternal(final String className) throws ClassNotFoundException { final byte[] data; if (shouldLookupClassData()) { // Lookup the class data. if (PERFORM_TIMING) { final long before = System.currentTimeMillis(); data = lookupClassData(className); final long after = System.currentTimeMillis(); lookupClassDataTimeMS += (after - before); } else { data = lookupClassData(className); } } else { // Generate the class data. final int lastPeriodIndex = className.lastIndexOf('.'); if (lastPeriodIndex < 0) { throw new ClassNotFoundException("Unable to find class: " + className); } final String unqualifiedClassName = className.substring(lastPeriodIndex + 1); try { if (PERFORM_TIMING) { final long before = System.currentTimeMillis(); data = LECCJavaBytecodeGenerator.generateClassData(module, unqualifiedClassName); final long after = System.currentTimeMillis(); generateClassDataTimeMS += (after - before); } else { data = LECCJavaBytecodeGenerator.generateClassData(module, unqualifiedClassName); } } catch (final CodeGenerationException e) { // Badness occurred. This is a runtime exception. // -- OR -- // The code generation failed because a foreign type or a foreign function's corresponding // Java entity // could not be resolved. (In this case the CodeGenerationException would be wrapping an // UnableToResolveForeignEntityException) // By throwing a NoClassDefFoundError instead of a ClassNotFoundException, // we ensure that classes in the namespace for cal module packages are not found by other // classloaders. // A ClassNotFoundException will be caught by the calling loadClass() method, which will try // again with the parent classloader. // Imitate behaviour where NoClassDefFoundErrors thrown by the VM have the slashified class // name as the message. final Error error = new NoClassDefFoundError(className.replace('.', '/')); error.initCause(e); throw error; } } return data; }
public void run(String[] args) { String script = null; try { FileInputStream stream = new FileInputStream(new File(args[0])); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); script = Charset.availableCharsets().get("UTF-8").decode(bb).toString(); } finally { stream.close(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } Context cx = Context.enter(); try { ScriptableObject scope = cx.initStandardObjects(); scope.putConst("language", scope, "java"); scope.putConst("platform", scope, "android"); scope.put("util", scope, new Util(cx, scope)); cx.evaluateString(scope, script, args[0], 1, null); } catch (Error ex) { ex.printStackTrace(); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } finally { Context.exit(); } System.exit(0); }
public static void main(String args[]) throws ParseException { pascal parser = new pascal(System.in); while (true) { System.out.println("Reading from standard input..."); System.out.print( "Enter a define like:| VAR myVar , b : INTEGER; myArray : ARRAY[1..5] OF INTEGER; :"); try { switch (pascal.define()) { case 0: System.out.println("OK."); break; case 1: System.out.println("Goodbye."); break; default: break; } } catch (Exception e) { System.out.println("NOK."); System.out.println(e.getMessage()); pascal.ReInit(System.in); } catch (Error e) { System.out.println("Oops."); System.out.println(e.getMessage()); break; } } }