@Override
  public Result execute(UIExecutionContext context) {
    Project project = getSelectedProject(context.getUIContext());
    final DependencyFacet deps = project.getFacet(DependencyFacet.class);

    if (arguments.hasValue()) {
      int count = 0;
      for (Dependency gav : arguments.getValue()) {
        Dependency existingDep =
            deps.getEffectiveManagedDependency(DependencyBuilder.create(gav).setVersion(null));
        if (existingDep != null) {
          if (context
              .getPrompt()
              .promptBoolean(
                  String.format(
                      "Dependency [%s:%s] is currently managed. "
                          + "Reference the existing managed dependency [%s:%s:%s]?",
                      gav.getCoordinate().getArtifactId(),
                      gav.getCoordinate().getGroupId(),
                      existingDep.getCoordinate().getGroupId(),
                      existingDep.getCoordinate().getArtifactId(),
                      existingDep.getCoordinate().getVersion()))) {
            gav = DependencyBuilder.create(existingDep).setScopeType(gav.getScopeType());
          }
        }

        this.installer.install(project, gav);
        count++;
      }

      return Results.success(
          "Installed [" + count + "] dependenc" + (count == 1 ? "y" : "ies") + ".");
    }
    return Results.fail("No arguments specified.");
  }
Example #2
0
 @Override
 public Result execute(final UIExecutionContext context) throws Exception {
   applyUIValues(context.getUIContext());
   Project project = getSelectedProject(context);
   JPAFacet<?> facet = jpaVersion.getValue();
   if (facetFactory.install(project, facet)) {
     return Results.success();
   }
   return Results.fail("Could not install JPA.");
 }
Example #3
0
 @Override
 public Result execute(final UIExecutionContext context) throws Exception {
   JavaEESpecFacet chosen = javaEEVersion.getValue();
   if (facetFactory.install(getSelectedProject(context.getUIContext()), chosen)) {
     // This facet may activate other facets, so better invalidate the cache
     projectFactory.invalidateCaches();
     return Results.success("JavaEE " + chosen.getSpecVersion() + " has been installed.");
   }
   return Results.fail("Could not install JavaEE " + chosen.getSpecVersion());
 }
Example #4
0
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    String url = getJolokiaUrl();
    if (url == null) {
      return Results.fail("Not connected to remote jolokia agent. Use camel-connect command first");
    }

    org.apache.camel.commands.RouteShowCommand command =
        new org.apache.camel.commands.RouteShowCommand(route.getValue(), name.getValue());
    command.execute(getController(), getOutput(context), getError(context));
    return Results.success();
  }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    JavaResource javaResource = targetClass.getValue();
    JavaClassSource targetClass = javaResource.getJavaType();
    GetSetMethodGenerator generator;
    if (builderPattern.getValue()) {
      generator = new BuilderGetSetMethodGenerator();
    } else {
      generator = new DefaultGetSetMethodGenerator();
    }
    List<PropertySource<JavaClassSource>> selectedProperties = new ArrayList<>();
    if (properties == null || properties.getValue() == null) {
      return Results.fail("No properties were selected");
    }
    for (String selectedProperty : properties.getValue()) {
      selectedProperties.add(targetClass.getProperty(selectedProperty));
    }

    for (PropertySource<JavaClassSource> property : selectedProperties) {
      MethodSource<JavaClassSource> accessor =
          targetClass.getMethod("get" + Strings.capitalize(property.getName()));
      if (accessor == null) {
        generator.createAccessor(property);
      } else {
        if (!generator.isCorrectAccessor(accessor, property)) {
          if (promptToFixMethod(context, accessor.getName(), property.getName())) {
            targetClass.removeMethod(accessor);
            generator.createMutator(property);
          }
        }
      }
      String mutatorMethodName = "set" + Strings.capitalize(property.getName());
      String mutatorMethodParameter = property.getType().getName();
      MethodSource<JavaClassSource> mutator =
          targetClass.getMethod(mutatorMethodName, mutatorMethodParameter);
      if (mutator == null) {
        generator.createMutator(property);
      } else {
        if (!generator.isCorrectMutator(mutator, property)) {
          if (promptToFixMethod(context, mutator.getName(), property.getName())) {
            targetClass.removeMethod(mutator);
            generator.createMutator(property);
          }
        }
      }
    }
    setCurrentWorkingResource(context, targetClass);
    return Results.success("Mutators and accessors were generated successfully");
  }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    String url = getJolokiaUrl();
    if (url == null) {
      return Results.fail("Not connected to remote jolokia agent. Use camel-connect command first");
    }

    boolean val = "true".equals(verbose.getValue());

    org.apache.camel.commands.CatalogLanguageListCommand command =
        new org.apache.camel.commands.CatalogLanguageListCommand(val, label.getValue());
    command.execute(getController(), getOutput(context), getError(context));

    return Results.success();
  }
  @Override
  public Result execute(UIExecutionContext context) {
    final Result result;
    Project project = getSelectedProject(context.getUIContext());
    DependencyFacet deps = project.getFacet(DependencyFacet.class);

    String urlValue = url.getValue();
    DependencyRepository rep = deps.removeRepository(urlValue);
    if (rep != null) {
      result = Results.success("Removed repository [" + rep.getId() + "->" + rep.getUrl() + "]");
    } else {
      result = Results.fail("No repository with url [" + urlValue + "]");
    }
    return result;
  }
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   UIContext uiContext = context.getUIContext();
   Project project = (Project) uiContext.getAttributeMap().get(Project.class);
   String coordinate =
       archetypeGroupId.getValue()
           + ":"
           + archetypeArtifactId.getValue()
           + ":"
           + archetypeVersion.getValue();
   DependencyQueryBuilder depQuery = DependencyQueryBuilder.create(coordinate);
   String repository = archetypeRepository.getValue();
   if (repository != null) {
     depQuery.setRepositories(new DependencyRepository("archetype", repository));
   }
   DependencyResolver resolver =
       SimpleContainer.getServices(getClass().getClassLoader(), DependencyResolver.class).get();
   Dependency resolvedArtifact = resolver.resolveArtifact(depQuery);
   FileResource<?> artifact = resolvedArtifact.getArtifact();
   MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
   File fileRoot = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();
   ArchetypeHelper archetypeHelper =
       new ArchetypeHelper(
           artifact.getResourceInputStream(),
           fileRoot,
           metadataFacet.getProjectGroupName(),
           metadataFacet.getProjectName(),
           metadataFacet.getProjectVersion());
   JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
   archetypeHelper.setPackageName(facet.getBasePackage());
   archetypeHelper.execute();
   return Results.success();
 }
Example #9
0
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   getConfiguration().setProperty(named.getValue(), url.getValue().getFullyQualifiedName());
   getArchetypeCatalogFactoryRegistry()
       .addArchetypeCatalogFactory(named.getValue(), url.getValue().getUnderlyingResourceObject());
   return Results.success();
 }
Example #10
0
 @Override
 public NavigationResult next(UINavigationContext context) throws Exception {
   if (type.getValue() != null) {
     return Results.navigateTo(type.getValue().getSetupFlow());
   } else {
     return null;
   }
 }
Example #11
0
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   List<Result> results = new LinkedList<>();
   for (UICommand command : commands) {
     Result result = command.execute(context);
     results.add(result);
   }
   return Results.aggregate(results);
 }
Example #12
0
  protected Result processDeployment(Project project, String path, Type type) {
    Result result;

    // The server must be running
    if (serverController.hasServer() && serverController.getServer().isRunning()) {
      final PackagingFacet packagingFacet = project.getFacet(PackagingFacet.class);

      // Can't deploy what doesn't exist
      if (!packagingFacet.getFinalArtifact().exists())
        throw new DeploymentFailureException(
            messages.getMessage("deployment.not.found", path, type));
      final File content;
      if (path == null) {
        content = new File(packagingFacet.getFinalArtifact().getFullyQualifiedName());
      } else if (path.startsWith("/")) {
        content = new File(path);
      } else {
        // TODO this might not work for EAR deployments
        content =
            new File(packagingFacet.getFinalArtifact().getParent().getFullyQualifiedName(), path);
      }
      try {
        final ModelControllerClient client = serverController.getClient();
        final Deployment deployment =
            StandaloneDeployment.create(client, content, null, type, null, null);
        deployment.execute();
        result = Results.success(messages.getMessage("deployment.successful", type));
      } catch (Exception e) {
        if (e.getCause() != null) {
          result =
              Results.fail(e.getLocalizedMessage() + ": " + e.getCause().getLocalizedMessage());
        } else {
          result = Results.fail(e.getLocalizedMessage());
        }
      }
    } else {
      result =
          Results.fail(
              messages.getMessage(
                  "server.not.running", configuration.getHostname(), configuration.getPort()));
    }

    return result;
  }
Example #13
0
  @Override
  public Result start(UIContext context) {
    Result result = null;
    if ((serverController.hasServer() && serverController.getServer().isRunning())
        || false) // getState().isRunningState())
    {
      result = Results.fail(messages.getMessage("server.already.running"));
    } else {
      try {

        if (!serverController.hasServer()) createServer(context);

        Server<ModelControllerClient> server = serverController.getServer();

        // Start the server
        server.start();
        server.checkServerState();

        if (server.isRunning()) {
          result =
              Results.success(
                  messages.getMessage("server.start.success", configuration.getVersion()));
        } else {
          result =
              Results.fail(messages.getMessage("server.start.failed", configuration.getVersion()));
        }
      } catch (Exception e) {
        result =
            Results.fail(
                messages.getMessage(
                    "server.start.failed.exception",
                    configuration.getVersion(),
                    e.getLocalizedMessage()));
      }
      if (result instanceof Failed) {
        // closeConsoleOutput();
      }
    }
    return result;
  }
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   String packageName = named.getValue();
   JavaSourceFacet facet = getSelectedProject(context).getFacet(JavaSourceFacet.class);
   DirectoryResource newPackage;
   if (testFolder.getValue()) {
     newPackage = facet.saveTestPackage(packageName, createPackageInfo.getValue());
   } else {
     newPackage = facet.savePackage(packageName, createPackageInfo.getValue());
   }
   context.getUIContext().setSelection(newPackage);
   return Results.success(String.format("Package '%s' created succesfully.", packageName));
 }
Example #15
0
  @Override
  public Result shutdown(UIContext context) {
    try {
      if (!serverController.hasServer()) {
        createServer(context);
      }
      return serverController.shutdownServer();

    } catch (Exception e) {
      return Results.fail(e.getLocalizedMessage());
    } finally {
      serverController.closeClient();
    }
  }
Example #16
0
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    Result result = Results.success("Project named '" + named.getValue() + "' has been created.");
    DirectoryResource directory = targetLocation.getValue();
    DirectoryResource targetDir = directory.getChildDirectory(named.getValue());

    if (targetDir.mkdirs() || overwrite.getValue()) {
      ProjectType value = type.getValue();

      Project project = null;
      if (value != null) {
        project =
            projectFactory.createProject(
                targetDir, buildSystem.getValue(), value.getRequiredFacets());
      } else {
        project = projectFactory.createProject(targetDir, buildSystem.getValue());
      }

      if (project != null) {
        UIContext uiContext = context.getUIContext();
        MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
        metadataFacet.setProjectName(named.getValue());
        metadataFacet.setProjectVersion(version.getValue());
        metadataFacet.setTopLevelPackage(topLevelPackage.getValue());

        if (finalName.hasValue()) {
          PackagingFacet packagingFacet = project.getFacet(PackagingFacet.class);
          packagingFacet.setFinalName(finalName.getValue());
        }

        uiContext.setSelection(project.getRoot());
        uiContext.getAttributeMap().put(Project.class, project);
      } else result = Results.fail("Could not create project of type: [" + value + "]");
    } else result = Results.fail("Could not create target location: " + targetDir);

    return result;
  }
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   Map<String, ConnectionProfile> connectionProfiles =
       provider.getConnectionProfileManager().loadConnectionProfiles();
   ConnectionProfile connectionProfile = new ConnectionProfile();
   connectionProfile.setName(name.getValue());
   connectionProfile.setDialect(hibernateDialect.getValue().getClassName());
   connectionProfile.setDriver(driverClass.getValue().getName());
   connectionProfile.setPath(driverLocation.getValue().getFullyQualifiedName());
   connectionProfile.setUrl(jdbcUrl.getValue());
   connectionProfile.setUser(userName.getValue());
   connectionProfile.setSavePassword(saveUserPassword.getValue());
   connectionProfile.setPassword(userPassword.getValue());
   connectionProfiles.put(name.getValue(), connectionProfile);
   provider.getConnectionProfileManager().saveConnectionProfiles(connectionProfiles.values());
   return Results.success(
       "Connection profile " + connectionProfile.getName() + " has been saved successfully");
 }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    Project project = getSelectedProject(context);
    DeltaSpikeFacet deltaSpikeFacet = project.getFacet(DeltaSpikeFacet.class);

    Iterable<DeltaSpikeModule> selectedModules = dsModules.getValue();
    Set<DeltaSpikeModule> modulesInstalled = new HashSet<DeltaSpikeModule>();
    Set<DeltaSpikeModule> modulesRemoved = new HashSet<DeltaSpikeModule>();
    for (DeltaSpikeModule dsModule : DeltaSpikeModules.values()) {
      boolean selected = false;
      for (DeltaSpikeModule selectedModule : selectedModules) {
        if (selectedModule.equals(dsModule)) {
          selected = true;
        }
      }
      // Modules to Install
      if (selected && !deltaSpikeFacet.isModuleInstalled(dsModule)) {
        modulesInstalled.add(dsModule);
        deltaSpikeFacet.install(dsModule);
        if (dsModule.getInstallationExtraStep() != null) {
          dsModule.getInstallationExtraStep().install(project);
        }
      }
      // Modules to Remove
      if (!selected && deltaSpikeFacet.isModuleInstalled(dsModule)) {
        modulesRemoved.add(dsModule);
        deltaSpikeFacet.remove(dsModule);
        if (dsModule.getInstallationExtraStep() != null) {
          dsModule.getInstallationExtraStep().remove(project);
        }
      }
    }

    return Results.success(
        "DeltaSpike modules installed:"
            + modulesInstalled
            + "\nDeltaSpike modules removed:"
            + modulesRemoved);
  }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Project project = getSelectedProject(uiContext);

    facetFactory.install(project, FurnaceVersionFacet.class);
    project.getFacet(FurnaceVersionFacet.class).setVersion(furnace.getVersion().toString());

    facetFactory.install(project, AddonTestFacet.class);
    for (AddonId addonId : addonDependencies.getValue()) {
      DependencyBuilder dependency =
          DependencyBuilder.create(addonId.getName())
              .setVersion(addonId.getVersion().toString())
              .setScopeType("test");
      if (!dependencyInstaller.isInstalled(project, dependency)) {
        dependencyInstaller.install(project, dependency);
      }
    }
    return Results.success(
        "Project "
            + project.getFacet(MetadataFacet.class).getProjectName()
            + " is now configured for testing");
  }
Example #20
0
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    String buildConfigName = buildName.getValue();
    Objects.assertNotNull(buildConfigName, "buildName");
    Map<String, String> labels = BuildConfigs.createBuildLabels(buildConfigName);
    String ouputImageName = imageName.getValue();
    String gitUrlText = getOrFindGitUrl(context, gitUri.getValue());
    String imageText = outputImage.getValue();
    Model mavenModel = getMavenModel(context);
    if (Strings.isNullOrBlank(imageText) && mavenModel != null) {
      imageText = mavenModel.getProperties().getProperty("docker.image");
    }

    String webhookSecretText = webHookSecret.getValue();
    if (Strings.isNullOrBlank(webhookSecretText)) {
      // TODO generate a really good secret!
      webhookSecretText = "secret101";
    }
    BuildConfig buildConfig =
        BuildConfigs.createBuildConfig(
            buildConfigName, labels, gitUrlText, ouputImageName, imageText, webhookSecretText);

    System.out.println("Generated BuildConfig: " + toJson(buildConfig));

    ImageStream imageRepository = BuildConfigs.imageRepository(buildConfigName, labels);

    Controller controller = createController();
    controller.applyImageStream(
        imageRepository, "generated ImageStream: " + toJson(imageRepository));
    controller.applyBuildConfig(buildConfig, "generated BuildConfig: " + toJson(buildConfig));
    return Results.success(
        "Added BuildConfig: "
            + Builds.getName(buildConfig)
            + " to OpenShift at master: "
            + getKubernetes().getAddress());
  }
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   return Results.success();
 }
Example #22
0
 @Override
 public Result execute(UIExecutionContext context) throws Exception {
   context.getPrompt().prompt("Press <ENTER> to continue...");
   return Results.success();
 }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    LOG.info("Creating the fabric8.yml file");

    String fileName = ProjectConfigs.FILE_NAME;
    Project project = getSelectedProject(context);
    File configFile = getProjectConfigFile(context.getUIContext(), getSelectedProject(context));
    if (configFile == null) {
      // lets not fail as we typically want to execute SaveDevOpsStep next...
      return Results.success();
    }
    ProjectConfig config = null;
    boolean hasFile = false;
    if (configFile.exists()) {
      config = ProjectConfigs.parseProjectConfig(configFile);
      hasFile = true;
    }
    if (config == null) {
      config = new ProjectConfig();
    }

    CommandHelpers.putComponentValuesInAttributeMap(context, inputComponents);
    updateConfiguration(context, config);
    LOG.info("Result: " + config);

    String message;
    if (config.isEmpty() && !hasFile) {
      message = "No " + fileName + " need be generated as there is no configuration";
      return Results.success(message);
    } else {
      String operation = "Updated";
      if (!configFile.exists()) {
        operation = "Created";
      }
      ProjectConfigs.saveConfig(config, configFile);
      message = operation + " " + fileName;
    }

    // now lets update the devops stuff
    UIContext uiContext = context.getUIContext();
    Map<Object, Object> attributeMap = uiContext.getAttributeMap();

    String gitUrl = getStringAttribute(attributeMap, "gitUrl");
    if (Strings.isNullOrBlank(gitUrl)) {
      gitUrl = getStringAttribute(attributeMap, "gitAddress");
    }

    Object object = attributeMap.get(Project.class);
    String user = getStringAttribute(attributeMap, "gitUser");
    String named = getStringAttribute(attributeMap, "projectName");
    ;
    File basedir = CommandHelpers.getBaseDir(project);
    if (basedir == null && configFile != null) {
      basedir = configFile.getParentFile();
    }

    if (object instanceof Project) {
      Project newProject = (Project) object;
      MetadataFacet facet = newProject.getFacet(MetadataFacet.class);
      if (facet != null) {
        if (Strings.isNullOrBlank(named)) {
          named = facet.getProjectName();
        }
        if (Strings.isNullOrBlank(gitUrl)) {
          String address = getStringAttribute(attributeMap, "gitAddress");
          gitUrl = address + user + "/" + named + ".git";
        }
      } else {
        LOG.error("No MetadataFacet for newly created project " + newProject);
      }
    } else {
      // updating an existing project - so lets try find the git url from the current source code
      if (Strings.isNullOrBlank(gitUrl)) {
        gitUrl = GitHelpers.extractGitUrl(basedir);
      }
      if (basedir != null) {
        if (Strings.isNullOrBlank(named)) {
          named = basedir.getName();
        }
      }
    }
    // lets default the environments from the pipeline
    PipelineDTO pipelineValue = pipeline.getValue();
    LOG.info("Using pipeline " + pipelineValue);
    String buildName = config.getBuildName();
    if (Strings.isNotBlank(buildName)) {
      if (pipelineValue != null) {
        List<String> environments = pipelineValue.getEnvironments();
        if (environments == null) {
          environments = new ArrayList<>();
        }
        LinkedHashMap<String, String> environmentMap = new LinkedHashMap<>();
        if (environments.isEmpty()) {
          environmentMap.put("Current", namespace);
        } else {
          for (String environment : environments) {
            String envNamespace = namespace + "-" + environment.toLowerCase();
            environmentMap.put(environment, envNamespace);
          }
        }
        config.setEnvironments(environmentMap);
      }
    }
    LOG.info("Configured project " + buildName + " environments: " + config.getEnvironments());
    ProjectConfigs.defaultEnvironments(config, namespace);

    String projectName = config.getBuildName();
    if (Strings.isNullOrBlank(projectName)) {
      projectName = named;
      config.setBuildName(projectName);
    }

    LOG.info("Project name is: " + projectName);
    if (Strings.isNotBlank(projectName) && project != null) {
      MavenFacet maven = project.getFacet(MavenFacet.class);
      Model pom = maven.getModel();
      if (pom != null
          && !isFunktionParentPom(project)
          && !isFabric8MavenPlugin3OrGreater(project)) {
        Properties properties = pom.getProperties();
        boolean updated = false;
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.project", projectName, updated);
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.version", "${project.version}", updated);
        if (updated) {
          LOG.info("Updating pom.xml properties!");
          maven.setModel(pom);
        } else {
          LOG.warn("Did not update pom.xml properties!");
        }
      } else {
        LOG.warn("No pom.xml found!");
      }
    }

    Boolean copyFlowToProjectValue = copyPipelineToProject.getValue();
    if (copyFlowToProjectValue != null && copyFlowToProjectValue.booleanValue()) {
      if (basedir == null || !basedir.isDirectory()) {
        LOG.warn("Cannot copy the pipeline to the project as no basedir!");
      } else {
        String flow = null;
        PipelineDTO pipelineDTO = pipelineValue;
        if (pipelineDTO != null) {
          flow = pipelineDTO.getValue();
        }
        if (Strings.isNullOrBlank(flow)) {
          LOG.warn("Cannot copy the pipeline to the project as no pipeline selected!");
        } else {
          String flowText = getFlowContent(flow, uiContext);
          if (Strings.isNullOrBlank(flowText)) {
            LOG.warn(
                "Cannot copy the pipeline to the project as no pipeline text could be loaded!");
          } else {
            flowText = Strings.replaceAllWithoutRegex(flowText, "GIT_URL", "'" + gitUrl + "'");
            File newFile = new File(basedir, ProjectConfigs.LOCAL_FLOW_FILE_NAME);
            Files.writeToFile(newFile, flowText.getBytes());
            LOG.info("Written pipeline to " + newFile);
            if (config != null) {
              config.setPipeline(null);
              config.setUseLocalFlow(true);
            }
          }
        }
      }
    }

    final DevOpsConnector connector = new DevOpsConnector();
    connector.setProjectConfig(config);
    connector.setTryLoadConfigFileFromRemoteGit(false);
    connector.setUsername(user);
    connector.setPassword(getStringAttribute(attributeMap, "gitPassword"));
    connector.setBranch(getStringAttribute(attributeMap, "gitBranch", "master"));
    connector.setBasedir(basedir);
    connector.setGitUrl(gitUrl);
    connector.setRepoName(named);

    connector.setRegisterWebHooks(true);

    // lets not trigger the jenkins webhook yet as the git push should trigger the build
    connector.setTriggerJenkinsJob(false);

    LOG.info("Using connector: " + connector);

    /*
            attributeMap.put("registerWebHooks", new Runnable() {
                @Override
                public void run() {
                    LOG.info("Now registering webhooks!");
                    connector.registerWebHooks();
                }
            });
    */
    try {
      connector.execute();
    } catch (Exception e) {
      LOG.error("Failed to update DevOps resources: " + e, e);
    }

    return Results.success(message);
  }
 /** Prints the given table and returns success */
 protected Result tableResults(TablePrinter table) {
   table.print(getOut());
   return Results.success();
 }
Example #25
0
 @Override
 public NavigationResult next(UINavigationContext context) throws Exception {
   applyUIValues(context.getUIContext());
   return Results.navigateTo(JPASetupConnectionStep.class);
 }
  @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");
  }