Work after Sonarcloud

This commit is contained in:
Nicolas Héron 2020-06-01 16:34:55 +02:00
commit 0a97629aa5
25 changed files with 256 additions and 503 deletions

View file

@ -32,7 +32,7 @@ public class DecisionTableExcelService {
private String assetContent;
public DecisionTableExcelService(){
public DecisionTableExcelService() {
this.kieRepositoryService = AppContext.getApplicationContext().getBean(KieRepositoryService.class);
this.config = AppContext.getApplicationContext().getBean(KieConfigurationData.class);
this.userConnectedService = AppContext.getApplicationContext().getBean(UserConnectedService.class);
@ -48,18 +48,17 @@ public class DecisionTableExcelService {
return assetContent;
}
public List<HashMap<String,Object>> importExcel(InputStream inputStream) throws IOException {
Workbook workbook= WorkbookFactory.create(inputStream);
public List<HashMap<String, Object>> importExcel(InputStream inputStream) throws IOException {
Workbook workbook = null;
List<HashMap<String, Object>> result = null;
try {
workbook = WorkbookFactory.create(inputStream);
result = new ArrayList<>();
DataFormatter dataFormatter = new DataFormatter();
for (Sheet sheet : workbook) {
for (Row row : sheet) {
List<HashMap<String,Object>> result=new ArrayList<>();
for(Sheet sheet: workbook) {
for (Row row: sheet) {
if(row.getRowNum()!=0) {
if (row.getRowNum() != 0) {
HashMap<String, Object> tmp = new HashMap<>();
result.add(tmp);
@ -75,9 +74,16 @@ public class DecisionTableExcelService {
}
}
}
} catch (IOException e) {
throw e;
} finally {
if (workbook != null) {
workbook.close();
}
}
return result;
}
public ByteArrayInputStream exportExcel(String nameTemplate) {
//Récupération des objets JAVA
@ -89,11 +95,10 @@ public class DecisionTableExcelService {
userConnectedService.getProject(),
userConnectedService.getAsset());
GuidedDecisionTable52 model = GuidedDTXMLPersistence.getInstance().unmarshal(assetContent);
Workbook workbook = null;
try {
workbook = new XSSFWorkbook();
DecisionTable decisionTable = new DecisionTable(model);
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet(nameTemplate);
@ -108,9 +113,9 @@ public class DecisionTableExcelService {
if (decisionTable.getRows() != null && decisionTable.getRows().size() != 0) {
int columnIndex = 0;
int j=0;
int j = 0;
for (ColumnDefinition columnDefinition : decisionTable.getColumnDefinitionList()) {
if (columnDefinition.isHideColumn()==false){
if (columnDefinition.isHideColumn() == false) {
Cell cell = headerRow.createCell(j);
cell.setCellValue(columnDefinition.getHeader());
cell.setCellStyle(headerCellStyle);
@ -123,10 +128,10 @@ public class DecisionTableExcelService {
for (int i = 0; i < decisionTable.getRows().size(); i++) {
org.chtijbug.drools.console.vaadinComponent.componentView.service.dtmodel.Row row = decisionTable.getRows().get(i);
int k = 0;
int jj=0;
int jj = 0;
Row r = sheet.createRow(rowIndex);
for (ColumnDefinition columnDefinition : decisionTable.getColumnDefinitionList()) {
if (columnDefinition.isHideColumn()==false) {
if (columnDefinition.isHideColumn() == false) {
Cell cell = r.createCell(k);
cell.setCellValue(row.getRowElements().get(jj).getValue());
cell.setCellStyle(headerCellStyle);
@ -140,7 +145,7 @@ public class DecisionTableExcelService {
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
FileOutputStream fileOutputStream=new FileOutputStream(tmpDir+"/"+nameTemplate+".xlsx");
FileOutputStream fileOutputStream = new FileOutputStream(tmpDir + "/" + nameTemplate + ".xlsx");
workbook.write(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
@ -165,6 +170,14 @@ public class DecisionTableExcelService {
} catch (GuidedException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

View file

@ -31,7 +31,7 @@ public class GuidedRuleTemplateExcelService {
private String assetContent;
public GuidedRuleTemplateExcelService(){
public GuidedRuleTemplateExcelService() {
this.kieRepositoryService = AppContext.getApplicationContext().getBean(KieRepositoryService.class);
this.config = AppContext.getApplicationContext().getBean(KieConfigurationData.class);
this.userConnectedService = AppContext.getApplicationContext().getBean(UserConnectedService.class);
@ -48,37 +48,38 @@ public class GuidedRuleTemplateExcelService {
return assetContent;
}
public List<HashMap<String,Object>> importExcel(InputStream inputStream) throws IOException {
Workbook workbook= WorkbookFactory.create(inputStream);
public List<HashMap<String, Object>> importExcel(InputStream inputStream) throws IOException {
List<HashMap<String, Object>> result = null;
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(inputStream);
DataFormatter dataFormatter = new DataFormatter();
List<HashMap<String,Object>> result=new ArrayList<>();
for(Sheet sheet: workbook) {
for (Row row: sheet) {
if(row.getRowNum()!=0) {
result = new ArrayList<>();
for (Sheet sheet : workbook) {
for (Row row : sheet) {
if (row.getRowNum() != 0) {
HashMap<String, Object> tmp = new HashMap<>();
result.add(tmp);
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell);
Integer numColumn = cell.getColumnIndex();
Cell title = sheet.getRow(0).getCell(numColumn);
tmp.put(dataFormatter.formatCellValue(title), cellValue);
}
}
}
}
} catch (IOException e) {
throw e;
} finally {
if (workbook != null) {
workbook.close();
}
}
return result;
}
public ByteArrayInputStream exportExcel(String nameTemplate){
public ByteArrayInputStream exportExcel(String nameTemplate) {
//Récupération des objets JAVA
@ -117,24 +118,24 @@ public class GuidedRuleTemplateExcelService {
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headerRow=sheet.createRow(0);
Row headerRow = sheet.createRow(0);
if(rows!=null&&rows.size()!=0){
int columnIndex=0;
for(Map.Entry<String,Object> t:rows.get(0).entrySet()){
Cell cell=headerRow.createCell(columnIndex);
if (rows != null && rows.size() != 0) {
int columnIndex = 0;
for (Map.Entry<String, Object> t : rows.get(0).entrySet()) {
Cell cell = headerRow.createCell(columnIndex);
cell.setCellValue(t.getKey());
cell.setCellStyle(headerCellStyle);
columnIndex++;
}
int rowIndex=1;
for(HashMap<String,Object> t:rows) {
int rowIndex = 1;
for (HashMap<String, Object> t : rows) {
int columnIndexTmp=0;
Row r=sheet.createRow(rowIndex);
int columnIndexTmp = 0;
Row r = sheet.createRow(rowIndex);
for (Map.Entry<String, Object> tmp : t.entrySet()) {
Cell cell=r.createCell(columnIndexTmp);
Cell cell = r.createCell(columnIndexTmp);
cell.setCellValue(String.valueOf(tmp.getValue()));
cell.setCellStyle(headerCellStyle);
columnIndexTmp++;
@ -144,7 +145,7 @@ public class GuidedRuleTemplateExcelService {
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
FileOutputStream fileOutputStream=new FileOutputStream(tmpDir+"/"+nameTemplate+".xlsx");
FileOutputStream fileOutputStream = new FileOutputStream(tmpDir + "/" + nameTemplate + ".xlsx");
workbook.write(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();

View file

@ -23,7 +23,7 @@ import java.util.Map;
public class JenkinsService {
JenkinsServer jenkins = null;
public void createJobForRepo(String jenkinsServerUrl, String username, String password, String viewName, String groupId, String artifactId, String pomXml, String nexusName, String nexusUrl, String jdkVersion) throws URISyntaxException, IOException {
public void createJobForRepo(String jenkinsServerUrl, String username, String password, String viewName, String groupId, String artifactId, String pomXml, String nexusName, String nexusUrl, String jdkVersion) throws URISyntaxException, IOException, InterruptedException {
GitLabConfigurationData configGitLab = AppContext.getApplicationContext().getBean(GitLabConfigurationData.class);
JenkinsConfigurationData jenkinsConfigurationData = AppContext.getApplicationContext().getBean(JenkinsConfigurationData.class);
@ -57,9 +57,9 @@ public class JenkinsService {
} else {
synchronized (this) {
try {
Thread.currentThread().wait(1000);
this.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
}
}
}

View file

@ -25,6 +25,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.google.common.base.Throwables.propagate;
@Service
@DependsOn("applicationContext")
public class ProjectPersistService {
@ -229,10 +231,12 @@ public class ProjectPersistService {
} else if ("ACCEPTED".equals(jobStatus.getStatus())
|| ("APPROVED".equals(jobStatus.getStatus()))) {
try {
synchronized (this) {
workOnGoingView.addRow("JobID=" + jobID + " not yet finished", ui);
Thread.sleep(1000);
this.wait(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
propagate(e);
}
} /*else if("RESOURCE_NOT_EXIST".equals(jobStatus.getStatus())||
"SERVER_ERROR".equals(jobStatus.getStatus())||

View file

@ -67,7 +67,7 @@ public class AssociateProjectKie extends VerticalLayout {
});
gridRuntime.addSelectionListener(selectionEvent -> {
if (selectionEvent.getFirstSelectedItem() != null && selectionEvent.getFirstSelectedItem().isPresent()) {
if ( selectionEvent.getFirstSelectedItem().isPresent()) {
associer.setEnabled(true);
} else {

View file

@ -91,7 +91,7 @@ public class ColumnDefinition {
this.header = actionSetFieldCol52.getHeader();
if (actionSetFieldCol52.getDefaultValue() != null) {
DTCellValue52 defaultValue = actionSetFieldCol52.getDefaultValue();
if (!(DataType.TYPE_STRING.equals(defaultValue.getDataType()) && defaultValue.getStringValue().isEmpty())) {
if (!(DataType.DataTypes.STRING.equals(defaultValue.getDataType()) && defaultValue.getStringValue().isEmpty())) {
this.hasDefaultValue = true;
this.defaultValue = getValue(actionSetFieldCol52.getDefaultValue());
}
@ -107,7 +107,7 @@ public class ColumnDefinition {
this.header = actionInsertFact52.getHeader();
if (actionInsertFact52.getDefaultValue() != null) {
DTCellValue52 defaultValue = actionInsertFact52.getDefaultValue();
if (!(DataType.TYPE_STRING.equals(defaultValue.getDataType()) && defaultValue.getStringValue().isEmpty())) {
if (!(DataType.DataTypes.STRING.equals(defaultValue.getDataType()) && defaultValue.getStringValue().isEmpty())) {
this.hasDefaultValue = true;
this.defaultValue = getValue(actionInsertFact52.getDefaultValue());
}

View file

@ -41,7 +41,7 @@ public class GuidedException extends Exception {
}
public void setAttribute(String attribute) {
attribute = attribute;
this.attribute = attribute;
}
public String getValue() {

View file

@ -74,7 +74,7 @@ public class InformationStructure extends VerticalLayout {
List<RuntimePersist> runtimePersists=runtimeService.getRuntimeRepository().findAll();
actualiseKieServer(runtimePersists!=null?runtimePersists.size():0);
actualiseKieServer(runtimePersists.size());
numberKieWb=new Label(strKieWb+"0");
numberKieWb.setClassName("leftMenu-global-inforStructure-label");

View file

@ -10,6 +10,8 @@ import com.vaadin.flow.router.Route;
import com.vaadin.flow.shared.communication.PushMode;
import org.chtijbug.drools.console.vaadinComponent.Squelette.SqueletteComposant;
import java.util.Optional;
@Push(PushMode.AUTOMATIC)
@StyleSheet("css/accueil.css")
@HtmlImport("frontend://styles/shared-styles.html")
@ -22,7 +24,10 @@ public class AccueilView extends SqueletteComposant implements BeforeEnterObserv
if (getUserConnectedService().getUserConnected()==null) {
beforeEnterEvent.rerouteTo(LoginView.class);
UI.getCurrent().getUI().get().getPage().executeJavaScript("window.alert($0)", "Session expiré, veuillez-vous reconnecter");
Optional<UI> theUI = UI.getCurrent().getUI();
if (theUI.isPresent()) {
theUI.get().getPage().executeJavaScript("window.alert($0)", "Session expiré, veuillez-vous reconnecter");
}
}
}

View file

@ -172,7 +172,7 @@ public class DeploymentView extends VerticalLayout implements AddLog {
projectPersistGrid.addSelectionListener(selectionEvent -> {
if (selectionEvent.getFirstSelectedItem() != null && selectionEvent.getFirstSelectedItem().isPresent()) {
if (selectionEvent.getFirstSelectedItem().isPresent()) {
majAction(selectionEvent.getFirstSelectedItem().get());
} else {
getDeploymentAction().getAssociateKieServer().setEnabled(false);

View file

@ -4,7 +4,6 @@ import com.vaadin.flow.component.dependency.StyleSheet;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import org.chtijbug.drools.console.vaadinComponent.componentView.GridLogging;
import org.chtijbug.drools.console.vaadinComponent.componentView.GridRuntime;
import org.chtijbug.drools.console.vaadinComponent.leftMenu.Action.ActionLogging;
@StyleSheet("css/accueil.css")
@ -31,7 +30,7 @@ public class LoggingView extends VerticalLayout {
gridLogging.addSelectionListener(selectionEvent -> {
if(selectionEvent.getFirstSelectedItem()!=null&&selectionEvent.getFirstSelectedItem().isPresent()) {
if(selectionEvent.getFirstSelectedItem().isPresent()) {
actionLogging.getViewAction().setEnabled(true);
}else {
actionLogging.getViewAction().setEnabled(false);

View file

@ -2,7 +2,6 @@ package org.chtijbug.drools.console.view;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dependency.StyleSheet;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
@ -16,12 +15,14 @@ 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.componentView.AssetEdit;
import org.chtijbug.drools.console.vaadinComponent.leftMenu.Action.TemplatesAction;
import org.chtijbug.guvnor.server.jaxrs.jaxb.Asset;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectResponse;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@StyleSheet("css/accueil.css")
public class TemplateView extends VerticalLayout {
@ -102,19 +103,22 @@ public class TemplateView extends VerticalLayout {
public void edit(ComboBox<PlatformProjectResponse> spaceSelection){
Set<Asset> selectedElements = assetListGrid.getSelectedItems();
if (selectedElements.toArray().length > 0) {
String assetName = selectedElements.stream().findFirst().get().getTitle();
Optional<Asset> assetOptional = selectedElements.stream().findFirst();
if (assetOptional.isPresent()) {
String assetName = assetOptional.get().getTitle();
if (assetName != null) {
PlatformProjectResponse response = spaceSelection.getValue();
userConnectedService.addAssetToSession(assetName);
userConnectedService.addProjectToSession(response.getName());
userConnectedService.addSpaceToSession(response.getSpaceName());
DialogPerso dialog=new DialogPerso();
DialogPerso dialog = new DialogPerso();
dialog.add(new EditTemplateView(dialog,assetName));
dialog.add(new EditTemplateView(dialog, assetName));
dialog.open();
}
}
}
}
private void refreshtGrid(String value,String type){
filterDataProvider.setFilter(filterGrid(value.toUpperCase(),type));

View file

@ -1,5 +1,5 @@
server.port=${port:8200}
kie-wb.baseurl=http://localhost:8080/kie-wb/rest
kie-wb.baseurl=http://localhost:18080/kie-wb/rest
kie-wb.mainwbintern=http://localhost:8080/kie-wb
kie-wb.mainwbextern=http://localhost:8080/kie-wb
kie-wb.username=admin

View file

@ -43,7 +43,6 @@ public class CalculatedAttribute {
public void setClassName(String className) {
this.className = className;
new Boolean(booleanValue).toString();
}
public String getKey() {

View file

@ -195,8 +195,9 @@ public class GenericResource {
Method traceMethod = foundClass.getMethod("logTrace", String.class);
if (traceMethod != null) {
jsonInString = mapper.writeValueAsString(chtijbutObjectResponse.getSessionLogging());
}
traceMethod.invoke(input, jsonInString);
}
} catch (Exception e) {
}

View file

@ -43,7 +43,7 @@ public class SftpServerService {
public void initServer() throws IOException {
if (System.getProperty("org.chtijbug.server.sftpPort") != null) {
try {
port = Integer.valueOf(System.getProperty("org.chtijbug.server.sftpPort")).intValue();
port = Integer.valueOf(System.getProperty("org.chtijbug.server.sftpPort"));
} catch (NumberFormatException e) {
port = 9080;
}

View file

@ -311,7 +311,9 @@ public class PackageResource {
private org.uberfire.java.nio.file.Path getDirectoryElementPath(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream=null;
try {
adirectoryStream = ioService.newDirectoryStream(elementPath);
if (elementPath.getFileName().toString().equals(assetName)) {
return elementPath;
}
@ -319,6 +321,13 @@ public class PackageResource {
if (foundElementPath != null) {
return foundElementPath;
}
}catch (Exception e){
}finally {
if (adirectoryStream!= null){
adirectoryStream.close();
}
}
}
}
return null;
@ -390,17 +399,31 @@ public class PackageResource {
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, Asset asset) {
try {
WorkspaceProject project = getProject(organizationalUnitName, projectName);
if (project!= null) {
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPathDirectory = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPathDirectory);
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream=null;
try {
directoryStream = ioService.newDirectoryStream(nioPathDirectory);
org.uberfire.java.nio.file.Path directoryWhereCreateAsset = getDirectoryElementPath(directoryStream, asset.getTitle());
if (directoryWhereCreateAsset!= null) {
final org.uberfire.java.nio.file.Path nioPath = Paths.get(directoryWhereCreateAsset.toUri());
if (ioService.exists(nioPath)) {
throw new FileAlreadyExistsException(nioPath.toString());
}
CommentedOption commentedOption = new CommentedOption(asset.getComment());
ioService.write(nioPath, asset.getContent().getBytes(), commentedOption);
}
}catch (Exception e){
}finally {
if (directoryStream!= null){
directoryStream.close();
}
}
}
} catch (Exception e) {
throw new WebApplicationException(e);
}
@ -427,6 +450,7 @@ public class PackageResource {
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
org.uberfire.java.nio.file.Path elementToUpdate = getFileElementPath(directoryStream, assetName);
if (elementToUpdate != null) {
File fileToUpdate = elementToUpdate.toFile();
if (fileToUpdate.isFile()) {
content = content.replace("\"", "");
@ -437,6 +461,9 @@ public class PackageResource {
}
}
}else{
throw new WebApplicationException("Asset not found " + assetName);
}
} catch (RuntimeException e) {
throw new WebApplicationException(e);
}

View file

@ -63,7 +63,7 @@ public class DroolsFactObjectFactory {
}
return createFactObject;
} catch (Exception e) {
logger.error("Not possible to introspect {} for reason {}", o, e);
logger.error("Not possible to introspect {} for reason {}", o, e.getMessage(),e);
throw Throwables.propagate(e);
} finally {
logger.debug("<< createFactObject", createFactObject);

View file

@ -15,7 +15,6 @@
*/
package org.chtijbug.drools.runtime;
import org.chtijbug.drools.runtime.impl.RuleBaseCommandSingleton;
import org.chtijbug.drools.runtime.impl.RuleBaseSingleton;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.chtijbug.drools.runtime.resource.FileKnowledgeResource;
@ -34,17 +33,7 @@ public abstract class RuleBaseBuilder {
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseBuilder.class);
public static RuleBasePackage createRemoteStandardRestBasePackage(String containerId, String url,String username,String password) throws DroolsChtijbugException {
logger.debug(">> createWorkbenchRuleBasePackage()");
RuleBaseCommandSingleton newRuleBasePackage = new RuleBaseCommandSingleton(RuleBaseSingleton.DEFAULT_RULE_THRESHOLD,containerId,url,username,password);
try {
newRuleBasePackage.connectKBase();
//_____ Returning the result
return newRuleBasePackage;
} finally {
logger.debug("<< createWorkbenchRuleBasePackage", newRuleBasePackage);
}
}
public static RuleBasePackage createWorkbenchRuleBasePackage(Long ruleBaseId, HistoryListener historyListener, String groupId, String artifactId, String version, String workbenchUrl, String username, String password) throws DroolsChtijbugException {

View file

@ -1,221 +0,0 @@
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.common.reflection.ReflectionUtils;
import org.chtijbug.drools.entity.DroolsFactObject;
import org.chtijbug.drools.entity.DroolsRuleObject;
import org.chtijbug.drools.entity.history.HistoryContainer;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.kie.api.KieServices;
import org.kie.api.command.BatchExecutionCommand;
import org.kie.api.command.Command;
import org.kie.api.command.KieCommands;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.server.api.model.ServiceResponse;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.RuleServicesClient;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Created by nheron on 07/06/2016.
*/
public class RuleBaseCommandSession implements RuleBaseSession {
private List<Command<?>> commands = new ArrayList<Command<?>>();
private KieCommands commandsFactory = KieServices.Factory.get().getCommands();
private int maxNumberRuleToExecute = 2000;
private KieServicesClient kieServicesClient;
private String containerId;
public RuleBaseCommandSession(int maxNumberRuleToExecute,KieServicesClient kieServicesClient,String containerId) {
this.maxNumberRuleToExecute = maxNumberRuleToExecute;
this.kieServicesClient=kieServicesClient;
this.containerId = containerId;
}
@Override
public void insertObject(Object newObject) {
commands.add(commandsFactory.newInsert(newObject, newObject.toString()));
}
@Override
public void insertByReflection(Object newObject) throws DroolsChtijbugException {
if (newObject.getClass().getPackage().getName().startsWith("java.")) {
return;
}
//____ Then foreach getters insert item by reflection
for (Method method : newObject.getClass().getMethods()) {
//____ only manage getters
if (!ReflectionUtils.IsGetter(method)) {
continue;
}
Object getterValue;
try {
getterValue = method.invoke(newObject, (Object[]) null);
} catch (Exception e) {
throw new DroolsChtijbugException(DroolsChtijbugException.insertByReflection, "getterValue = method.invoke(newObject, (Object[]) null);", e);
}
if (getterValue == null)
continue;
//____ If returned value is not a collection, insert it in the ksession
if (!(getterValue instanceof Iterable)) {
this.insertByReflection(getterValue);
} else {
Iterable<?> iterable = (Iterable) getterValue;
for (Object item : iterable) {
this.insertByReflection(item);
}
}
}
this.insertObject(newObject);
}
@Override
public void setGlobal(String identifier, Object value) {
commands.add(commandsFactory.newSetGlobal(identifier, value));
}
@Override
public void updateObject(Object updatedObject) {
// Not Possible
}
@Override
public void retractObject(Object oldObject) {
// Not Possible
}
@Override
public void fireAllRules() throws DroolsChtijbugException {
commands.add(commandsFactory.newFireAllRules(maxNumberRuleToExecute));
}
@Override
public Object fireAllRulesAndStartProcess(Object inputObject, String processName) throws DroolsChtijbugException {
Object outputObject=null;
if (inputObject != null) {
//this.insertObject(inputObject);
this.insertByReflection(inputObject);
}
if (processName != null && processName.length() > 0) {
this.startProcess(processName);
}
this.fireAllRules();
commands.add(commandsFactory.newGetObjects(inputObject.getClass().getName()));
RuleServicesClient ruleClient = kieServicesClient.getServicesClient(RuleServicesClient.class);
BatchExecutionCommand batchCommand = commandsFactory.newBatchExecution(commands);
ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(this.containerId, batchCommand);
if (response.equals(ServiceResponse.ResponseType.SUCCESS)){
ExecutionResults actualData = response.getResult();
Collection<String> identifiers = actualData.getIdentifiers();
for (String id : identifiers){
outputObject=actualData.getValue(id);
}
}
return outputObject;
}
@Override
public Object fireAllRulesAndStartProcessWithParam(Object inputObject, String processName) throws DroolsChtijbugException {
//commands.add(commandsFactory.newFireAllRules(maxNumberRuleToExecute));
return this.fireAllRulesAndStartProcess(inputObject,processName);
}
@Override
public void startProcess(String processName) {
commands.add(commandsFactory.newStartProcess(processName));
}
@Override
public void dispose() {
}
@Override
public HistoryContainer getHistoryContainer() {
return null;
}
@Override
public String getHistoryContainerXML() {
return null;
}
@Override
public Collection<DroolsFactObject> listLastVersionObjects() {
return null;
}
@Override
public String listLastVersionObjectsXML() {
return null;
}
@Override
public Collection<DroolsRuleObject> listRules() {
return null;
}
@Override
public int getNumberRulesExecuted() {
return 0;
}
@Override
public Long getSessionId() {
return null;
}
@Override
public Long getRuleBaseID() {
return null;
}
@Override
public KieSession getKnowledgeSession() {
return null;
}
@Override
public Collection<? extends Object> getObjects(ObjectFilter objectFilter) {
return null;
}
@Override
public void completeWorkItem(long processId, Map<String, Object> vars) {
commands.add(commandsFactory.newCompleteWorkItem(processId, vars));
}
@Override
public void abortWorkItem(long processId) {
commands.add(commandsFactory.newAbortWorkItem(processId));
}
@Override
public void registerWorkItemHandler(String workItemName, WorkItemHandler workItemHandler) {
commands.add(commandsFactory.newRegisterWorkItemHandlerCommand(workItemHandler, workItemName));
}
@Override
public ProcessInstance startProcess(String processName, Map<String, Object> vars) {
commands.add(commandsFactory.newStartProcess(processName, vars));
return null;
}
public List<Command<?>> getCommands() {
return commands;
}
}

View file

@ -1,127 +0,0 @@
package org.chtijbug.drools.runtime.impl;
import org.chtijbug.drools.entity.history.EventCounter;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBasePackage;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.drools.runtime.listener.HistoryListener;
import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
/**
* Created by nheron on 07/06/2016.
*/
public class RuleBaseCommandSingleton implements RuleBasePackage {
/**
* default rule threshold
*/
public static int DEFAULT_RULE_THRESHOLD = 2000;
/**
* Class Logger
*/
private static Logger logger = LoggerFactory.getLogger(RuleBaseCommandSingleton.class);
/**
* unique ID of the RuleBase in the JVM
*/
protected EventCounter eventCounter = EventCounter.newCounter();
protected EventCounter sessionCounter = EventCounter.newCounter();
private int maxNumberRuleToExecute = DEFAULT_RULE_THRESHOLD;
/**
* Semaphore used to void concurrent access to the singleton
*/
private Semaphore lockKbase = new Semaphore(1);
/**
* History Listener
*/
private String containerId;
private String url;
private String username;
private String password;
private KieServicesClient kieServicesClient;
public RuleBaseCommandSingleton(int maxNumberRuleToExecute) {
this.maxNumberRuleToExecute = maxNumberRuleToExecute;
}
public RuleBaseCommandSingleton(int defaultRuleThreshold, String containerId,String url, String username, String password) {
this(defaultRuleThreshold);
this.containerId=containerId;
this.url=url;
this.username=username;
this.password=password;
}
@Override
public RuleBaseSession createRuleBaseSession() throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession");
try {
//____ Creating new Rule Base Session using default rule threshold
return this.createRuleBaseSession(this.maxNumberRuleToExecute);
} finally {
logger.debug("<<createRuleBaseSession");
}
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, null);
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener) throws DroolsChtijbugException {
logger.debug(">>createRuleBaseSession", maxNumberRulesToExecute);
RuleBaseSession newRuleBaseSession = null;
try {
//_____ Wrapping the knowledge Session
newRuleBaseSession = new RuleBaseCommandSession(maxNumberRulesToExecute,this.kieServicesClient,this.containerId);
//_____ Release semaphore
lockKbase.release();
return newRuleBaseSession;
} finally {
logger.debug("<<createRuleBaseSession", newRuleBaseSession);
}
}
@Override
public RuleBaseSession createRuleBaseSession(int maxNumberRulesToExecute, HistoryListener sessionHistoryListener, String sessionName) throws DroolsChtijbugException {
return this.createRuleBaseSession(maxNumberRulesToExecute, sessionHistoryListener);
}
@Override
public void loadKBase(String version) throws DroolsChtijbugException {
//
}
@Override
public HistoryListener getHistoryListener() {
return null;
}
@Override
public Long getRuleBaseID() {
return null;
}
@Override
public void dispose() {
}
public void connectKBase() {
KieServicesConfiguration config;
config = KieServicesFactory.newRestConfiguration(url, username, password);
MarshallingFormat marshallingFormat = MarshallingFormat.XSTREAM;
config.setMarshallingFormat(marshallingFormat);
this.kieServicesClient = KieServicesFactory.newKieServicesClient(config);
}
}

View file

@ -20,7 +20,7 @@ public enum FactType {
public static FactType getEnum(String factType) {
for (FactType type : FactType.values()) {
if (type.name().equals(type))
if (type.name().equals(factType))
return type;
}
return null;

View file

@ -9,13 +9,24 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
public class MainClass {
public static void main(String [] args) throws UnknownHostException {
public static void main(String[] args) throws UnknownHostException {
Settings settings = Settings.builder()
.put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings)
TransportClient client = null;
PreBuiltTransportClient preBuiltTransportClient=null;
try {
preBuiltTransportClient = new PreBuiltTransportClient(settings);
client = preBuiltTransportClient
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));
} finally {
if (client != null) {
client.close();
}
if (preBuiltTransportClient!=null){
preBuiltTransportClient.close();
}
}
// on shutdown
client.close(); }
}
}

View file

@ -210,6 +210,7 @@ public class KieServiceCommon {
Set<Class<?>> classes = kieContainerInstance.getExtraClasses();
String className = container.getClassName();
Class foundClass = this.getClassFromName(classes, className);
if (foundClass!=null) {
ClassLoader classLoader = foundClass.getClassLoader();
Class<?> theClass = classLoader.loadClass(className);
camelContext.setApplicationContextClassLoader(classLoader);
@ -220,6 +221,7 @@ public class KieServiceCommon {
DroolsRouter droolsRouter = new DroolsRouter(camelContext, theClass, projectName, kieContainerInstance, processId);
camelContext.addRoutes(droolsRouter);
routes.put(containerId, droolsRouter);
}
} finally {
if (localClassLoader != null) {
Thread.currentThread().setContextClassLoader(localClassLoader);

46
pom.xml
View file

@ -31,8 +31,38 @@
<version.org.wildfly.core>4.0.0.Final</version.org.wildfly.core>
<version.mongodb.driver>3.8.2</version.mongodb.driver>
<version.number>${git.commit.time}.${git.commit.id.abbrev}</version.number>
<!-- Sonarcloud -->
<!--sonar.projectKey>pymma_almady-planning-application</sonar.projectKey-->
<sonar.projectKey>pymma_pymma-kie-platform:${project.groupId}:${project.artifactId}</sonar.projectKey>
<sonar.organization>pymma</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.login>4c6b7da0a4367cf592a7b8bb32f6b5934ce1b7a2</sonar.login>
</properties>
<profiles>
<profile>
<id>coverage</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>dev</id>
<activation>
@ -58,6 +88,22 @@
</profiles>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.6.0.1398</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>