Drools 7.57.0. mateSpace oom - drools

I ues Drools 7.57.0 version ,Each time a rule is added, mateSpace usage increases and is not recycled
Map<String, KieBaseModel> kieBaseModels = kieModuleModel.getKieBaseModels();
KieBaseModel kieBaseModel = kieBaseModels.get(kieBaseName);
if (kieBaseModel == null) {
kieBaseModel = kieModuleModel.newKieBaseModel(kieBaseName);
KieSessionModel kieSessionModel = kieBaseModel.newKieSessionModel(kieBaseName);}
List<String> packages = kieBaseModel.getPackages();
if (CollUtil.isEmpty(packages) || !packages.contains(pkg)) {
kieBaseModel.addPackage(pkg);
}
kieFileSystem.write(filePath, engineRule.getScript());
kieFileSystem.writeKModuleXML(kieModuleModel.toXML());
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
kieBuilder.buildAll();
kieContainer.updateToVersion(kieRepository.getDefaultReleaseId());

try to use KieRepository.removeKieModule(ReleaseId) to remove old kieModules.
References:
https://bugzilla.redhat.com/show_bug.cgi?id=1044007
https://issues.redhat.com/browse/DROOLS-381
https://github.com/kiegroup/drools/commit/88672e348ed9d32c3f74683e91f727c80754350f

Related

OPC UA.NET custom Node Manager creating

I'm trying to use UA-.NETStandardLibrary by OPC Foundation to create my own OPC UA Server that will maintain some variables.
I've created a server class inherited from StandardServer and node manager inherited from CustomNodeManager2.
There were some node managers in their examples, I removed them and add my own one. The server starts normally and doesn't contain any nodes except from standard ones, as planned. So, my problem is how to create my own variable node from code (not from xml, as in examples) and be able update its value on demand.
For example, I want to add a folder with couple of nodes inside.
Does anyone have a code snippet which demonstrates how to do it? I don't want anybody write it for me, I will appreciate only if you just tell me about a right way to make it.
Thanks a lot.
I am pretty sure the snippets you are looking for are included. Here is my testing code and I am 100% positive, I didn't write the second piece of code. Anyway, if this helps you...
{
var ticker_seq = createVariable(myFolder, "MyFolder/Ticker", "Ticker", BuiltInType.UInt64, ValueRanks.Scalar);
variables.Add(ticker_seq);
subscriptions.Add(clock.Ticker.Subscribe(val =>
{
lock (Lock)
{
ticker_seq.Value = val;
ticker_seq.Timestamp = DateTime.UtcNow;
ticker_seq.ClearChangeMasks(SystemContext, false);
}
}));
}
and creation
private BaseDataVariableState createVariable(NodeState parent, string path, string name, NodeId dataType, int valueRank)
{
BaseDataVariableState variable = new BaseDataVariableState(parent);
variable.SymbolicName = name;
variable.ReferenceTypeId = ReferenceTypes.Organizes;
variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
variable.NodeId = new NodeId(path, NamespaceIndex);
variable.BrowseName = new QualifiedName(path, NamespaceIndex);
variable.DisplayName = new LocalizedText("en", name);
variable.WriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.UserWriteMask = AttributeWriteMask.DisplayName | AttributeWriteMask.Description;
variable.DataType = dataType;
variable.ValueRank = valueRank;
variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
variable.Historizing = false;
variable.Value = 0;
variable.StatusCode = StatusCodes.Good;
variable.Timestamp = DateTime.UtcNow;
if (parent != null)
{
parent.AddChild(variable);
}
return variable;
}
creating the folder:
private FolderState CreateFolder(NodeState parent, string path, string name)
{
FolderState folder = new FolderState(parent);
folder.SymbolicName = name;
folder.ReferenceTypeId = ReferenceTypes.Organizes;
folder.TypeDefinitionId = ObjectTypeIds.FolderType;
folder.NodeId = new NodeId(path, NamespaceIndex);
folder.BrowseName = new QualifiedName(path, NamespaceIndex);
folder.DisplayName = new LocalizedText("en", name);
folder.WriteMask = AttributeWriteMask.None;
folder.UserWriteMask = AttributeWriteMask.None;
folder.EventNotifier = EventNotifiers.None;
if (parent != null)
{
parent.AddChild(folder);
}
return folder;
}

Entity Framework 6 and Async() Performance

i have a question about Entity Framework 6 and ToListAsync()/ToList().
if i have a little amount of data (around 1000 rows) i have noticed that ToListAsync() is faster than ToList().
But if i have a huge amount of data (around 600.000 rows) ToList() is faster than ToListAsync().
Here you can fine the code, someone can explain me why?.
//SharedAnagra contains around 1000 rows
static List<SharedAnagra> GetSharedAnagraList()
{
using (Intranet2k3Entities intranet2K3Entities = new Intranet2k3Entities())
{
List<SharedAnagra> listaSharedAnagras = (from a in intranet2K3Entities.sharedAnagra
select new SharedAnagra
{
AnagraActive = a.AnagraActive,
AnagraId = a.AnagraID,
AnagraName = a.AnagraName,
OfficeId = a.OfficeID
}).ToList();
return listaSharedAnagras;
}
}
static async Task<List<SharedAnagra>> GetSharedAnagraListAsync()
{
using (Intranet2k3Entities intranet2K3Entities = new Intranet2k3Entities())
{
List<SharedAnagra> listaSharedAnagras = await (from a in intranet2K3Entities.sharedAnagra
select new SharedAnagra
{
AnagraActive = a.AnagraActive,
AnagraId = a.AnagraID,
AnagraName = a.AnagraName,
OfficeId = a.OfficeID
}).ToListAsync();
return listaSharedAnagras;
}
}
//sharedAnagraNDGClienti contains 950000 rows
static List<SharedAnagraNdgClienti> ListaSharedNdgClienti()
{
using (Intranet2k3Entities intranet2K3Entities = new Intranet2k3Entities())
{
List<SharedAnagraNdgClienti> lista = (from a in intranet2K3Entities.sharedAnagraNDGClienti
select new SharedAnagraNdgClienti
{
Cm = a.CM,
CodFisc = a.CodFisc,
Cognome = a.Cognome,
Descrizione = a.Descrizione,
FilialePrevalente = a.Filiale_Prevalente,
Ndg = a.NDG,
Nome = a.Nome,
Telefono = a.Telefono,
Tipologia = a.Tipologia,
Trae = a.TRAE,
Tsae = a.TSAE
}).AsNoTracking().ToList();
return lista;
}
}
static async Task<List<SharedAnagraNdgClienti>> GetIssueTypeByIdAsync()
{
List<SharedAnagraNdgClienti> listaSharedAnagraNdgClienti;
using (Intranet2k3Entities intranet2K3Entities = new Intranet2k3Entities())
{
listaSharedAnagraNdgClienti = await (from a in intranet2K3Entities.sharedAnagraNDGClienti
select new SharedAnagraNdgClienti
{
Cm = a.CM,
CodFisc = a.CodFisc,
Cognome = a.Cognome,
Descrizione = a.Descrizione,
FilialePrevalente = a.Filiale_Prevalente,
Ndg = a.NDG,
Nome = a.Nome,
Telefono = a.Telefono,
Tipologia = a.Tipologia,
Trae = a.TRAE,
Tsae = a.TSAE
}).AsNoTracking().ToListAsync();
}
return listaSharedAnagraNdgClienti;
}
I think this is not a problem of your query.This is an issue of EF 6+ framework itself.I personally didn't do any R&D about Asyn vc Sync.But I have found out some useful posts about that.Hope that will help to you.
When to really use async ?
In most applications using async will have no noticeable benefits and
even could be detrimental. Use tests, profiling and common sense to
measure the impact of async in your particular scenario before
committing to it.
Here is that article : Async Query & Save (EF6 onwards)
And here is the Great research done by one of the Stackoveflow user.You can read that too.Great one.
Entity Framework async operation takes ten times as long to complete

epplus dispose don't work

I open with epplus an excel file.
After reading some data, I would like to close the package:
pck.Stream.Close()
pck.Dispose()
Unfortunatelly the excel file is still blocked. I need to close the whole application to get the excel file unlocked.
I have googled, but found nothing useful except the above.
How are you opening the file? The following creates, saves, reopens, prints, and finally deletes all withing the same thread without issue. I can even set a breakpoint anywhere and delete the file. Reading the file this way should not lock the file since it is pulled into memory:
[TestMethod]
public void OpenReopenPrintDeleteTest()
{
//Create some data
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
workbook.Worksheets.Add("newsheet");
package.Save();
}
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.First();
//The data
worksheet.Cells["A1"].Value = "Col1";
worksheet.Cells["A2"].Value = "sdf";
worksheet.Cells["A3"].Value = "ghgh";
worksheet.Cells["B1"].Value = "Col2";
worksheet.Cells["B2"].Value = "Group B";
worksheet.Cells["B3"].Value = "Group A";
worksheet.Cells["C1"].Value = "Col3";
worksheet.Cells["C2"].Value = 634.5;
worksheet.Cells["C3"].Value = 274.5;
worksheet.Cells["D1"].Value = "Col4";
worksheet.Cells["D2"].Value = 996440;
worksheet.Cells["D3"].Value = 185780;
package.Save();
}
//Reopen the file
using (var package = new ExcelPackage(existingFile))
{
var workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
var currentWorksheet = workBook.Worksheets.First();
var lastrow = currentWorksheet.Dimension.End.Row;
var lastcol = currentWorksheet.Dimension.End.Column;
for (var i = 1; i <= lastrow; i++)
for (var j = 1; j <= lastcol; j++)
Console.WriteLine(currentWorksheet.Cells[i, j].Value);
}
}
}
//Delete the file
existingFile.Delete();
}
I was having the same problem... But I found the solution:
During the "SaveAs" method, I was creating a FileStream that was not being disposed.
Before:
ExcelPackage excel_package = new ExcelPackage(new MemoryStream());
//...
//Do something here
//...
excel_package.SaveAs(new FileStream("filename.xlsx", FileMode.Create));
excel_package.Dispose();
After:
ExcelPackage excel_package = new ExcelPackage(new MemoryStream());
//...
//Do something here
//...
var file_stream = new FileStream("filename.xlsx", FileMode.Create);
excel_package.SaveAs(file_stream);
file_stream.Dispose();
excel_package.Dispose();
Note that the Memory Stream opened during the ExcelPackage declaration was not explicitly disposed, because the last command "excel_package.Dispose()" already does this internally.
Hope it help.
c# excel epplus

How to get a Fact creating BRL in Guvnor and querying Drools Server

I'm stuck with BRL rules in Guvnor.. I'm trying to execute rules from my application using Drools Server (this solution because in production I can use more server and maybe improve performance.. Not sure about this as it's the first time that in my company we are using Drools)..
So basically the rule is .. Given an object Route setting the property "selectedOutboundJourney" that I uploaded in guvnor in a jar, I'd like to get another object with the property "selectedReturnJourney" set.. (but Is it possible to get the same object??)
Actually I get a Route object where the selectedReturnJourney is null.
I'm not sure if using BRL is a good solution given the troubles that I'm having.. It seems easy to use for non technical people that may want to change the rules or creating new ones.
Anyway..
This is the BRL that I created in Guvnor:
rule "Selected Return for Dover - Calais"
dialect "mvel"
when
Route( selectedOutboundJourney == "DOCA" )
then
Route fact0 = new Route();
fact0.setSelectedReturnJourney( "CADO" );
insertLogical( fact0 );
end
This is the code I'm using:
final List<Command> commands = new ArrayList<Command>();
final Command insertObjectCommand = CommandFactory.newInsert(input, RESULT, true, "default");
final Command getObjectCommand = CommandFactory.newGetObjects();
final Command fireAllRulesCommand = CommandFactory.newFireAllRules();
commands.add(insertObjectCommand);
commands.add(getObjectCommand);
commands.add(fireAllRulesCommand);
final ExecutionResults executionResults = droolsHttpClient.callDroolsServer(commands);
return executionResults.getValue(RESULT);
The class DroolsHttpClient is:
public ExecutionResults callDroolsServer(final List<Command> commands) throws DroolsException
{
PostMethod postMethod = null;
try
{
final HttpClient httpClient = new HttpClient();
final String droolsServerHost = Config.getString(PoferriesrulesengineConstants.DROOLS_SERVER_HOST, "");
final int droolsServerPort = Config.getInt(PoferriesrulesengineConstants.DROOLS_SERVER_PORT, 0);
httpClient.getHostConfiguration().setHost(droolsServerHost, droolsServerPort);
final String droolsServerUrl = Config.getString(PoferriesrulesengineConstants.DROOLS_SERVER_URL, "");
postMethod = new PostMethod(droolsServerUrl);
final BatchExecutionCommand command = CommandFactory.newBatchExecution(commands, PoferriesrulesengineConstants.DROOLS_SESSION);
final XStream xStreamMarshaller = BatchExecutionHelper.newXStreamMarshaller();
final String xmlCommand = xStreamMarshaller.toXML(command);
final StringRequestEntity request = new StringRequestEntity(xmlCommand, MediaType.TEXT_PLAIN_VALUE, CharEncoding.UTF_8);
postMethod.setRequestEntity(request);
httpClient.executeMethod(postMethod);
if (postMethod.getStatusCode() != 200)
{
throw new RuntimeException("Drools Communication Error, code: " + postMethod.getStatusCode());
}
final String response = postMethod.getResponseBodyAsString();
final ExecutionResults executionResults = (ExecutionResults) xStreamMarshaller.fromXML(response);
return executionResults;
}
catch (final Exception e)
{
throw new DroolsException(e.getMessage());
}
finally
{
postMethod.releaseConnection();
}
}
If I use a DRL like below it words perfectly without using the getObjectCommand:
rule "Selected Return Routes for Dover Calais"
when
r : Route(selectedOutboundJourney == "DOCA")
then
r.setSelectedReturnJourney("CADO")
end
Can anyone help me out, please?
Assuming you only have one fact in your Knowledge Session at the start, after the execution of the following rule
rule "Selected Return for Dover - Calais"
dialect "mvel"
when
Route( selectedOutboundJourney == "DOCA" )
then
Route fact0 = new Route()
fact0.setSelectedReturnJourney( "CADO" )
insert( fact0 )
end
you will have two Route facts in your session, since you just have inserted the second one.
Route: selectedOutboundJourney = "DOCA", selectedReturnJourney=null
Route: selectedOutboundJourney = null, selectedReturnJourney="DACO"
If you want to modify the original fact use the following rule:
rule "Selected Return Routes for Dover Calais"
when
$r : Route(selectedOutboundJourney == "DOCA")
then
modify ($r) {
selectedReturnJourney = "CADO"
}
end

How to create an ArcMap Layer from a ArcGIS Map Service

I would like to add an ILayer created from an ArcGIS Server Map service to an IMap with ArcObjects, but don't see how to do it.
I am getting an IMapServer3 with the following code, where mapName = the map service:
serverContext = som.CreateServerContext(mapName, "MapServer");
IServerObject serverObject = serverContext.ServerObject;
IMapServer3 mapServer = (IMapServer3)serverObject;
It looks like I can get an ILayer from an IMapServerGroupLayer, but it looks like the IMapServerGroupLayer is looking for a different connection type than I am using.
If you have an example of getting an ILayer from a Map Service, your assistance is appreciated.
This is what worked...
private static void GetLayerFromMapServerLayer()
{
IAGSServerConnectionName servConnName = new AGSServerConnectionNameClass();
IPropertySet props = new PropertySetClass();
props.SetProperty("machine", "server");
servConnName.ConnectionProperties = props;
IAGSServerConnectionFactory pAGSServerConnectionFactory = new AGSServerConnectionFactoryClass();
IAGSServerConnection pAGSConnection = pAGSServerConnectionFactory.Open(props, 0);
IAGSEnumServerObjectName pEnumSOName = pAGSConnection.ServerObjectNames;
IAGSServerObjectName pSOName = pEnumSOName.Next();
while (pSOName != null)
{
if (pSOName.Name == "Base_Map")
break;
pSOName = pEnumSOName.Next();
}
IName pName = (IName)pSOName;
IMapServer mapServer = (IMapServer)pName.Open();
IMapServerLayer msLyr = new MapServerLayerClass();
msLyr.ServerConnect(pSOName, mapServer.DefaultMapName);
IMapServerGroupLayer group = (IMapServerGroupLayer)msLyr;
ILayer msLayer = (ILayer)msLyr;
//return msLayer;
MapDocument mapDoc = new MapDocumentClass();
mapDoc.Open(#"F:\~mkoneya~2011_82_13_58_30.mxd");
IMap myMap = mapDoc.get_Map(0);
myMap.AddLayer(msLayer);
mapDoc.Save();
}