public String determineName(Object thing) { Object name; try { if (thing instanceof Named) { name = ((Named) thing).getName(); } else if (thing instanceof Map) { name = ((Map) thing).get("name"); } else if (thing instanceof GroovyObject) { name = ((GroovyObject) thing).getProperty("name"); } else { name = DynamicObjectUtil.asDynamicObject(thing).getProperty("name"); } } catch (MissingPropertyException e) { throw new NoNamingPropertyException(thing); } if (name == null) { throw new NullNamingPropertyException(thing); } return name.toString(); }
@Override public void setProperty(final String property, final Object newValue) { if (property == null) { throw new MissingPropertyException("null", getClass()); } switch (property) { case "sha": case "url": case "author": case "committer": case "parents": case "message": case "comment_count": case "comments": case "additions": case "deletions": case "total_changes": case "files": case "statuses": throw new ReadOnlyPropertyException(property, getClass()); default: throw new MissingPropertyException(property, getClass()); } }
@Override public void setProperty(final String property, final Object newValue) { if (property == null) { throw new MissingPropertyException("null", getClass()); } switch (property) { case "sha": case "filename": case "status": case "patch": case "additions": case "deletions": case "changes": case "raw_url": case "blob_url": throw new ReadOnlyPropertyException(property, getClass()); default: throw new MissingPropertyException(property, getClass()); } }
@Override public Object getProperty(final String property) { if (property == null) { throw new MissingPropertyException("null", getClass()); } switch (property) { case "id": return comment.getId(); case "url": return comment.getUrl(); case "user": return GitHubHelper.userToLogin(comment.getUser()); case "body": return comment.getBody(); case "created_at": return comment.getCreatedAt(); case "updated_at": return comment.getUpdatedAt(); default: throw new MissingPropertyException(property, getClass()); } }
@Override public void setProperty(final String property, final Object newValue) { if (property == null) { throw new MissingPropertyException("null", getClass()); } switch (property) { case "id": case "url": case "user": case "created_at": case "updated_at": throw new ReadOnlyPropertyException(property, getClass()); case "body": setBody(newValue.toString()); break; default: throw new MissingPropertyException(property, getClass()); } }
@Override public void setProperty(final String property, final Object newValue) { if (property == null) { throw new MissingPropertyException("null", getClass()); } switch (property) { case "id": case "url": case "status": case "context": case "description": case "target_url": case "created_at": case "updated_at": case "creator": throw new ReadOnlyPropertyException(property, getClass()); default: throw new MissingPropertyException(property, getClass()); } }
/** * Result {@code null} means that there is no variable. Result other than {@code null} means that there is a variable (that may possibly * be {@code null}). * * @param name the name of the variable. * @return a holder for a variable. */ protected Mutable<Object> doGetVariable(String name) { List<Object> variables = scripts.stream().filter(script -> script.getMetaClass().hasProperty(script.getMetaClass().getTheClass(), name) != null) .map(script -> script.getProperty(name)).collect(Collectors.toList()); if (variables.isEmpty()) { try { return new MutableObject<>(binding.getProperty(name)); } catch (MissingPropertyException e) { return null; // This means that no variable has been found! } } return new MutableObject<>(variables.get(0)); }
@TaskAction public void danGenerateEntity() { try { String entities = (String) this.getProject().property("entities"); if (entities != null) { for(String entity: Arrays.asList(entities.split(","))) { new DanConsole().generateEntity(entity); } } else { throw new MissingPropertyException(""); } } catch (MissingPropertyException e) { System.err.println(USAGE); throw e; } }
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldClearBindingsBetweenEvals() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); try { engine.eval("g.V().has('name',s).next()"); fail("This should have failed because s is no longer bound"); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals(MissingPropertyException.class, t.getClass()); assertTrue(t.getMessage().startsWith("No such property: s for class")); } }
@Test public void shouldNotPreserveInstantiatedVariablesBetweenEvals() throws Exception { final ScriptEngines engines = new ScriptEngines(se -> {}); engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.emptyMap()); final Bindings localBindingsFirstRequest = new SimpleBindings(); localBindingsFirstRequest.put("x", "there"); assertEquals("herethere", engines.eval("z = 'here' + x", localBindingsFirstRequest, "gremlin-groovy")); try { final Bindings localBindingsSecondRequest = new SimpleBindings(); engines.eval("z", localBindingsSecondRequest, "gremlin-groovy"); fail("Should not have knowledge of z"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } }
@Test public void shouldPromoteDefinedVarsInInterpreterModeWithNoBindings() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeCustomizerProvider()); engine.eval("def addItUp = { x, y -> x + y }"); assertEquals(3, engine.eval("int xxx = 1 + 2")); assertEquals(4, engine.eval("yyy = xxx + 1")); assertEquals(7, engine.eval("def zzz = yyy + xxx")); assertEquals(4, engine.eval("zzz - xxx")); assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer")); assertEquals("accessible-globally", engine.eval("outer")); try { engine.eval("inner"); fail("Should not have been able to access 'inner'"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } assertEquals(10, engine.eval("addItUp(zzz,xxx)")); }
@Test public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeCustomizerProvider()); final Bindings b = new SimpleBindings(); b.put("x", 2); engine.eval("def addItUp = { x, y -> x + y }", b); assertEquals(3, engine.eval("int xxx = 1 + x", b)); assertEquals(4, engine.eval("yyy = xxx + 1", b)); assertEquals(7, engine.eval("def zzz = yyy + xxx", b)); assertEquals(4, engine.eval("zzz - xxx", b)); assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b)); assertEquals("accessible-globally", engine.eval("outer", b)); try { engine.eval("inner", b); fail("Should not have been able to access 'inner'"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } assertEquals(10, engine.eval("addItUp(zzz,xxx)", b)); }
/** * Error hook installed to Groovy shell. * * Will display exception that appeared during executing command. In most * cases we will simply delegate the call to printing throwable method, * however in case that we've received ClientError.CLIENT_0006 (server * exception), we will unwrap server issue and view only that as local * context shouldn't make any difference. * * @param t Throwable to be displayed */ public static void errorHook(Throwable t) { // Based on the kind of exception we are dealing with, let's provide different user experince if(t instanceof SqoopException && ((SqoopException)t).getErrorCode() == ShellError.SHELL_0006) { println("@|red Server has returned exception: |@"); printThrowable(t.getCause(), isVerbose()); } else if(t instanceof SqoopException && ((SqoopException)t).getErrorCode() == ShellError.SHELL_0003) { print("@|red Invalid command invocation: |@"); // In most cases the cause will be actual parsing error, so let's print that alone if (t.getCause() != null) { println(t.getCause().getMessage()); } else { println(t.getMessage()); } } else if(t.getClass() == MissingPropertyException.class) { print("@|red Unknown command: |@"); println(t.getMessage()); } else { println("@|red Exception has occurred during processing command |@"); printThrowable(t, isVerbose()); } }
/** * Retrieve the value of the property by its index. * A negative index will count backwards from the last column. * * @param index is the number of the column to look at * @return the value of the property */ public Object getAt(int index) { try { // a negative index will count backwards from the last column. if (index < 0) index += result.size(); Iterator it = result.values().iterator(); int i = 0; Object obj = null; while ((obj == null) && (it.hasNext())) { if (i == index) obj = it.next(); else it.next(); i++; } return obj; } catch (Exception e) { throw new MissingPropertyException(Integer.toString(index), GroovyRowResult.class, e); } }
private Object extractNewValue(Object newObject) { Object newValue; try { newValue = InvokerHelper.getProperty(newObject, propertyName); } catch (MissingPropertyException mpe) { //todo we should flag this when the path is created that this is a field not a prop... // try direct method... try { newValue = InvokerHelper.getAttribute(newObject, propertyName); if (newValue instanceof Reference) { newValue = ((Reference) newValue).get(); } } catch (Exception e) { //LOGME? newValue = null; } } return newValue; }
/** * Overloaded to make variables appear as bean properties or via the subscript operator */ public Object getProperty(String property) { try { return getProxyBuilder().doGetProperty(property); } catch (MissingPropertyException mpe) { if ((getContext() != null) && (getContext().containsKey(property))) { return getContext().get(property); } else { try { return getMetaClass().getProperty(this, property); } catch(MissingPropertyException mpe2) { if(mpe2.getProperty().equals(property) && propertyMissingDelegate != null) { return propertyMissingDelegate.call(new Object[]{property}); } throw mpe2; } } } }
private void addPropertiesToProject(Project project) { Properties projectProperties = new Properties(); File projectPropertiesFile = new File(project.getProjectDir(), Project.GRADLE_PROPERTIES); LOGGER.debug("Looking for project properties from: {}", projectPropertiesFile); if (projectPropertiesFile.isFile()) { projectProperties = GUtil.loadProperties(projectPropertiesFile); LOGGER.debug("Adding project properties (if not overwritten by user properties): {}", projectProperties.keySet()); } else { LOGGER.debug("project property file does not exists. We continue!"); } Map<String, String> mergedProperties = propertiesLoader.mergeProperties(new HashMap(projectProperties)); ExtraPropertiesExtension extraProperties = new DslObject(project).getExtensions().getExtraProperties(); for (Map.Entry<String, String> entry: mergedProperties.entrySet()) { try { project.setProperty(entry.getKey(), entry.getValue()); } catch (MissingPropertyException e) { if (!entry.getKey().equals(e.getProperty())) { throw e; } // Ignore and define as an extra property extraProperties.set(entry.getKey(), entry.getValue()); } } }
@Test public void shouldClearBindingsBetweenEvals() throws Exception { final Graph graph = TinkerFactory.createModern(); final GraphTraversalSource g = graph.traversal(); final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId(graph, "marko")); assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next()); try { engine.eval("g.V().has('name',s).next()"); fail("This should have failed because s is no longer bound"); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals(MissingPropertyException.class, t.getClass()); assertTrue(t.getMessage().startsWith("No such property: s for class")); } }
@Test public void shouldPromoteDefinedVarsInInterpreterModeWithNoBindings() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeGroovyCustomizer()); engine.eval("def addItUp = { x, y -> x + y }"); assertEquals(3, engine.eval("int xxx = 1 + 2")); assertEquals(4, engine.eval("yyy = xxx + 1")); assertEquals(7, engine.eval("def zzz = yyy + xxx")); assertEquals(4, engine.eval("zzz - xxx")); assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer")); assertEquals("accessible-globally", engine.eval("outer")); try { engine.eval("inner"); fail("Should not have been able to access 'inner'"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } assertEquals(10, engine.eval("addItUp(zzz,xxx)")); }
@Test public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeGroovyCustomizer()); final Bindings b = new SimpleBindings(); b.put("x", 2); engine.eval("def addItUp = { x, y -> x + y }", b); assertEquals(3, engine.eval("int xxx = 1 + x", b)); assertEquals(4, engine.eval("yyy = xxx + 1", b)); assertEquals(7, engine.eval("def zzz = yyy + xxx", b)); assertEquals(4, engine.eval("zzz - xxx", b)); assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b)); assertEquals("accessible-globally", engine.eval("outer", b)); try { engine.eval("inner", b); fail("Should not have been able to access 'inner'"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } assertEquals(10, engine.eval("addItUp(zzz,xxx)", b)); }
private static boolean hasProperty(Object object, String property) { if (InvokerHelper.getMetaClass(object).hasProperty(object, property) != null) { return true; } // The only way to be sure whether something is handled as a property in // Groovy is to actually get it and catch a MissingPropertyException. // But this actually accesses the property (-> side effects?)! // Here this is no problem, since we only disallow some write access... // The only allowed class with side effects should be InstanceAccessor, // which is in "allAllowedClasses" and thus shouldn't reach here try { InvokerHelper.getProperty(object, property); return true; } catch (MissingPropertyException e) { return false; } }
@Override public Object getProperty(String property) { if (property.equals("name")) { return getName(); } if (property.equals("displayName")) { return getDisplayName(); } I element = get(property); if (element == null) { throw new MissingPropertyException(property, ModelMap.class); } return element; }
public Object propertyMissing(final String name) { if (suiteXmlBuilder != null) { return suiteXmlBuilder.getMetaClass().getProperty(suiteXmlBuilder, name); } throw new MissingPropertyException(name, getClass()); }
public Object propertyMissing(String name) { if (getProject().getProperties().containsKey(name)) { return getProject().getProperties().get(name); } throw new MissingPropertyException(name, getClass()); }
public void propertyMissing(String name, Object value) { if (value instanceof Closure) { map(name, (Closure) value); } else { throw new MissingPropertyException(name, getClass()); } }
public Object getProperty(String name) { if (name.equals("properties")) { return getProperties(); } if (storage.containsKey(name)) { return storage.get(name); } else { throw new MissingPropertyException(UnknownPropertyException.createMessage(name), name, null); } }
@Override public Object getProperty(String name) throws MissingPropertyException { GetPropertyResult result = new GetPropertyResult(); getProperty(name, result); if (!result.isFound()) { throw getMissingProperty(name); } return result.getValue(); }
@Override public void setProperty(String name, Object value) throws MissingPropertyException { SetPropertyResult result = new SetPropertyResult(); setProperty(name, value, result); if (!result.isFound()) { throw setMissingProperty(name); } }
public MissingPropertyException getMissingProperty(String name) { Class<?> publicType = getPublicType(); boolean includeDisplayName = hasUsefulDisplayName(); if (publicType != null && includeDisplayName) { return new MissingPropertyException(String.format("Could not get unknown property '%s' for %s of type %s.", name, getDisplayName(), publicType.getName()), name, publicType); } else if (publicType != null) { return new MissingPropertyException(String.format("Could not get unknown property '%s' for object of type %s.", name, publicType.getName()), name, publicType); } else { // Use the display name anyway return new MissingPropertyException(String.format("Could not get unknown property '%s' for %s.", name, getDisplayName()), name, null); } }
public MissingPropertyException setMissingProperty(String name) { Class<?> publicType = getPublicType(); boolean includeDisplayName = hasUsefulDisplayName(); if (publicType != null && includeDisplayName) { return new MissingPropertyException(String.format("Could not set unknown property '%s' for %s of type %s.", name, getDisplayName(), publicType.getName()), name, publicType); } else if (publicType != null) { return new MissingPropertyException(String.format("Could not set unknown property '%s' for object of type %s.", name, publicType.getName()), name, publicType); } else { // Use the display name anyway return new MissingPropertyException(String.format("Could not set unknown property '%s' for %s.", name, getDisplayName()), name, null); } }
@Override public Object getProperty(final String property) { if (property == null) { throw new MissingPropertyException("null", this.getClass()); } switch (property) { case "id": return commitComment.getId(); case "url": return commitComment.getUrl(); case "user": return GitHubHelper.userToLogin(commitComment.getUser()); case "created_at": return commitComment.getCreatedAt(); case "updated_at": return commitComment.getUpdatedAt(); case "commit_id": return commitComment.getCommitId(); case "original_commit_id": return commitComment.getOriginalCommitId(); case "body": return commitComment.getBody(); case "path": return commitComment.getPath(); case "line": return commitComment.getLine(); case "position": return commitComment.getPosition(); case "original_position": return commitComment.getPosition(); case "diff_hunk": return commitComment.getDiffHunk(); default: throw new MissingPropertyException(property, this.getClass()); } }
@Override public void setProperty(final String property, final Object newValue) { if (property == null) { throw new MissingPropertyException("null", this.getClass()); } switch (property) { case "id": case "url": case "user": case "created_at": case "updated_at": case "commit_id": case "original_commit_id": case "path": case "line": case "position": case "original_position": case "diff_hunk": throw new ReadOnlyPropertyException(property, getClass()); case "body": Objects.requireNonNull(newValue, "body cannot be null"); setBody(newValue.toString()); break; default: throw new MissingPropertyException(property, this.getClass()); } }
@Override public Object getProperty(final String property) { if (property == null) { throw new MissingPropertyException("null", this.getClass()); } switch (property) { case "sha": return commit.getSha(); case "url": return commit.getUrl(); case "author": return commit.getAuthor().getLogin(); case "committer": return commit.getCommitter().getLogin(); case "parents": return getParents(); case "message": return commit.getCommit().getMessage(); case "comment_count": return commit.getCommit().getCommentCount(); case "comments": return getComments(); case "additions": return commit.getStats().getAdditions(); case "deletions": return commit.getStats().getDeletions(); case "total_changes": return commit.getStats().getTotal(); case "files": return getFiles(); case "statuses": return getStatuses(); default: throw new MissingPropertyException(property, this.getClass()); } }
@Override public Object getProperty(final String property) { if (property == null) { throw new MissingPropertyException("null", this.getClass()); } switch (property) { case "sha": return file.getSha(); case "filename": return file.getFilename(); case "status": return file.getStatus(); case "patch": return file.getPatch(); case "additions": return file.getAdditions(); case "deletions": return file.getDeletions(); case "changes": return file.getChanges(); case "raw_url": return file.getRawUrl(); case "blob_url": return file.getBlobUrl(); default: throw new MissingPropertyException(property, this.getClass()); } }
@Override public Object getProperty(final String property) { if (property == null) { throw new MissingPropertyException("null", this.getClass()); } switch (property) { case "id": return commitStatus.getId(); case "url": return commitStatus.getUrl(); case "status": return commitStatus.getState(); case "context": return commitStatus.getContext(); case "description": return commitStatus.getDescription(); case "target_url": return commitStatus.getTargetUrl(); case "created_at": return commitStatus.getCreatedAt(); case "updated_at": return commitStatus.getUpdatedAt(); case "creator": return commitStatus.getCreator().getLogin(); default: throw new MissingPropertyException(property, this.getClass()); } }
private EclipseModel eclipseModel(Project project) { try { return (EclipseModel) project.property("eclipse"); } catch (MissingPropertyException e) { throw new RuntimeException( "Cannot find 'eclipse' property.\nEnsure that the following is in your project: \n\napply plugin: 'eclipse'\n\n", e); } }
@Override public final Object getProperty(String property) { if (!dynamicProperties.containsKey(property)) { throw new MissingPropertyException(property); } return dynamicProperties.get(property); }
@TaskAction public void danGenerateView() { try { String argUiName = (String) this.getProject().property("uiName"); String argViewName = (String) this.getProject().property("viewName"); if (argUiName != null && argViewName != null) { new DanConsole().generateView(argUiName, argViewName); } else { throw new MissingPropertyException(""); } } catch (MissingPropertyException e) { System.err.println(USAGE); throw e; } }
@TaskAction public void danGenerateUi() { try { String argUiName = (String) this.getProject().property("uiName"); if (argUiName != null) { new DanConsole().generateUi(argUiName); } else { throw new MissingPropertyException(""); } } catch (MissingPropertyException e) { System.err.println(USAGE); throw e; } }
@Deployment public void testFailingScript() { Exception expectedException = null; try { runtimeService.startProcessInstanceByKey("failingScript"); } catch (Exception e) { expectedException = e; } // Check if correct exception is found in the stacktrace verifyExceptionInStacktrace(expectedException, MissingPropertyException.class); }