@Before @Override public void beforeTest() throws Exception { super.beforeTest(); initializeJavaProject(); // setup validation queueInputLines("", ""); getShell().execute(VALIDATION_PLUGIN_NAME + " setup"); // create a class assertTrue(getProject().hasFacet(JavaSourceFacet.class)); final JavaSourceFacet javaSourceFacet = getProject().getFacet(JavaSourceFacet.class); assertNotNull(javaSourceFacet); final JavaClass fooClass = JavaParser.create(JavaClass.class) .setPackage(javaSourceFacet.getBasePackage()) .setName(CLASS_NAME); fooClass.addField("private String " + PROPERTY_NAME + ";"); fooClass.addMethod("public String " + PROPERTY_ACESSOR_NAME + "(){return foo;}"); JavaResource fooResource = javaSourceFacet.saveJavaSource(fooClass); assertNotNull(fooResource); // pick-up the created resource getShell().execute("pick-up " + fooResource.getFullyQualifiedName()); }
@Test public void testAddPatternConstraint() throws Exception { final String message = "Message"; getShell() .execute( CONSTRAINT_PLUGIN_NAME + " Pattern --onProperty " + PROPERTY_NAME + " --regexp [a-z]* --message " + message); getShell() .execute( CONSTRAINT_PLUGIN_NAME + " Pattern --onProperty " + PROPERTY_NAME + " --regexp [a-z]* --onAccessor"); final JavaClass fooClass = getJavaClassFromResource(getShell().getCurrentResource()); final Field<JavaClass> property = fooClass.getField(PROPERTY_NAME); assertNotNull(property); assertTrue(property.hasAnnotation(Pattern.class)); assertEquals("[a-z]*", property.getAnnotation(Pattern.class).getStringValue("regexp")); assertEquals(message, property.getAnnotation(Pattern.class).getStringValue("message")); assertEquals(null, property.getAnnotation(Pattern.class).getStringValue("flags")); final Method<JavaClass> accessor = fooClass.getMethod(PROPERTY_ACESSOR_NAME); assertNotNull(accessor); assertTrue(accessor.hasAnnotation(Pattern.class)); assertEquals("[a-z]*", accessor.getAnnotation(Pattern.class).getStringValue("regexp")); }
@Test public void testAddDigitsConstraint() throws Exception { final String message = "Message"; getShell() .execute( CONSTRAINT_PLUGIN_NAME + " Digits --onProperty " + PROPERTY_NAME + " --integer 3 --fraction 4 --message " + message); getShell() .execute( CONSTRAINT_PLUGIN_NAME + " Digits --onProperty " + PROPERTY_NAME + " --integer 4 --fraction 3 --onAccessor"); final JavaClass fooClass = getJavaClassFromResource(getShell().getCurrentResource()); final Field<JavaClass> property = fooClass.getField(PROPERTY_NAME); assertNotNull(property); assertTrue(property.hasAnnotation(Digits.class)); assertEquals("3", property.getAnnotation(Digits.class).getLiteralValue("integer")); assertEquals("4", property.getAnnotation(Digits.class).getLiteralValue("fraction")); assertEquals(message, property.getAnnotation(Digits.class).getStringValue("message")); final Method<JavaClass> accessor = fooClass.getMethod(PROPERTY_ACESSOR_NAME); assertNotNull(accessor); assertTrue(accessor.hasAnnotation(Digits.class)); assertEquals("4", accessor.getAnnotation(Digits.class).getLiteralValue("integer")); assertEquals("3", accessor.getAnnotation(Digits.class).getLiteralValue("fraction")); }
@Override public boolean install() { if (!isInstalled()) { JavaSourceFacet javaSourceFacet = project.getFacet(JavaSourceFacet.class); JavaClass applicationClass = JavaParser.create(JavaClass.class) .setPackage(classPackage) .setName(className) .setSuperType("javax.ws.rs.core.Application") .addAnnotation("javax.ws.rs.ApplicationPath") .setStringValue(rootPath) .getOrigin(); applicationClass.addImport("javax.ws.rs.core.Application"); applicationClass.addImport("javax.ws.rs.ApplicationPath"); try { javaSourceFacet.saveJavaSource(applicationClass); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } return true; }
@Command(value = "new-page", help = "Create a new Graphene page element class") public void createTest( @Option( required = false, help = "the package in which to build this page class", description = "source package", type = PromptType.JAVA_PACKAGE, name = "package") final String packageName, @Option(required = true, name = "named", help = "the page class name") String name, @Option( required = false, name = "type", help = "Page Object or Page Fragment", defaultValue = "page") PageType type, final PipeOut out) throws Exception { if (PageType.page.equals(type) && !name.endsWith("Page")) { name = name + "Page"; } if (PageType.fragment.equals(type) && !name.endsWith("Fragment")) { name = name + "Fragment"; } final JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); String pagePackage; if ((packageName != null) && !"".equals(packageName)) { pagePackage = packageName; } else if (getPackagePortionOfCurrentDirectory() != null) { pagePackage = getPackagePortionOfCurrentDirectory(); } else { pagePackage = shell.promptCommon( "In which package you'd like to create this Page, or enter for default", PromptType.JAVA_PACKAGE, java.getBasePackage() + ".pages"); } JavaClass javaClass = JavaParser.create(JavaClass.class).setPackage(pagePackage).setName(name).setPublic(); if (PageType.fragment.equals(type)) { Field<JavaClass> field = javaClass.addField(); field .setName("root") .setPrivate() .setType("org.openqa.selenium.WebElement") .addAnnotation("org.jboss.arquillian.graphene.spi.annotations.Root"); } JavaResource javaFileLocation = java.saveTestJavaSource(javaClass); shell.println("Created " + type + " [" + javaClass.getQualifiedName() + "]"); pickup.fire(new PickupResource(javaFileLocation)); }
@Test public void testAddSizeConstraintWithMinMax() throws Exception { getShell() .execute( CONSTRAINT_PLUGIN_NAME + " Size --onProperty " + PROPERTY_NAME + " --min 0 --max 3"); final JavaClass fooClass = getJavaClassFromResource(getShell().getCurrentResource()); final Field<JavaClass> property = fooClass.getField(PROPERTY_NAME); assertNotNull(property); assertTrue(property.hasAnnotation(Size.class)); assertEquals("0", property.getAnnotation(Size.class).getLiteralValue("min")); assertEquals("3", property.getAnnotation(Size.class).getLiteralValue("max")); }
@Command("new-class") public void newClass( @PipeIn final InputStream in, @Option( required = false, help = "the package in which to build this Class", description = "source package", type = PromptType.JAVA_PACKAGE, name = "package") final String pckg, @Option( required = false, help = "the class definition: surround with quotes", description = "class definition") final String... def) throws FileNotFoundException { JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); JavaClass jc = null; if (def != null) { String classDef = Strings.join(Arrays.asList(def), " "); jc = JavaParser.parse(JavaClass.class, classDef); } else if (in != null) { jc = JavaParser.parse(JavaClass.class, in); } else { throw new RuntimeException("arguments required"); } if (pckg != null) { jc.setPackage(pckg); } if (!jc.hasSyntaxErrors()) { java.saveJavaSource(jc); } else { writer.println(ShellColor.RED, "Syntax Errors:"); for (SyntaxError error : jc.getSyntaxErrors()) { writer.println(error.toString()); } writer.println(); if (prompt.promptBoolean("Your class has syntax errors, create anyway?", true)) { java.saveJavaSource(jc); } } pickUp.fire(new PickupResource(java.getJavaResource(jc))); }
/** Recursive lookup for properties from superclass in order to support inheritance */ private void inspectClassProperties(final String type, Map<String, Property> properties) { JavaSource<?> clazz = sourceForName(this.project, type); if (clazz instanceof MethodHolder<?>) { lookupGetters(properties, (MethodHolder<?>) clazz); lookupSetters(properties, (MethodHolder<?>) clazz); if (clazz instanceof JavaClass) { JavaClass source = JavaParser.parse(JavaClass.class, clazz.toString()); if (!source.getSuperType().equals("java.lang.Object")) { inspectClassProperties(source.getSuperType(), properties); } } } }
@Test public void testAddValidConstraint() throws Exception { getShell().execute(CONSTRAINT_PLUGIN_NAME + " Valid --onProperty " + PROPERTY_NAME); getShell() .execute(CONSTRAINT_PLUGIN_NAME + " Valid --onProperty " + PROPERTY_NAME + " --onAccessor"); final JavaClass fooClass = getJavaClassFromResource(getShell().getCurrentResource()); final Field<JavaClass> property = fooClass.getField(PROPERTY_NAME); assertNotNull(property); assertTrue(property.hasAnnotation(Valid.class)); final Method<JavaClass> accessor = fooClass.getMethod(PROPERTY_ACESSOR_NAME); assertNotNull(accessor); assertTrue(accessor.hasAnnotation(Valid.class)); }
@Override public void validate(UIValidationContext validator) { boolean overwriteValue = overwrite.getValue() != null && overwrite.getValue(); JavaResource resource = (JavaResource) validator.getUIContext().getInitialSelection().get(); JavaClass javaClass; if (!overwriteValue) { try { String fieldName = conversationFieldName.getValue(); String beginName = beginMethodName.getValue(); String endName = endMethodName.getValue(); javaClass = (JavaClass) resource.getJavaSource(); if (javaClass.hasField(fieldName) && !javaClass.getField(fieldName).isType(Conversation.class)) { validator.addValidationError( conversationFieldName, "Field [" + fieldName + "] already exists."); } if (javaClass.hasMethodSignature(beginName) && (javaClass.getMethod(beginName).getParameters().size() == 0)) { validator.addValidationError(beginMethodName, "Method [" + beginName + "] exists."); } if (javaClass.hasMethodSignature(endName) && (javaClass.getMethod(endName).getParameters().size() == 0)) { validator.addValidationError(endMethodName, "Method [" + endName + "] exists."); } } catch (FileNotFoundException e) { validator.addValidationError(null, "The selected resource file was not found"); } } }
@Override public List<String> getCompletionTokens() { final List<String> tokens = new ArrayList<String>(); final Resource<?> currentResource = shell.getCurrentResource(); try { final JavaClass javaClass = getJavaClassFromResource(currentResource); for (Field<JavaClass> oneField : javaClass.getFields()) { tokens.add(oneField.getName()); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } return tokens; }
private void createHashCodeAndEquals(final JavaClass javaClass) { javaClass .addMethod( "public boolean equals(Object that) { " + "if (this == that) { return true; } " + "if (that == null) { return false; } " + "if (getClass() != that.getClass()) { return false; } " + "if (id != null) { return id.equals(((" + javaClass.getName() + ") that).id); } " + "return super.equals(that); " + "}") .addAnnotation(Override.class); javaClass .addMethod( "public int hashCode() { " + "if (id != null) { return id.hashCode(); } " + "return super.hashCode(); }") .addAnnotation(Override.class); }
@Test public void testCreateEndpoint() throws Exception { Project project = getProject(); JavaClass entity = generateEntity(project, null, "User"); assertFalse(entity.hasAnnotation(XmlRootElement.class)); setupRest(); queueInputLines(""); getShell().execute("rest endpoint-from-entity"); JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); JavaResource resource = java.getJavaResource(java.getBasePackage() + ".rest.UserEndpoint"); JavaClass endpoint = (JavaClass) resource.getJavaSource(); assertEquals("/user", endpoint.getAnnotation(Path.class).getStringValue()); assertEquals("java.util.List", endpoint.getMethod("listAll").getQualifiedReturnType()); Method<JavaClass> method = endpoint.getMethod("findById", Long.class); Type<JavaClass> returnTypeInspector = method.getReturnTypeInspector(); assertEquals( "com.test." + PersistenceFacetImpl.DEFAULT_ENTITY_PACKAGE + ".User", returnTypeInspector.getQualifiedName()); assertTrue(java.getJavaResource(entity).getJavaSource().hasAnnotation(XmlRootElement.class)); getShell().execute("build"); }
@Test public void testCreateEndpointPrimitiveNonStandardGetterId() throws Exception { Project project = getProject(); JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); JavaClass entity = JavaParser.parse(JavaClass.class, RestPluginTest.class.getResourceAsStream("User3.java")); entity.setPackage(java.getBasePackage() + ".model"); java.saveJavaSource(entity); getShell().setCurrentResource(java.getJavaResource(entity)); setupRest(); queueInputLines(""); getShell().execute("rest endpoint-from-entity"); JavaResource resource = java.getJavaResource(java.getBasePackage() + ".rest.User3Endpoint"); JavaClass endpoint = (JavaClass) resource.getJavaSource(); assertEquals("/user3", endpoint.getAnnotation(Path.class).getStringValue()); assertTrue(endpoint.toString().contains("entity.setObjectId(id);")); getShell().execute("build"); }
public List<String> searchForAllResourcesFQN(String sourcePackage, boolean recursive) { try { System.out.println("recursive ?: " + recursive); List<String> resourcesFQNs = new ArrayList<String>(); // get resource Files List<File> resources = recursive == true ? this.searchForAllResourcesRecursive(sourcePackage) : this.searchForAllResources(sourcePackage); System.out.println("resourcesFQN: " + resources); // make sure all resources exist and are Java Types for (File file : resources) { JavaClass js = JavaParser.parse(JavaClass.class, file); if (js != null) { resourcesFQNs.add(js.getQualifiedName()); } } return resourcesFQNs; } catch (Exception e) { e.printStackTrace(); return null; } }
@Command(value = "new-element", help = "Create a new WebElement in the current class") public void newElement( @Option(required = true, name = "named", help = "the element name") String name, @Option(required = true, name = "findby", help = "the locator name") FindByType findBy, @Option(required = true, name = "value", help = "the locator value") String value, @Option(required = false, name = "fragmentClass", help = "the Page Fragment class") Resource<?> fragmentClass, final PipeOut out) throws Exception { final JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); JavaClass javaClass = getJavaClass(); if (javaClass.hasField(name)) { throw new IllegalStateException("Class already has a field named [" + name + "]"); } Field<JavaClass> field = javaClass.addField(); field.setName(name).setPrivate(); if (fragmentClass != null) { JavaClass javaFragment = JavaParser.parse(JavaClass.class, fragmentClass.getResourceInputStream()); if (javaFragment == null) { throw new IllegalStateException( "Class notfound in test resources [" + fragmentClass.getFullyQualifiedName() + "]"); } field.setType(javaFragment.getQualifiedName()); } else { field.setType("org.openqa.selenium.WebElement"); } Annotation<JavaClass> annotation = field.addAnnotation("org.jboss.arquillian.graphene.enricher.findby.FindBy"); annotation.setStringValue(findBy.name(), value); javaClass .addMethod() .setReturnType(field.getTypeInspector().toString()) .setName("get" + Strings.capitalize(name)) .setPublic() .setBody("return this." + name + ";"); java.saveTestJavaSource(javaClass); shell.println("Created element [" + field.getName() + "]"); }
@Override public Result execute(UIExecutionContext context) throws Exception { UIContext uiContext = context.getUIContext(); JavaResource resource = (JavaResource) uiContext.getInitialSelection().get(); String name = named.getValue(); String fieldName = conversationFieldName.getValue(); String beginName = beginMethodName.getValue(); String endName = endMethodName.getValue(); Boolean overwriteValue = overwrite.getValue(); UIOutput output = uiContext.getProvider().getOutput(); if (resource.exists()) { if (resource.getJavaSource().isClass()) { JavaClass javaClass = (JavaClass) resource.getJavaSource(); if (javaClass.hasField(fieldName) && !javaClass.getField(fieldName).isType(Conversation.class)) { if (overwriteValue) { javaClass.removeField(javaClass.getField(fieldName)); } else { return Results.fail("Field [" + fieldName + "] already exists."); } } if (javaClass.hasMethodSignature(beginName) && (javaClass.getMethod(beginName).getParameters().size() == 0)) { if (overwriteValue) { javaClass.removeMethod(javaClass.getMethod(beginName)); } else { return Results.fail("Method [" + beginName + "] exists."); } } if (javaClass.hasMethodSignature(endName) && (javaClass.getMethod(endName).getParameters().size() == 0)) { if (overwriteValue) { javaClass.removeMethod(javaClass.getMethod(endName)); } else { return Results.fail("Method [" + endName + "] exists."); } } javaClass .addField() .setPrivate() .setName(fieldName) .setType(Conversation.class) .addAnnotation(Inject.class); Method<JavaClass> beginMethod = javaClass.addMethod().setName(beginName).setReturnTypeVoid().setPublic(); if (Strings.isNullOrEmpty(name)) { beginMethod.setBody(fieldName + ".begin();"); } else { beginMethod.setBody(fieldName + ".begin(\"" + name + "\");"); } if (timeout.getValue() != null) { beginMethod.setBody( beginMethod.getBody() + "\n" + fieldName + ".setTimeout(" + timeout + ");"); } javaClass .addMethod() .setName(endName) .setReturnTypeVoid() .setPublic() .setBody(fieldName + ".end();"); if (javaClass.hasSyntaxErrors()) { output.err().println("Modified Java class contains syntax errors:"); for (SyntaxError error : javaClass.getSyntaxErrors()) { output.err().print(error.getDescription()); } } resource.setContents(javaClass); } else { return Results.fail( "Must operate on a Java Class file, not an [" + resource.getJavaSource().getSourceType() + "]"); } } return Results.success("Conversation block created"); }
@Override public JavaResource getTestJavaResource(final JavaClass javaClass) throws FileNotFoundException { return getTestJavaResource(javaClass.getPackage() + "." + javaClass.getName()); }
@SuppressWarnings("unchecked") @DefaultCommand(help = "Create a JPA @Entity") public void newEntity( @Option(required = true, name = "named", description = "The @Entity name") final String entityName, @Option( required = false, name = "package", type = PromptType.JAVA_PACKAGE, description = "The package name") final String packageName) throws Throwable { final PersistenceFacet jpa = project.getFacet(PersistenceFacet.class); final JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); String entityPackage; if ((packageName != null) && !"".equals(packageName)) { entityPackage = packageName; } else if (getPackagePortionOfCurrentDirectory() != null) { entityPackage = getPackagePortionOfCurrentDirectory(); } else { entityPackage = shell.promptCommon( "In which package you'd like to create this @Entity, or enter for default", PromptType.JAVA_PACKAGE, jpa.getEntityPackage()); } JavaClass javaClass = JavaParser.create(JavaClass.class) .setPackage(entityPackage) .setName(entityName) .setPublic() .addAnnotation(Entity.class) .getOrigin() .addInterface(Serializable.class); Field<JavaClass> id = javaClass.addField("private Long id = null;"); id.addAnnotation(Id.class); id.addAnnotation(GeneratedValue.class).setEnumValue("strategy", GenerationType.AUTO); id.addAnnotation(Column.class) .setStringValue("name", "id") .setLiteralValue("updatable", "false") .setLiteralValue("nullable", "false"); Field<JavaClass> version = javaClass.addField("private int version = 0;"); version.addAnnotation(Version.class); version.addAnnotation(Column.class).setStringValue("name", "version"); Refactory.createGetterAndSetter(javaClass, id); Refactory.createGetterAndSetter(javaClass, version); Refactory.createToStringFromFields(javaClass, id); createHashCodeAndEquals(javaClass); JavaResource javaFileLocation = java.saveJavaSource(javaClass); shell.println("Created @Entity [" + javaClass.getQualifiedName() + "]"); /** Pick up the generated resource. */ shell.execute("pick-up " + javaFileLocation.getFullyQualifiedName()); }