Merge pull request #172 from pymma/kafka

Kafka
This commit is contained in:
Nicolas Héron 2020-10-22 18:59:36 +02:00 committed by GitHub
commit 3ea1b42188
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 677 additions and 219 deletions

View file

@ -39,6 +39,7 @@ import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import org.springframework.kafka.support.serializer.JsonSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.PathSelectors;
@ -56,6 +57,7 @@ import java.util.Map;
@EnableKafka
@PropertySource("classpath:application.properties")
@EnableSwagger2
@EnableScheduling
public class DroolsSpringBootConsoleApplication extends SpringBootServletInitializer {

View file

@ -1,9 +1,14 @@
package org.chtijbug.drools.console.middle;
import org.chtijbug.drools.console.service.KieRepositoryService;
import org.chtijbug.drools.console.service.ProjectPersistService;
import org.chtijbug.drools.console.service.model.UserConnected;
import org.chtijbug.drools.proxy.persistence.model.*;
import org.chtijbug.drools.proxy.persistence.repository.*;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.UUID;
@ -17,6 +22,9 @@ public class DababaseContentInit {
@Value("${kie-wb.mainwbextern}")
private String mainwbExtern;
@Value("${kie-wb.baseurl}")
private String kiewbUrl;
@Autowired
private UserRepository userRepository;
@ -32,10 +40,13 @@ public class DababaseContentInit {
@Autowired
private CustomerRepository customerRepository;
public void initDatabaseIfNecessary(){
@Autowired
private KieRepositoryService kieRepositoryService;
User adminUser = userRepository.findByLogin("admin");
if (adminUser==null){
@Autowired
private ProjectPersistService projectPersistService;
public void initDatabaseIfNecessary() {
/**
* admin The administrator
* analyst The analyst
@ -44,66 +55,101 @@ public class DababaseContentInit {
* user The end user
* kiemgmt KIE management user
*/
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"process-admin"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"manager"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"admin"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"analyst"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"rest-all"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"developer"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"rest-project"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"user"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(),"kiemgmt"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(),"admingroup"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(),"demogroup"));
adminUser = new User(UUID.randomUUID().toString(),"admin","adminadmin99#");
adminUser.getUserGroups().add(userGroupsRepository.findByName("kiemgmt"));
adminUser.getUserGroups().add(userGroupsRepository.findByName("admingroup"));
adminUser.getUserRoles().add(userRolesRepository.findByName("admin"));
adminUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
adminUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
userRepository.save(adminUser);
User nheronUser = new User(UUID.randomUUID().toString(),"nheron","adminnheron00@");
nheronUser.getUserGroups().add(userGroupsRepository.findByName("kiemgmt"));
nheronUser.getUserGroups().add(userGroupsRepository.findByName("admingroup"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("admin"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
userRepository.save(nheronUser);
KieWorkbench mainWorkbench = new KieWorkbench();
mainWorkbench.setID(UUID.randomUUID().toString());
mainWorkbench.setName("demo");
mainWorkbench.setExternalUrl(mainwbExtern);
mainWorkbench.setInternalUrl(mainwbUrlIntern);
mainWorkbench = kieWorkbenchRepository.save(mainWorkbench);
Customer demCustomer = new Customer();
demCustomer.setKieWorkbench(mainWorkbench);
demCustomer.setName("demoCustomer");
demCustomer.setID(UUID.randomUUID().toString());
customerRepository.save(demCustomer);
User demoUser = new User(UUID.randomUUID().toString(),"demo","demo");
demoUser.getUserGroups().add(userGroupsRepository.findByName("demogroup"));
demoUser.getUserRoles().add(userRolesRepository.findByName("user"));
demoUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
demoUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
demoUser.setWbName(mainWorkbench.getName());
demoUser.setCustomer(demCustomer);
userRepository.save(demoUser);
User adminUser = userRepository.findByLogin("admin");
if (adminUser == null) {
this.initDatabase();
}else{
this.synchronizeDatabaseWithWorkbenches();
}
}
private void initDatabase(){
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "process-admin"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "manager"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "admin"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "analyst"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "rest-all"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "developer"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "rest-project"));
userRolesRepository.save(new UserRoles(UUID.randomUUID().toString(), "user"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(), "kiemgmt"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(), "admingroup"));
userGroupsRepository.save(new UserGroups(UUID.randomUUID().toString(), "demogroup"));
User adminUser = new User(UUID.randomUUID().toString(), "admin", "adminadmin99#");
adminUser.getUserGroups().add(userGroupsRepository.findByName("kiemgmt"));
adminUser.getUserGroups().add(userGroupsRepository.findByName("admingroup"));
adminUser.getUserRoles().add(userRolesRepository.findByName("admin"));
adminUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
adminUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
userRepository.save(adminUser);
User nheronUser = new User(UUID.randomUUID().toString(), "nheron", "adminnheron00@");
nheronUser.getUserGroups().add(userGroupsRepository.findByName("kiemgmt"));
nheronUser.getUserGroups().add(userGroupsRepository.findByName("admingroup"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("admin"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
nheronUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
userRepository.save(nheronUser);
KieWorkbench mainWorkbench = new KieWorkbench();
mainWorkbench.setID(UUID.randomUUID().toString());
mainWorkbench.setName("demo");
mainWorkbench.setExternalUrl(mainwbExtern);
mainWorkbench.setInternalUrl(mainwbUrlIntern);
mainWorkbench = kieWorkbenchRepository.save(mainWorkbench);
UserConnected userConnected = kieRepositoryService.getUserContent(mainWorkbench.getExternalUrl() + "/rest",
nheronUser.getLogin(), nheronUser.getPassword(), mainWorkbench.getName());
for (PlatformProjectData platformProjectData : userConnected.getProjectResponses()) {
String projectName = platformProjectData.getName();
String workspaceName = platformProjectData.getSpaceName();
ProjectPersist projectPersist=projectPersistService.saveorUpdateProject(platformProjectData, mainWorkbench);
UserGroups workspaceUserGroups=projectPersistService.createWorkSpaceGroupIfNeeded(workspaceName, mainWorkbench);
projectPersistService.createProjectGroupIfNeeded(projectName, mainWorkbench,projectPersist,workspaceUserGroups);
//platformProjectData.getJavaClasses()
}
Customer demCustomer = new Customer();
demCustomer.setKieWorkbench(mainWorkbench);
demCustomer.setName("demoCustomer");
demCustomer.setID(UUID.randomUUID().toString());
customerRepository.save(demCustomer);
User demoUser = new User(UUID.randomUUID().toString(), "demo", "demo");
demoUser.getUserGroups().add(userGroupsRepository.findByName("demogroup"));
demoUser.getUserRoles().add(userRolesRepository.findByName("user"));
demoUser.getUserRoles().add(userRolesRepository.findByName("rest-all"));
demoUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
demoUser.setWbName(mainWorkbench.getName());
demoUser.setCustomer(demCustomer);
userRepository.save(demoUser);
}
@Scheduled(cron = "0 0 0/1 * * ?")
public void synchronizeDatabaseWithWorkbenches(){
for (KieWorkbench kieWorkbench : kieWorkbenchRepository.findAll()){
User nheronUser = userRepository.findByLogin("nheron");
UserConnected userConnected = kieRepositoryService.getUserContent(kieWorkbench.getExternalUrl() + "/rest",
nheronUser.getLogin(), nheronUser.getPassword(), kieWorkbench.getName());
for (PlatformProjectData platformProjectData : userConnected.getProjectResponses()) {
String projectName = platformProjectData.getName();
String workspaceName = platformProjectData.getSpaceName();
ProjectPersist projectPersist=projectPersistService.saveorUpdateProject(platformProjectData, kieWorkbench);
UserGroups workSpaceGroupIfNeeded = projectPersistService.createWorkSpaceGroupIfNeeded(workspaceName, kieWorkbench);
projectPersistService.createProjectGroupIfNeeded(projectName, kieWorkbench,projectPersist,workSpaceGroupIfNeeded);
}
}
}
}

View file

@ -4,9 +4,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.chtijbug.drools.console.service.IndexerService;
import org.chtijbug.drools.console.service.JobService;
import org.chtijbug.drools.console.service.ProjectPersistService;
import org.chtijbug.drools.proxy.persistence.model.KieWorkbench;
import org.chtijbug.drools.proxy.persistence.model.User;
import org.chtijbug.drools.proxy.persistence.model.UserGroups;
import org.chtijbug.drools.proxy.persistence.repository.KieWorkbenchRepository;
import org.chtijbug.drools.proxy.persistence.repository.UserGroupsRepository;
import org.chtijbug.drools.proxy.persistence.repository.UserRepository;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectData;
import org.guvnor.rest.client.CreateProjectJobRequest;
@ -44,12 +47,17 @@ public class AssetServiceExpose {
@Autowired
private KieWorkbenchRepository kieWorkbenchRepository;
@Autowired
private UserGroupsRepository userGroupsRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private JobService jobService;
@Autowired
private ProjectPersistService projectPersistService;
@PostMapping(value = "/spaces",
consumes = {javax.ws.rs.core.MediaType.APPLICATION_JSON, javax.ws.rs.core.MediaType.APPLICATION_XML},
@ -85,6 +93,7 @@ public class AssetServiceExpose {
}
return new ResponseEntity<>(extractedResponse, clientHttpResponse.getHeaders(), clientHttpResponse.getStatusCode());
});
projectPersistService.createWorkSpaceGroupIfNeeded(request.getSpaceName(),kieWorkbench);
jobService.executeWrite(kieWorkbench.getExternalUrl()+"/rest", connectedUser.getLogin(), connectedUser.getPassword(), null, response.getBody().getJobId(), null);
Variant variant = Variant.mediaTypes(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE).add().build().get(0);
return Response.status(Response.Status.CREATED).entity(response.getBody()).variant(variant).build();
@ -143,6 +152,8 @@ public class AssetServiceExpose {
Variant variant = Variant.mediaTypes(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE).add().build().get(0);
UserGroups workspaceUsergroup = userGroupsRepository.findByName("wrk_" + spaceName);
projectPersistService.createProjectGroupIfNeeded(request.getName(),kieWorkbench,null,workspaceUsergroup);
return Response.status(Response.Status.CREATED).entity(response2.getBody()).variant(variant).build();
}
private RequestCallback requestCallback(final Object content, String username, String password) {

View file

@ -51,7 +51,7 @@ public class KieRepositoryService {
logger.info("url updateAssetSource : {}", completeurl);
restTemplateKiewb
.execute(completeurl, HttpMethod.POST, requestCallback(assetSource, username, password), clientHttpResponse -> {
.execute(completeurl, HttpMethod.PUT, requestCallback(assetSource, username, password), clientHttpResponse -> {
String extractedResponse = null;
if (clientHttpResponse.getBody() != null) {
Scanner s = new Scanner(clientHttpResponse.getBody()).useDelimiter("\\A");
@ -125,6 +125,49 @@ public class KieRepositoryService {
});
UserConnected userConnected = new UserConnected();
userConnected.setUserName(username);
userConnected.setUserPassword(password);
userConnected.setUserPassword(password);
if (response!= null) {
UserLoginInformation responseBody = response.getBody();
if (responseBody!= null) {
userConnected.getProjectResponses().addAll(responseBody.getProjects());
userConnected.getRoles().addAll(responseBody.getRoles());
}
}
userConnected.setUserName(username);
userConnected.setKieWorkbenchName(workbenchName);
return userConnected;
} else {
return null;
}
}
public UserConnected getUserContent(String url, String username, String password,String workbenchName) {
User user = userRepository.findByLogin(username);
String completeurl = url + chtijbugprefix+"content";
if (user != null && user.getPassword().equals(password)) {
if (user.getCustomer()!= null &&
user.getCustomer().getKieWorkbench()!= null
&& user.getCustomer().getKieWorkbench().getInternalUrl()!= null){
completeurl = user.getCustomer().getKieWorkbench().getInternalUrl()+"/rest/chtijbug/content";
}
logger.info("url moteur reco : {}" , completeurl);
ResponseEntity<UserLoginInformation> response = restTemplateKiewb
.execute(completeurl, HttpMethod.GET, requestCallback(null, username, password), clientHttpResponse -> {
UserLoginInformation extractedResponse =null;
if (clientHttpResponse.getBody() != null) {
Scanner s = new Scanner(clientHttpResponse.getBody()).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
extractedResponse = mapper.readValue(result, UserLoginInformation.class);
}
return new ResponseEntity<>(extractedResponse, clientHttpResponse.getHeaders(), clientHttpResponse.getStatusCode());
});
UserConnected userConnected = new UserConnected();
UserLoginInformation responseBody = response.getBody();
userConnected.setUserName(username);
userConnected.setUserPassword(password);
@ -138,7 +181,6 @@ public class KieRepositoryService {
return null;
}
}
public List<Asset> getListAssets(String url, String username, String password, String spaceName, String projectName) {
String completeurl = url + chtijbugprefix + spaceName + "/" + projectName + "/assets";
logger.info("url getListAssets : {}" , completeurl);

View file

@ -1,7 +1,6 @@
package org.chtijbug.drools.console.service;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.VaadinSession;
import org.chtijbug.drools.ReverseProxyUpdate;
import org.chtijbug.drools.common.KafkaTopicConstants;
import org.chtijbug.drools.console.AddLog;
@ -20,10 +19,7 @@ import org.springframework.context.annotation.DependsOn;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
@DependsOn("applicationContext")
@ -41,6 +37,13 @@ public class ProjectPersistService {
private KieConfigurationData config;
@Autowired
private UserRepository userRepository;
@Autowired
private UserRolesRepository userRolesRepository;
@Autowired
private UserConnectedService userConnectedService;
@ -62,6 +65,8 @@ public class ProjectPersistService {
@Autowired
private KafkaTemplate<String, ReverseProxyUpdate> kafkaTemplateProxyUpdate;
@Autowired
private UserGroupsRepository userGroupsRepository;
public ProjectPersistService() {
@ -69,58 +74,102 @@ public class ProjectPersistService {
}
public ProjectPersist saveorUpdateProject(PlatformProjectData platformProjectData, KieWorkbench kieWorkbench) {
ProjectPersist projectPersist = projectRepository.findByProjectNameAndBranch(new KieProject(platformProjectData.getSpaceName(), platformProjectData.getName()), platformProjectData.getBranch());
public void saveIfnotExist(List<PlatformProjectData> platformProjectResponses, String workbenchName) {
if (projectPersist == null) {
projectPersist = platformProjectResponseToProjectPersist(platformProjectData);
projectPersist.setKieWorkbench(kieWorkbench);
projectPersist.setProjectVersion(platformProjectData.getVersion());
projectPersist.setArtifactID(platformProjectData.getArtifactId());
projectPersist.setGroupID(platformProjectData.getGroupId());
projectPersist.setClassNameList(new ArrayList<>());
for (String className : platformProjectData.getJavaClasses()) {
projectPersist.getClassNameList().add(className);
KieWorkbench kieWorkbench = workbenchRepository.findByName(workbenchName);
for (PlatformProjectData platformProjectResponse : platformProjectResponses) {
ProjectPersist projectPersist = projectRepository.findByProjectNameAndBranch(new KieProject(platformProjectResponse.getSpaceName(), platformProjectResponse.getName()), platformProjectResponse.getBranch());
if (projectPersist == null) {
projectPersist = platformProjectResponseToProjectPersist(platformProjectResponse);
projectPersist.setKieWorkbench(kieWorkbench);
projectPersist = projectRepository.save(projectPersist);
addProjectToSession(projectPersist, true);
} else {
projectPersist.setKieWorkbench(kieWorkbench);
projectPersist.getClassNameList().clear();
for (String className : platformProjectResponse.getJavaClasses()) {
projectPersist.getClassNameList().add(className);
projectRepository.save(projectPersist);
}
addProjectToSession(projectPersist, false);
}
}
}
projectPersist = projectRepository.save(projectPersist);
public Map<String, ProjectPersist> getProjectsSession() {
return (Map<String, ProjectPersist>) VaadinSession.getCurrent().getAttribute(projectVariable);
}
public void addProjectToSession(ProjectPersist projectPersist, boolean isModifiable) {
Map<String, ProjectPersist> projectPersists = getProjectsSession();
if (projectPersists == null) {
projectPersists = new HashMap<>();
}
if (isModifiable) {
projectPersists.put(projectPersist.getProjectName().toString() + "-" + projectPersist.getBranch(), projectPersist);
} else {
projectPersist.setKieWorkbench(kieWorkbench);
projectPersist.setProjectVersion(platformProjectData.getVersion());
projectPersist.setArtifactID(platformProjectData.getArtifactId());
projectPersist.setGroupID(platformProjectData.getGroupId());
projectPersist.setClassNameList(new ArrayList<>());
for (String className : platformProjectData.getJavaClasses()) {
projectPersist.getClassNameList().add(className);
ProjectPersist tmp = projectPersists.get(projectPersist.getProjectName().toString() + "-" + projectPersist.getBranch());
if (tmp == null) {
projectPersists.put(projectPersist.getProjectName().toString() + "-" + projectPersist.getBranch(), projectPersist);
}
projectRepository.save(projectPersist);
}
return projectPersist;
}
public void createProjectGroupIfNeeded(String projectName, KieWorkbench kieWorkbench,ProjectPersist projectPersist,UserGroups workspaceUserGroup ) {
UserGroups userGroups = userGroupsRepository.findByName("prj_" + projectName);
if (userGroups == null) {
UserGroups projectGroup = new UserGroups(UUID.randomUUID().toString(), "prj_" + projectName);
projectGroup.setKieWorkbench(kieWorkbench);
projectGroup.setProjectName(projectName);
projectGroup.setProjectPersist(projectPersist);
projectGroup.setWorkspaceUserGroup(workspaceUserGroup);
userGroupsRepository.save(projectGroup);
User groupUser = new User(UUID.randomUUID().toString(), "prj_user_" + projectName, "adminadmin99#");
groupUser.getUserGroups().add(projectGroup);
groupUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
userRepository.save(groupUser);
}else{
userGroups.setWorkspaceUserGroup(workspaceUserGroup);
userGroupsRepository.save(userGroups);
}
}
public UserGroups createWorkSpaceGroupIfNeeded(String workSpaceName, KieWorkbench kieWorkbench) {
UserGroups userGroupsWorkSpace = userGroupsRepository.findByName("wrk_" + workSpaceName);
if (userGroupsWorkSpace == null) {
userGroupsWorkSpace = new UserGroups(UUID.randomUUID().toString(), "wrk_" + workSpaceName);
userGroupsWorkSpace.setKieWorkbench(kieWorkbench);
userGroupsWorkSpace.setSpaceName(workSpaceName);
userGroupsRepository.save(userGroupsWorkSpace);
User groupUser = new User(UUID.randomUUID().toString(), "wrk_user_" + workSpaceName, "pymma#");
groupUser.getUserGroups().add(userGroupsWorkSpace);
groupUser.getUserRoles().add(userRolesRepository.findByName("analyst"));
userRepository.save(groupUser);
}
VaadinSession.getCurrent().setAttribute(projectVariable, projectPersists);
return userGroupsWorkSpace;
}
public Map<String, ProjectPersist> findProjectsConnectedUser() {
//VaadinSession.getCurrent().get
boolean isAdmin =false;
UserConnected userConnected = userConnectedService.getUserConnected();
User user = userRepository.findByLogin(userConnected.getUserName());
for (UserRoles userRoles : user.getUserRoles()){
if ("admin".equals(userRoles.getName())){
isAdmin=true;
}
}
List<ProjectPersist> projectPersists = new ArrayList<>();
if (isAdmin) {
projectPersists = projectRepository.findAll();
}else {
List<UserGroups> userGroups = user.getUserGroups();
}
Map<String, ProjectPersist> map = new HashMap<>();
for (ProjectPersist projectPersist : projectPersists){
map.put(projectPersist.getProjectName().toString() + "-" + projectPersist.getBranch(),projectPersist);
}
return map;
}
public boolean associate(ProjectPersist projectPersist, List<RuntimePersist> runtimePersists) {
projectPersist.setStatus(ProjectPersist.Deployable);
projectPersist.setContainerID(projectPersist.getDeploymentName() + "-" + projectPersist.getProjectName());
@ -148,7 +197,6 @@ public class ProjectPersistService {
reverseProxyUpdate.getServerNames().add(hostName);
}
projectRepository.save(projectPersist);
addProjectToSession(projectPersist, true);
kafkaTemplateProxyUpdate.send(KafkaTopicConstants.REVERSE_PROXY, reverseProxyUpdate);
return true;
}
@ -175,7 +223,6 @@ public class ProjectPersistService {
}
public void waitForJobToBeEnded(String url, String username, String password, ProjectPersist projectPersist, AddLog workOnGoingView, UI ui) {
UserConnected userConnected = userConnectedService.getUserConnected();
@ -195,7 +242,6 @@ public class ProjectPersistService {
jobService.executeWrite(url, username, password, workOnGoingView, result.getJobId(), ui);
for (String serverName : projectPersist.getServerNames()) {
@ -224,7 +270,6 @@ public class ProjectPersistService {
}
public ProjectRepository getProjectRepository() {
return projectRepository;
}

View file

@ -1,6 +1,8 @@
package org.chtijbug.drools.console.service.model.kie;
public class KieConfigurationData {
import java.io.Serializable;
public class KieConfigurationData implements Serializable {
private String kiewbUrl;

View file

@ -112,7 +112,6 @@ public class DefineProject extends VerticalLayout {
if (createMode) {
projectPersist.setStatus(ProjectPersist.DEFINI);
}
projectPersistService.addProjectToSession(projectPersist,true);
projectPersistService.getProjectRepository().save(projectPersist);
deploymentView.setDataProvider();
dialog.close();

View file

@ -97,7 +97,7 @@ public class GridRuntime extends Grid<RuntimePersist> {
branch.addValueChangeListener(e -> {
refreshtGrid(branch.getValue(), strBranch);
});
versionCo.setHeader(branch);
statusCo.setHeader(branch);
Grid.Column<RuntimePersist> branchCo = addColumn(runtimePersist -> runtimePersist.getStatus());
status = new TextField(strStatus);
@ -156,13 +156,9 @@ public class GridRuntime extends Grid<RuntimePersist> {
urlMap.put(runtimePersist.getServerName(), runtimePersist.getServerUrl());
RuntimePersist runtimePersist1 = runtimePersist.duplicate();
if (projectPersist != null) {
runtimeToShow.add(runtimePersist1);
if (projectPersist.getServerNames().contains(runtimePersist1.getServerName())) {
runtimeToShow.add(runtimePersist1);
getSelectionModel().select(runtimePersist1);
} else {
if (projectPersist.getServerNames().size() == 0){
runtimeToShow.add(runtimePersist1);
}
}
}else{
runtimeToShow.add(runtimePersist1);

View file

@ -17,12 +17,13 @@ import org.springframework.data.domain.PageRequest;
import java.util.List;
public class ActionLogging extends VerticalLayout {
private static String active="active";
private Button viewAction;
private TextFieldPerso transactionIdSearch;
private IndexerService indexerService;
private transient IndexerService indexerService;
public ActionLogging(LoggingView loggingView){
@ -78,17 +79,17 @@ public class ActionLogging extends VerticalLayout {
}
private boolean isActive(Button button){
return button.getClassNames().contains("active");
return button.getClassNames().contains(active);
}
private void removeActive(Button button) {
if(button.getClassNames().contains("active")){
button.getClassNames().remove("active");
if(button.getClassNames().contains(active)){
button.getClassNames().remove(active);
}
}
private void active(Button button){
removeActive(viewAction);
button.getClassNames().add("active");
button.getClassNames().add(active);
}
public Button getViewAction() {

View file

@ -3,9 +3,13 @@ package org.chtijbug.drools.console.vaadincomponent.leftMenu.Action;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import org.chtijbug.drools.console.service.ProjectPersistService;
import org.chtijbug.drools.console.service.util.AppContext;
import org.chtijbug.drools.console.vaadincomponent.componentperso.ComboBoxPerso;
import org.chtijbug.drools.console.view.TemplateView;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectData;
import org.chtijbug.drools.proxy.persistence.model.ProjectPersist;
import java.util.Map;
public class TemplatesAction extends VerticalLayout {
@ -15,16 +19,20 @@ public class TemplatesAction extends VerticalLayout {
private Button edit;
private ComboBoxPerso<PlatformProjectData> spaceSelection;
private ComboBoxPerso<ProjectPersist> spaceSelection;
private ProjectPersistService projectPersistService;
public TemplatesAction(TemplateView templateView){
setClassName("leftMenu-global-action");
projectPersistService = AppContext.getApplicationContext().getBean(ProjectPersistService.class);
Map<String, ProjectPersist> map = projectPersistService.findProjectsConnectedUser();
spaceSelection = new ComboBoxPerso<>("Project",VaadinIcon.SEARCH.create());
spaceSelection.getComboBox().setItems(templateView.getUserConnectedService().getUserConnected().getProjectResponses());
spaceSelection.getComboBox().setItemLabelGenerator(PlatformProjectData::getName);
spaceSelection.getComboBox().setItems(map.values());
spaceSelection.getComboBox().setItemLabelGenerator(ProjectPersist::getKieProjectName);
spaceSelection.getComboBox().addValueChangeListener(valueChangeEvent -> {
templateView.setDataProvider(spaceSelection.getComboBox());
});

View file

@ -130,7 +130,7 @@ public class FormulaireComposant extends VerticalLayout {
if(connected!=null) {
connected.setConnected(true);
userConnectedService.addUserToSession(connected);
projectPersistService.saveIfnotExist(connected.getProjectResponses(),configKie.getName());
//projectPersistService.saveIfnotExist(connected.getProjectResponses(),configKie.getName());
return true;
}else {

View file

@ -28,7 +28,7 @@ public class MenuSecondaireAssets extends HorizontalLayout {
TemplateView templateView=new TemplateView();
TemplatesAction templatesAction=new TemplatesAction(templateView);
templateView.setTemplatesAction(templatesAction);
squeletteComposant.navigate(templateView,TemplateView.pageName,templatesAction);
squeletteComposant.navigate(templateView,TemplateView.PAGE_NAME,templatesAction);
});
}
private boolean isActive(Button button){

View file

@ -10,6 +10,7 @@ import org.chtijbug.drools.console.view.LoggingView;
@StyleSheet("css/accueil.css")
public class MenuSecondaireLogging extends HorizontalLayout {
private static String active="active";
private Button logging;
@ -30,23 +31,23 @@ public class MenuSecondaireLogging extends HorizontalLayout {
ActionLogging actionLogging=new ActionLogging(loggingView);
loggingView.setActionLogging(actionLogging);
squeletteComposant.navigate(loggingView,LoggingView.pageName,actionLogging);
squeletteComposant.navigate(loggingView,LoggingView.PAGE_NAME,actionLogging);
});
}
private boolean isActive(Button button){
return button.getClassNames().contains("active");
return button.getClassNames().contains(active);
}
private void removeActive(Button button) {
if(button.getClassNames().contains("active")){
button.getClassNames().remove("active");
if(button.getClassNames().contains(active)){
button.getClassNames().remove(active);
}
}
private void active(Button button){
removeActive(logging);
button.getClassNames().add("active");
button.getClassNames().add(active);
}
public Button getLogging() {

View file

@ -213,7 +213,7 @@ public class DeploymentView extends VerticalLayout implements AddLog {
public void setDataProvider() {
Map<String, ProjectPersist> projectPersists = projectPersistService.getProjectsSession();
Map<String, ProjectPersist> projectPersists = projectPersistService.findProjectsConnectedUser();
if (projectPersists != null) {
ListDataProvider<ProjectPersist> dataProvider = new ListDataProvider<>(projectPersists.values());
filterDataProvider = dataProvider.withConfigurableFilter();

View file

@ -9,7 +9,7 @@ import org.chtijbug.drools.console.vaadincomponent.leftMenu.Action.ActionLogging
@StyleSheet("css/accueil.css")
public class LoggingView extends VerticalLayout {
public static final String pageName="Logging";
public static final String PAGE_NAME = "Logging";
private Label title;
@ -17,29 +17,25 @@ public class LoggingView extends VerticalLayout {
private ActionLogging actionLogging;
public LoggingView(){
public LoggingView() {
title=new Label("Logging : ");
title = new Label("Logging : ");
add(title);
gridLogging=new GridLogging();
gridLogging = new GridLogging();
add(gridLogging);
gridLogging.addSelectionListener(selectionEvent -> {
gridLogging.addSelectionListener(selectionEvent ->
actionLogging.getViewAction().setEnabled(selectionEvent.getFirstSelectedItem().isPresent())
if(selectionEvent.getFirstSelectedItem().isPresent()) {
actionLogging.getViewAction().setEnabled(true);
}else {
actionLogging.getViewAction().setEnabled(false);
}
});
);
}
public static String getPageName() {
return pageName;
return PAGE_NAME;
}
public GridLogging getGridLogging() {

View file

@ -10,14 +10,17 @@ import com.vaadin.flow.data.provider.ListDataProvider;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.function.SerializablePredicate;
import org.chtijbug.drools.console.service.KieRepositoryService;
import org.chtijbug.drools.console.service.ProjectPersistService;
import org.chtijbug.drools.console.service.UserConnectedService;
import org.chtijbug.drools.console.service.model.UserConnected;
import org.chtijbug.drools.console.service.model.kie.KieConfigurationData;
import org.chtijbug.drools.console.service.util.AppContext;
import org.chtijbug.drools.console.vaadincomponent.componentperso.DialogPerso;
import org.chtijbug.drools.console.vaadincomponent.leftMenu.Action.TemplatesAction;
import org.chtijbug.drools.proxy.persistence.model.ProjectPersist;
import org.chtijbug.drools.proxy.persistence.model.UserGroups;
import org.chtijbug.drools.proxy.persistence.repository.UserGroupsRepository;
import org.chtijbug.guvnor.server.jaxrs.jaxb.Asset;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectData;
import java.util.ArrayList;
import java.util.List;
@ -27,15 +30,19 @@ import java.util.Set;
@StyleSheet("css/accueil.css")
public class TemplateView extends VerticalLayout {
public static final String pageName="Templates";
public static final String PAGE_NAME = "Templates";
private KieConfigurationData config;
private transient KieConfigurationData config;
private KieRepositoryService kieRepositoryService;
private transient KieRepositoryService kieRepositoryService;
private UserConnected userConnected;
private transient UserConnected userConnected;
private UserConnectedService userConnectedService;
private transient UserConnectedService userConnectedService;
private transient UserGroupsRepository userGroupsRepository;
private transient ProjectPersistService projectPersistService;
private ListDataProvider<Asset> dataProvider;
@ -43,7 +50,7 @@ public class TemplateView extends VerticalLayout {
private TextField searchTemplate;
private ConfigurableFilterDataProvider<Asset,Void,SerializablePredicate<Asset>> filterDataProvider;
private ConfigurableFilterDataProvider<Asset, Void, SerializablePredicate<Asset>> filterDataProvider;
private TemplatesAction templatesAction;
@ -51,66 +58,80 @@ public class TemplateView extends VerticalLayout {
setClassName("template-content");
dataProvider=new ListDataProvider<>(new ArrayList<>());
dataProvider = new ListDataProvider<>(new ArrayList<>());
filterDataProvider = dataProvider.withConfigurableFilter();
this.kieRepositoryService = AppContext.getApplicationContext().getBean(KieRepositoryService.class);
this.userConnectedService = AppContext.getApplicationContext().getBean(UserConnectedService.class);
this.userGroupsRepository = AppContext.getApplicationContext().getBean(UserGroupsRepository.class);
this.userConnected = userConnectedService.getUserConnected();
this.projectPersistService = AppContext.getApplicationContext().getBean(ProjectPersistService.class);
this.config = AppContext.getApplicationContext().getBean(KieConfigurationData.class);
assetListGrid = new Grid();
assetListGrid = new Grid<>();
assetListGrid.setClassName("templates-grid-perso");
assetListGrid.setSelectionMode(Grid.SelectionMode.SINGLE);
Grid.Column<Asset> assetColumn=assetListGrid.addColumn(asset -> asset.getTitle());
searchTemplate=new TextField("title");
Grid.Column<Asset> assetColumn = assetListGrid.addColumn(Asset::getTitle);
searchTemplate = new TextField("title");
searchTemplate.setValueChangeMode(ValueChangeMode.EAGER);
searchTemplate.addValueChangeListener(e -> {
refreshtGrid(searchTemplate.getValue(), "title");
});
searchTemplate.addValueChangeListener(e ->
refreshtGrid(searchTemplate.getValue(), "title")
);
assetColumn.setHeader(searchTemplate);
add(assetListGrid);
assetListGrid.addSelectionListener(selectionEvent -> {
if(assetListGrid.getSelectedItems()==null){
templatesAction.getEdit().setEnabled(false);
}else {
templatesAction.getEdit().setEnabled(true);
}
});
assetListGrid.addSelectionListener(selectionEvent ->
templatesAction.getEdit().setEnabled(assetListGrid.getSelectedItems() != null)
);
}
public void setDataProvider(ComboBox<PlatformProjectData> spaceSelection){
PlatformProjectData response = spaceSelection.getValue();
List<Asset> tmp = kieRepositoryService.getListAssets(config.getKiewbUrl(), userConnected.getUserName(), userConnected.getUserPassword(), response.getSpaceName(), response.getName());
List<Asset> result = new ArrayList<>();
for (Asset asset : tmp) {
if (asset.getTitle().endsWith(".template")
|| asset.getTitle().endsWith(".gdst")) {
result.add(asset);
public void setDataProvider(ComboBox<ProjectPersist> spaceSelection) {
ProjectPersist response = spaceSelection.getValue();
if (response != null) {
UserGroups projectGroups = userGroupsRepository.findUserGroupsByProjectPersist(response);
String workspaceName = projectGroups.getWorkspaceUserGroup().getSpaceName();
List<Asset> tmp = kieRepositoryService.getListAssets(config.getKiewbUrl(),
userConnected.getUserName(),
userConnected.getUserPassword(),
workspaceName,
projectGroups.getProjectName());
List<Asset> result = new ArrayList<>();
for (Asset asset : tmp) {
if (asset.getTitle().endsWith(".template")
|| asset.getTitle().endsWith(".gdst")) {
result.add(asset);
}
}
dataProvider = new ListDataProvider<>(result);
filterDataProvider = dataProvider.withConfigurableFilter();
assetListGrid.setDataProvider(filterDataProvider);
reinitFilter();
} else {
List<Asset> result = new ArrayList<>();
dataProvider = new ListDataProvider<>(result);
filterDataProvider = dataProvider.withConfigurableFilter();
assetListGrid.setDataProvider(filterDataProvider);
reinitFilter();
}
dataProvider=new ListDataProvider<>(result);
filterDataProvider = dataProvider.withConfigurableFilter();
assetListGrid.setDataProvider(filterDataProvider);
reinitFilter();
}
public void refreshList(ComboBox<PlatformProjectData> spaceSelection) {
spaceSelection.setItems(userConnected.getProjectResponses());
public void refreshList(ComboBox<ProjectPersist> spaceSelection) {
spaceSelection.setItems(projectPersistService.findProjectsConnectedUser().values());
}
public void edit(ComboBox<PlatformProjectData> spaceSelection){
public void edit(ComboBox<ProjectPersist> spaceSelection) {
Set<Asset> selectedElements = assetListGrid.getSelectedItems();
if (selectedElements.toArray().length > 0) {
Optional<Asset> assetOptional = selectedElements.stream().findFirst();
if (assetOptional.isPresent()) {
String assetName = assetOptional.get().getTitle();
if (assetName != null) {
PlatformProjectData response = spaceSelection.getValue();
userConnectedService.addAssetToSession(assetName);
userConnectedService.addProjectToSession(response.getName());
userConnectedService.addSpaceToSession(response.getSpaceName());
UserGroups projectGroups = userGroupsRepository.findUserGroupsByProjectPersist(spaceSelection.getValue());
String workspaceName = projectGroups.getWorkspaceUserGroup().getSpaceName();
userConnectedService.addProjectToSession(projectGroups.getProjectName());
userConnectedService.addSpaceToSession(workspaceName);
DialogPerso dialog = new DialogPerso();
dialog.add(new EditTemplateView(dialog, assetName));
@ -119,16 +140,18 @@ public class TemplateView extends VerticalLayout {
}
}
}
private void refreshtGrid(String value,String type){
filterDataProvider.setFilter(filterGrid(value.toUpperCase(),type));
private void refreshtGrid(String value, String type) {
filterDataProvider.setFilter(filterGrid(value.toUpperCase(), type));
assetListGrid.getDataProvider().refreshAll();
}
private SerializablePredicate<Asset> filterGrid(String value, String type){
private SerializablePredicate<Asset> filterGrid(String value, String type) {
SerializablePredicate<Asset> columnPredicate = null;
if(value.equals(" ")||type.equals(" ")){
if (value.equals(" ") || type.equals(" ")) {
columnPredicate = asset -> (true);
}else {
} else {
if (type.equals("Asset Title")) {
columnPredicate = asset -> (asset.getTitle().contains(value));
}
@ -144,9 +167,11 @@ public class TemplateView extends VerticalLayout {
this.userConnectedService = userConnectedService;
}
public void duplicate(){}
public void duplicate() {
//NOP
}
public void reinitFilter(){
public void reinitFilter() {
searchTemplate.setValue("");
}

View file

@ -1,7 +1,7 @@
server.port=${port:8200}
kie-wb.baseurl=${PYMMA_KIE_BASE_URL:http://localhost:18080/kie-wb/rest}
kie-wb.mainwbintern=${PYMMA_KIE_MAINWBINTERN:http://localhost:8080/kie-wb}
kie-wb.mainwbextern=${PYMMA_KIE_MAINWBEXTERN:http://localhost:8080/kie-wb}
kie-wb.mainwbextern=${PYMMA_KIE_MAINWBEXTERN:http://localhost:18080/kie-wb}
kie-wb.username=${PYMMA_KIE_USER:admin}
kie-wb.password=${PYMMA_KIE_PASSWORD:admin}

View file

@ -16,7 +16,9 @@
package org.chtijbug.guvnor.uberfire.security;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@ -37,6 +39,8 @@ import org.uberfire.ext.security.management.util.SecurityManagementUtils;
import java.util.*;
import static com.mongodb.client.model.Filters.eq;
/**
* <p>Groups manager service provider implementation for Apache tomcat, when using default realm based on properties files.</p>
* @since 0.8.0
@ -85,14 +89,39 @@ public class KiePlatformGroupManager implements GroupManager, ContextualManager
@Override
public SearchResponse<Group> search(SearchRequest request) throws SecurityManagementException {
SearchResponse<Group> result = new SearchResponseImpl<>();
return result;
MongoCollection<Document> userCollection = database.getCollection("userGroups");
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name", new BasicDBObject("$regex", request.getSearchPattern() + ".*").append("$options", "i"));
List<Group> groups = new ArrayList<>();
long totalNumber = userCollection.countDocuments(regexQuery);
FindIterable<Document> documents = userCollection.find(regexQuery).skip(request.getPageSize() * (request.getPage() - 1)).limit(request.getPageSize());
documents.forEach((Block<? super Document>) document -> {
String groupName = document.getString("name");
Group group = new GroupImpl(groupName);
groups.add(group);
});
boolean hasNextPage = true;
if ((request.getPageSize() * (request.getPage()) > totalNumber)) {
hasNextPage = false;
}
SearchResponse<Group> response = new SearchResponseImpl(groups, request.getPage(), request.getPageSize(), Long.valueOf(totalNumber).intValue(), hasNextPage);
return response;
}
@Override
public Group get(String identifier) throws SecurityManagementException {
Group group = new GroupImpl(identifier);
return group;
MongoCollection<Document> userCollection = database.getCollection("userGroups");
List<Group> groups = new ArrayList<>();
userCollection.find(eq("name", identifier)).forEach((Block<? super Document>) document -> {
String groupName = document.getString("name");
Group group = new GroupImpl(groupName);
groups.add(group);
});
if (groups.size() == 1) {
return groups.get(0);
} else {
return null;
}
}
@Override

View file

@ -16,7 +16,9 @@
package org.chtijbug.guvnor.uberfire.security;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@ -38,6 +40,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.mongodb.client.model.Filters.eq;
/**
* <p>Groups manager service provider implementation for Apache tomcat, when using default realm based on properties files.</p>
*
@ -85,14 +89,39 @@ public class KiePlatformRoleManager implements RoleManager, ContextualManager {
@Override
public SearchResponse<Role> search(SearchRequest request) throws SecurityManagementException {
SearchResponse<Role> roleSearchResponse = new SearchResponseImpl<>();
return roleSearchResponse;
MongoCollection<Document> roleCollection = database.getCollection("userRoles");
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name", new BasicDBObject("$regex", request.getSearchPattern() + ".*").append("$options", "i"));
List<Role> roles = new ArrayList<>();
long totalNumber = roleCollection.countDocuments(regexQuery);
FindIterable<Document> documents = roleCollection.find(regexQuery).skip(request.getPageSize() * (request.getPage() - 1)).limit(request.getPageSize());
documents.forEach((Block<? super Document>) document -> {
String roleName = document.getString("name");
Role role = new RoleImpl(roleName);
roles.add(role);
});
boolean hasNextPage = true;
if ((request.getPageSize() * (request.getPage()) > totalNumber)) {
hasNextPage = false;
}
SearchResponse<Role> response = new SearchResponseImpl(roles, request.getPage(), request.getPageSize(), Long.valueOf(totalNumber).intValue(), hasNextPage);
return response;
}
@Override
public Role get(String identifier) throws SecurityManagementException {
RoleImpl role = new RoleImpl(identifier);
return role;
MongoCollection<Document> userCollection = database.getCollection("userRoles");
List<Role> roles = new ArrayList<>();
userCollection.find(eq("name", identifier)).forEach((Block<? super Document>) document -> {
String roleName = document.getString("name");
Role role = new RoleImpl(roleName);
roles.add(role);
});
if (roles.size() == 1) {
return roles.get(0);
} else {
return null;
}
}
@Override

View file

@ -42,7 +42,7 @@ public class KiePlatformSecurityService implements UserManagementService {
//-DconnectionString=localhost:28017 -Ddatabase=businessProxyDB
this.connectionString = System.getProperty("connectionString");
this.databaseName=System.getProperty("database");
this.databaseName=System.getProperty("name");
System.out.println("KiePlatformSecurityService initialized with databaseName = " + connectionString );
this.mongoClient = MongoClients.create(connectionString);
this.pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),

View file

@ -25,7 +25,6 @@ import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.types.ObjectId;
import org.jboss.errai.security.shared.api.Group;
import org.jboss.errai.security.shared.api.GroupImpl;
import org.jboss.errai.security.shared.api.Role;
@ -179,7 +178,7 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
MongoCollection<Document> userRolesCollection = database.getCollection("userRoles");
AtomicReference<ArrayList<DBRef>> roles = new AtomicReference<>(new ArrayList<>());
AtomicReference<ArrayList<DBRef>> groups = new AtomicReference<>(new ArrayList<>());
List<Document> users = new ArrayList<>();
ArrayList<Document> users = new ArrayList<>();
if (isCreated) {
userCollection.find(eq("login", entity.getIdentifier())).forEach((Block<? super Document>) document -> {
throw new SecurityManagementException("Existing identifier " + entity.getIdentifier());
@ -211,15 +210,21 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
roles.get().add(dbRef);
});
}
Document userDocument = new Document("_id", new ObjectId());
userDocument.append("login", entity.getIdentifier());
userDocument.append("password", entity.getIdentifier());
userDocument.append("userRoles", roles);
userDocument.append("userGroups", groups);
if (isCreated) {
Document userDocument = new Document();
userDocument.append("login", entity.getIdentifier());
userDocument.append("password", entity.getIdentifier());
userDocument.append("userRoles", roles);
userDocument.append("userGroups", groups);
userCollection.insertOne(userDocument);
} else {
userCollection.replaceOne(eq("login", entity.getIdentifier()), userDocument);
userCollection.find(eq("login", entity.getIdentifier())).forEach((Block<? super Document>) document -> {
document.append("userRoles", roles);
document.append("userGroups", groups);
userCollection.replaceOne(eq("login", entity.getIdentifier()), document);
});
}
}

View file

@ -34,6 +34,12 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.uberfire</groupId>
<artifactId>uberfire-rest-backend</artifactId>
<version>${jbpm.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.kie</groupId>

View file

@ -11,6 +11,7 @@ import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.POM;
import org.guvnor.common.services.project.model.WorkspaceProject;
import org.guvnor.common.services.project.service.WorkspaceProjectService;
import org.guvnor.rest.backend.UserManagementResourceHelper;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.guvnor.structure.repositories.Branch;
@ -18,10 +19,14 @@ import org.guvnor.structure.repositories.Repository;
import org.guvnor.structure.repositories.RepositoryService;
import org.kie.workbench.common.screens.datamodeller.service.DataModelerService;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.authz.AuthorizationService;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.base.options.CommentedOption;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.Paths;
import org.uberfire.security.authz.AuthorizationPolicy;
import org.uberfire.security.authz.PermissionManager;
import org.uberfire.security.impl.authz.AuthorizationPolicyBuilder;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ -63,7 +68,13 @@ public class PackageResource {
private WorkspaceProjectService workspaceProjectService;
@Inject
private AssetService assetService;
@Inject
private PermissionManager permissionManager;
@Inject
private AuthorizationService authorizationService;
@Inject
private UserManagementResourceHelper userManagementResourceHelper;
public PackageResource() {
System.out.println("coucou");
@ -76,6 +87,22 @@ public class PackageResource {
UserLoginInformation userLoginInformation = new UserLoginInformation();
userLoginInformation.setUsername(sc.getUserPrincipal().getName());
for (String role : PermissionConstants.tableauChaine) {
if (sc.isUserInRole(role) == true) {
userLoginInformation.getRoles().add(role);
}
}
return userLoginInformation;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/content")
public UserLoginInformation getUserContent() {
UserLoginInformation userLoginInformation = new UserLoginInformation();
userLoginInformation.setUsername(sc.getUserPrincipal().getName());
for (String role : PermissionConstants.tableauChaine) {
if (sc.isUserInRole(role) == true) {
@ -86,7 +113,6 @@ public class PackageResource {
return userLoginInformation;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/detailedSpaces")
@ -123,6 +149,8 @@ public class PackageResource {
return null;
}
@GET
@Path("{organizationalUnitName}/{projectName}/assets")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@ -435,4 +463,21 @@ public class PackageResource {
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/auth")
public AuthorizationPolicy getAuth() {
AuthorizationPolicy authorizationPolicy = this.permissionManager.getAuthorizationPolicy();
return authorizationPolicy;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/auth2")
public AuthorizationPolicy getAuth2() {
AuthorizationPolicyBuilder tata = this.permissionManager.newAuthorizationPolicy();
AuthorizationPolicy authorizationPolicy = this.permissionManager.getAuthorizationPolicy();
return authorizationPolicy;
}
}

View file

@ -86,6 +86,9 @@ public class AssetService {
return repoNames;
}
public void todo(){
// workspaceProjectService.
}

View file

@ -34,6 +34,7 @@ public class ProjectPersist implements Serializable {
@DBRef
private KieWorkbench kieWorkbench;
private KieProject projectName;
private String mainClass;
@ -179,6 +180,18 @@ public class ProjectPersist implements Serializable {
this.serverNames = serverNames;
}
public String getWorkspaceName(){
if (this.projectName!= null){
return projectName.getSpaceName();
}
return null;
}
public String getKieProjectName(){
if (this.projectName!= null){
return projectName.getName()+"-"+this.branch;
}
return null;
}
public ProjectPersist duplicate(){
ArrayList<String> listServerNames = new ArrayList<String>();
listServerNames.addAll(serverNames);

View file

@ -2,6 +2,7 @@ package org.chtijbug.drools.proxy.persistence.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@ -16,7 +17,14 @@ public class UserGroups {
@Indexed
private String projectName;
@DBRef
private KieWorkbench kieWorkbench;
@DBRef
private ProjectPersist projectPersist;
@DBRef
private UserGroups workspaceUserGroup;
public UserGroups() {
}
@ -58,4 +66,28 @@ public class UserGroups {
this.projectName = projectName;
}
public KieWorkbench getKieWorkbench() {
return kieWorkbench;
}
public void setKieWorkbench(KieWorkbench kieWorkbench) {
this.kieWorkbench = kieWorkbench;
}
public ProjectPersist getProjectPersist() {
return projectPersist;
}
public void setProjectPersist(ProjectPersist projectPersist) {
this.projectPersist = projectPersist;
}
public UserGroups getWorkspaceUserGroup() {
return workspaceUserGroup;
}
public void setWorkspaceUserGroup(UserGroups workspaceUserGroup) {
this.workspaceUserGroup = workspaceUserGroup;
}
}

View file

@ -1,5 +1,6 @@
package org.chtijbug.drools.proxy.persistence.repository;
import org.chtijbug.drools.proxy.persistence.model.ProjectPersist;
import org.chtijbug.drools.proxy.persistence.model.UserGroups;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@ -9,4 +10,6 @@ public interface UserGroupsRepository extends MongoRepository<UserGroups, String
UserGroups findByName(String login);
UserGroups findByID(String login);
UserGroups findUserGroupsByProjectPersist(ProjectPersist projectPersist);
}

View file

@ -30,7 +30,7 @@ public class CustomMappingsProvider extends MappingsProvider {
@Override
public MappingProperties resolveMapping(String originUri, HttpServletRequest request) {
MappingProperties result = mappingPropertiesMap.get(originUri);
MappingProperties result = mappingPropertiesMap.get(UpdateService.removeSlach(originUri));
if (result!= null){
return result;
}else {

View file

@ -49,7 +49,7 @@ public class UpdateService {
public void store(ReverseProxyUpdate update) {
boolean found = false;
for (MappingProperties mappingProperties : mappingPropertiesMap.values()) {
if (mappingProperties.getPath().equals(update.getPath())) {
if (UpdateService.removeSlach(mappingProperties.getPath()).equals(UpdateService.removeSlach(update.getPath()))) {
found = true;
mappingProperties.getDestinations().clear();
logger.info("Updating path {}",update.getPath());
@ -69,7 +69,7 @@ public class UpdateService {
newMappingProperties.getDestinations().add(destination);
logger.info("for path {} adding server {} ",update.getPath(),destination);
}
mappingPropertiesMap.put(update.getPath(), newMappingProperties);
mappingPropertiesMap.put(UpdateService.removeSlach(update.getPath()), newMappingProperties);
}
mappings.clear();
mappings.addAll(mappingPropertiesMap.values());
@ -81,6 +81,13 @@ public class UpdateService {
return mappings;
}
public static String removeSlach(String target){
if (target!= null) {
return target.replace("/", "");
}
return null;
}
private void generateMappings() {
projects.clear();
mappingPropertiesMap.clear();
@ -118,7 +125,7 @@ public class UpdateService {
mappingProperties2.getCustomConfiguration().put("read", 2000);
mappingProperties2.setStripPath(true);
if (mappingProperties2.getDestinations().size() > 0) {
mappingPropertiesMap.put(mappingProperties2.getPath(), mappingProperties2);
mappingPropertiesMap.put(UpdateService.removeSlach(mappingProperties2.getPath()), mappingProperties2);
paths.add(mappingProperties2);
logger.info("Startup creating path {}",mappingProperties2.getPath());
for (String serverName : mappingProperties2.getDestinations()){

View file

@ -1,19 +1,9 @@
To run the platform, we ecourage you to use the docker containers build with maven
To be able to build the docker container, active the profiles as follow
mvn clean install -Pdev,docker-build
we have a docker-compose file.
As we are using sso, you have in your /etc/hosts to add a line :
YourHostIPnotLocalhost host.docker
then on the root
docker-compose up -d
This the Kie Platform.
the workbench will be at the following url : htto://host.docker:8080/kie-wb
We need an ip visible from your browser when used as a callback once identified
[Extending the standard tooling](wiki/KieStandardTooling.md)
A test

122
wiki/KieStandardTooling.md Normal file
View file

@ -0,0 +1,122 @@
# Kie Platform extending standard drools Tooling
----
## Kie standard tools
The drools community is providing a certain numbers of tools :
1. An api provided as a Apache Maven dependency. This is the classical approach used since drools exists
2. An eclipse plugin to assist us in writing drools native language called « drl ». This plugin allows also to authors bpmn2 files for the jbpm library
3. a web application called « Business Central » that allows to handle the complete lifecycle of a drools/jbpm project
4. A runtime server, called « lie-server » that has a number of extension for standard components of the kielbasas community : drools, jbpm, optaplanner, etc.
To use the kie-server there are two possibilities :
1. use it as a standalone server
2. link it to a business central and deploy components from the user interface
In case 2, the connection only handles a set of kie-servers, this can be use in development mode and In case 1, you have to call the rest interfaces to start using components.
The drools community is the the kie=knowledge is everything and has its own we site : [http://kie.org/][1]
And by visiting it, you can see that there fours parts :
- Kogito : it is called the next generation platform and targets the micro-profile approach by allowing to embed in your applications a cloud-native approach components that uses the
- Quarkus : [https://quarkus.io/][2],
- GrallVM virtual machine [https://www.graalvm.org/][3],
- DMN notation [https://www.omg.org/dmn/][4]to model the business rules (it an OMG standard for modeling and running rules that is supported by most rule providers on the market),
- and the DMN runtime with drools which is the reference implementation, it as a technology compatibility Kit [https://github.com/dmn-tck/tck][5]. You can see here the test results [https://dmn-tck.github.io/tck/index.html][6]and all supported and supporting tools.
- Optaplanner : it is a constraint solver that offers an Api to use it. It uses drools as one possibility to implement business constraints.
- Jbpm : bpmn2 implementation that allows to run Business processes.
- Drools : rule engine that has a forward-chaining and backward-chaining inference algorithm to implement in an efficient way the business rules we want it to implement.
Our Kie Platform is focusing exclusively on drools for the moment.
## Apache Maven
Starting with version 6.x of drools, Apache Maven is the only possiblility to compile and build a runtime jar for drools project (the same applies to jbpm, Optaplanner and Kogito).
The drools compiler is provided as an Apache Maven plugin.
A drools project is now an Apache Maven module and is adding a new packaging type: « Kjar ». This means a drools project can now be added to any other project as an Apache Maven dependency.
The usage of standard Continuous Integration (CI) tools allows to build and deploy java applications using drools Apache Maven module/artefact :
- git serveur to store the source code (Gitlab, Github, etc..)
- jenkins to build the drools component
- Nexus to store the constructed Kjar to make it available to other projects
## Business Central
Business Central is a web application that handles the complete lifecycle of a drools project (a maven module).
- Authoring different rule artefact types : native drools rule, guided rules, guided rules template, Decision tables, etc..
- multi-user management,
- handles the history of all modifications using git behind,
- allows to define git hooks to push every modification to an outside git server, in the near future, we shall provide a git Gerrit server ([https://en.wikipedia.org/wiki/Gerrit\_(software)][7] ) that would contain all rule modules as a copy of all modification done on Business central [https://github.com/pymma/pymma-kie-platform/issues/149][8]
- exposes each module the git repository using git/http network protocol,
- compiles and builds rule artefacts using Apache Maven behind,
- stores all rule Apache Maven artefacts and all dependencies in its own Apache Maven repository,
- exposes the Apache Maven repository behind http as a normal Apache Maven repository.
Business Central is a complete CI tools by itself and we shall use it for that.
We have added some rest interfaces services to our Kie Plalform Business Central version to facilitate its integration with our platform/
## Execution Server
As already explained, Apache Maven is used to build a Kjar file that contains all artefacts of a drools project.
We can integrate the Kjar in an application that will use it using the standard API of drools.
The other way is to propose a runtime that can dynamically build and expose a Kjar. This is done out of the box by the KieServer proposed by the community as a standard Execution Server.
The rest KieServer extension proposed by the community has the same interface as the API. You have to insert object by object, ask for fireallrules and all is then transmitted to the KieServer in JSON format. On the other side, all is unmarshall and transformed in java instances.
If you have an instance A related to B and you transmit A and the B.
The sequence is
1. Insert A,
2. Insert B that is an attribute of A ,
3. execute fireAllrules.
The JSON message will contain something like this :
```json
{ "commands":[
{
"insert":{
"out-identifier":"CLASSA",
"return-object":"true",
"object": {
"CLASSB":{
"name" : "heron"
}
},
"insert":{
"out-identifier":"CLASSB",
"return-object":"true",
"object": {
"name" : "heron"
}
},
{
"fire-all-rules":""
}
]
}
```
On the server side,
1. instance A will be created with its attribute B and inserted to the working memory. This new A instance will be created with a B instance that is not inserted.
2. Instance B will be created and inserted in the working memory.
3. fireallrules command will be executed
You can see here that when un-marshaling on the other side, there are going to be two instances of CLASSB.
If some rules are using the relation between A and B, here the Object CLASSA has a relation with CLASSB but not for drools as another instance of CLASSB will be inserted which is not the instances linked to the object CLASSA.
## Service Approach for execution server
The standard rest interface obliges the client to insert one by one the java instances to insert into the drools runtime session.
To avoid this, another approach is :
1. use a service approach with java class as the top transmitted object
2. insert all connected instance by reflection following all get/set object and Lists
3. start a jbpm rule flow if needed
4. we shall define an end point like follows :
1. per project and branch
2. a process to start (if needed)
3. the top class to expose.
In our Kie Platform our execution server exposes endpoint like this.
## Missing features
### logging rule execution
The API proposed by drools allows the add callbacks to see what is happening in the engine during its execution.
For many business areas, traceability is key feature that is mandatory. Our platform is offering that functionality : traceability and storing of all execution request. Over the user interface, it is possible to get details of all rule executed, fact inserted/updated/retracted and rule flow executions.
### Logging deployment history
In a production system, each time a deployment is done, informations about should be stored : date, time and git commit ID. It is then possible to create a branch with git from that commit and deploy that precise version. Within the logging feature, the Kie platform shall memorize the commit id of each Apache Maven artefact used to produce the logging.
[errer]()
[1]: http://kie.org/
[2]: https://quarkus.io/
[3]: https://www.graalvm.org/
[4]: https://www.omg.org/dmn/
[5]: https://github.com/dmn-tck/tck
[6]: https://dmn-tck.github.io/tck/index.html
[7]: https://en.wikipedia.org/wiki/Gerrit_(software)
[8]: https://github.com/pymma/pymma-kie-platform/issues/149