@Override
  public boolean isInstalled() {
    JavaSourceFacet javaSourceFacet = project.getFacet(JavaSourceFacet.class);

    Configuration projectConfiguration = getProjectConfiguration();
    classPackage = projectConfiguration.getString(REST_APPLICATIONCLASS_PACKAGE);
    className = projectConfiguration.getString(REST_APPLICATIONCLASS_NAME);
    rootPath = projectConfiguration.getString(RestFacet.ROOTPATH);

    if ((classPackage == null || className == null) && !findApplicationClass()) {
      return false;
    }

    try {
      JavaResource javaResource = javaSourceFacet.getJavaResource(classPackage + "." + className);
      if (javaResource.exists() || findApplicationClass()) {
        return true;
      }

    } catch (FileNotFoundException e) {
      return false;
    }

    return false;
  }
예제 #2
0
  @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");
  }
  @Override
  public void setApplicationPath(String path) {
    getProjectConfiguration().setProperty(RestFacet.ROOTPATH, path);

    if (classPackage == null || className == null) {
      reportConfigurationError(className);
    }

    JavaSourceFacet javaSourceFacet = project.getFacet(JavaSourceFacet.class);

    try {
      String classname = classPackage + "." + this.className;
      JavaResource javaResource = javaSourceFacet.getJavaResource(classname);
      if (!javaResource.exists()) {
        reportConfigurationError(classname);
      }

      javaResource
          .getJavaSource()
          .getAnnotation("javax.ws.rs.ApplicationPath")
          .setStringValue(path);

    } catch (FileNotFoundException e) {
      reportConfigurationError(className);
    }
  }
  @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());
  }
예제 #5
0
  @Command("new-enum-const")
  @RequiresResource(JavaResource.class)
  public void newEnumConst(
      @PipeIn final String in,
      final PipeOut out,
      @Option(
              required = false,
              help = "the enum field definition",
              description = "enum field definition")
          final String... def)
      throws FileNotFoundException {
    JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);

    String enumConstDef = null;
    if (def != null) {
      enumConstDef = Strings.join(Arrays.asList(def), " ");
    } else if (in != null) {
      enumConstDef = in;
    } else {
      throw new RuntimeException("arguments required");
    }

    JavaEnum source = (JavaEnum) resource.getJavaSource();
    source.addEnumConstant(enumConstDef);
    java.saveEnumTypeSource(source);
  }
  @Command("new-class")
  public void newClassCommand(
      @Option(name = "interface", shortName = "i") String interfaceName,
      @Option(name = "implementation", shortName = "m", type = PromptType.JAVA_CLASS)
          String implName,
      PipeOut out) {

    ResourceFacet resourcesFacet = project.getFacet(ResourceFacet.class);
    JavaSourceFacet javaSourceFacet = project.getFacet(JavaSourceFacet.class);

    try {
      JavaResource implementationFile = javaSourceFacet.getJavaResource(implName);
      if (!implementationFile.exists()) {
        out.println(
            "The implementation class "
                + implName
                + " does not exist in the current project. You can declare only existing implementations of "
                + interfaceName);
        return;
      }
    } catch (FileNotFoundException fnfe) {
      out.println(
          "The implementation class "
              + implName
              + " does not exist in the current project. You can declare only existing implementations of "
              + interfaceName);
      return;
    }

    DirectoryResource servicesDirectory = getServicesDirectory(resourcesFacet);
    UnknownFileResource implementationsFile =
        getImplementationsFile(interfaceName, servicesDirectory);

    try {
      String implementations = getImplementations(implementationsFile, implName) + implName;
      implementationsFile.setContents(implementations);
    } catch (IOException ioe) {
      out.println("Could not update " + implementationsFile + ". Reason: " + ioe.getMessage());
    } catch (ImplementationExistsException iee) {
      out.println(
          "The implementation "
              + implName
              + " is already declared in "
              + implementationsFile
              + ".");
    }
  }
 @Override
 public String calculateName(JavaResource resource) {
   String fullPath = Packages.fromFileSyntax(resource.getFullyQualifiedName());
   String pkg = calculatePackage(resource);
   String name = fullPath.substring(fullPath.lastIndexOf(pkg) + pkg.length() + 1);
   name = name.substring(0, name.lastIndexOf(".java"));
   return name;
 }
예제 #8
0
 @Command("list-imports")
 @RequiresResource(JavaResource.class)
 public void listImports(final PipeOut out) throws FileNotFoundException {
   List<Import> imports = resource.getJavaSource().getImports();
   for (Import i : imports) {
     String str = "import " + (i.isStatic() ? "static " : "") + i.getQualifiedName() + ";";
     str = JavaColorizer.format(out, str);
     out.println(str);
   }
 }
  @Override
  public String calculatePackage(JavaResource resource) {
    String pkg = resource.getParent().getFullyQualifiedName();
    pkg = Packages.fromFileSyntax(pkg);

    String result = pkg;
    if (result.contains(getBasePackage())) {
      result = pkg.substring(pkg.lastIndexOf(getBasePackage()));
    }

    return result;
  }
예제 #10
0
  @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");
  }
예제 #11
0
  @Command("new-method")
  @RequiresResource(JavaResource.class)
  public void newMethod(
      @PipeIn final String in,
      final PipeOut out,
      @Option(
              required = false,
              help = "the method definition: surround with single quotes",
              description = "method definition")
          final String... def)
      throws FileNotFoundException {
    JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);

    String methodDef = null;
    if (def != null) {
      methodDef = Strings.join(Arrays.asList(def), " ");
    } else if (in != null) {
      methodDef = in;
    } else {
      throw new RuntimeException("arguments required");
    }

    JavaSource<?> source = resource.getJavaSource();
    if (source instanceof MethodHolder) {
      MethodHolder<?> clazz = ((MethodHolder<?>) source);

      Method<JavaClass> method =
          JavaParser.parse(JavaClass.class, "public class Temp{}").addMethod(methodDef);
      if (clazz.hasMethodSignature(method)) {
        throw new IllegalStateException(
            "Method with signature [" + method.toSignature() + "] already exists.");
      }

      clazz.addMethod(methodDef);
      java.saveJavaSource(source);
    }
  }
예제 #12
0
  @Command("new-field")
  @RequiresResource(JavaResource.class)
  public void newField(
      @PipeIn final String in,
      final PipeOut out,
      @Option(
              required = false,
              help = "the field definition: surround with single quotes",
              description = "field definition")
          final String... def)
      throws FileNotFoundException {
    JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);

    String fieldDef = null;
    if (def != null) {
      fieldDef = Strings.join(Arrays.asList(def), " ");
    } else if (in != null) {
      fieldDef = in;
    } else {
      throw new RuntimeException("arguments required");
    }

    JavaSource<?> source = resource.getJavaSource();
    if (source instanceof FieldHolder) {
      FieldHolder<?> clazz = ((FieldHolder<?>) source);

      String name =
          JavaParser.parse(JavaClass.class, "public class Temp{}").addField(fieldDef).getName();
      if (clazz.hasField(name)) {
        throw new IllegalStateException("Field named [" + name + "] already exists.");
      }

      clazz.addField(fieldDef);
      java.saveJavaSource(source);
    }
  }
  @Command(
      value = "create-from",
      help = "Create a new entity service class with CRUD methods for an existing entity bean.")
  public void createFrom(
      @Option(name = "entity", required = true, type = PromptType.JAVA_CLASS) JavaResource entity,
      final PipeOut out)
      throws FileNotFoundException {

    JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);

    JavaSource<?> entitySource = entity.getJavaSource();

    VelocityContext context = new VelocityContext();
    context.put("package", java.getBasePackage() + ".service");
    context.put("entityImport", entitySource.getQualifiedName());
    context.put("entityName", entitySource.getName());
    context.put("cdiName", entitySource.getName().toLowerCase());

    // Service class
    StringWriter writer = new StringWriter();
    Velocity.mergeTemplate("TemplateService.vtl", "UTF-8", context, writer);

    JavaClass serviceClass = JavaParser.parse(JavaClass.class, writer.toString());
    java.saveJavaSource(serviceClass);

    pickup.fire(new PickupResource(java.getJavaResource(serviceClass)));

    // ServiceTest class
    StringWriter writerTest = new StringWriter();
    Velocity.mergeTemplate("TemplateServiceTest.vtl", "UTF-8", context, writerTest);

    JavaClass serviceTestClass = JavaParser.parse(JavaClass.class, writerTest.toString());
    java.saveTestJavaSource(serviceTestClass);

    pickup.fire(new PickupResource(java.getTestJavaResource(serviceTestClass)));
  }
예제 #14
0
  @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());
  }