Drools marshall/unmarshall not save global - marshalling

I have a Test to unmarshall kiesession, with data in Global, but the unmarshall not return global.
The code is that :
Java Test
KieServices kieServices = KieServices.Factory.get();
KieContainer kContainer = kieServices.getKieClasspathContainer();
KieBase kBase1 = kContainer.getKieBase("KBase1");
KieSession kieSession1 = kContainer.newKieSession("KSession2_1");
Map<String, Object> map = new ConcurrentHashMap<String, Object>();
int tam = 10000;
for (int i = 0; i < tam; i++) {
map.put("map" + i, i);
}
kieSession1.setGlobal("map", map);
for (int i = 0; i < tam; i++) {
Client client = new Client();
client.setName("test");
client.setEdad(10);
kieSession1.insert(client);
}
kieSession1.fireAllRules();
Marshaller marshaller = MarshallerFactory.newMarshaller(kBase1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
marshaller.marshall(baos, kieSession1);
} catch (IOException e) {
fail("error");
}
byte[] data = baos.toByteArray();
try {
baos.close();
} catch (IOException e) {
fail("error");
}
//
kieSession1.dispose();
InputStream is = new ByteArrayInputStream(data);
try {
kieSession1 = marshaller.unmarshall(is);
} catch (ClassNotFoundException e) {
fail("error");
} catch (IOException e) {
fail("error : " + e);
} finally {
try {
is.close();
} catch (IOException e) {
}
}
assertEquals(tam, kieSession1.getFactCount());
assertNotNull("No existe Global !!", kieSession1.getGlobal("map"));
Drools Rule
global java.util.Map map
rule "test"
when
then
System.out.println("test !!" + map.size());
end
The version are :
org.drools:drools-compiler:jar:6.1.0.Final
org.drools:drools-core:jar:6.1.0.Final
org.kie:kie-api:jar:6.1.0.Final.1.2
org.kie:kie-internal:jar:6.1.0.Final

Globals are not inserted into the Working Memory, consequently they are not saved with the KieSession's state.
Globals have to be inserted every time you restore KieSession's state.

Just ran into this awesome behaviour, so here's a solution for loading:
You can initialise your globals BEFORE loading the session by registering a resolver with the environment:
Environment environment = kieServices.getEnvironment();
MapGlobalResolver resolver = new MapGlobalResolver(droolsProvider.globals());
environment.set(EnvironmentName.GLOBALS, resolver);
The MapGlobalResolver is the default resolver anyway. By using this approach, the resolver will be pre-initialised with the correct globals. Personally, I am thinking of writing an InjectionResolver so that Guice will inject globals on demand, but that might not be for everyone's need.
Then loading is as simple as passing the correct environment in:
KieSession loadedKieSession = kieServices.getKieService().getStoreServices().loadKieSession(session.getId(), kieBase, ksConf, environment);
Where the objects are the corresponding config object that are needed to set up the Environment.

Related

I keep getting the error java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.io.FileOutputStream

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Vector<Vector> tableData = model.getDataVector();
//Saving of object in a file
try {
FileOutputStream file = new FileOutputStream("StudentFile.bin");
ObjectOutputStream output = new ObjectOutputStream(file);
// Method for serialization of object
output.writeObject(file);
output.close();
file.close();
} catch (Exception ex) {
ex.printStackTrace();
}
new ComputerScience_IA_UI().setVisible(true);
this.dispose();//to close the current jframe
}
this is my code
I wanted it to save data in a file
But every time it always gave me the same error java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.io.FileOutputStream
this is the right code
try {
FileInputStream file = new FileInputStream("StudentFile.bin");
ObjectInputStream input = new ObjectInputStream(file);
Vector<Vector> tableData = (Vector<Vector>)input.readObject();
input.close();
file.close();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
for (int i = 0; i < tableData.size(); i++) {
Vector row = tableData.get(i);
model.addRow(new Object [] {row.get(0), row.get(1), row.get(2), row.get(3), row.get(4), row.get(5)});
}
} catch (Exception ex) {
ex.printStackTrace();
}

org.apache.fop.fo.flow.ExternalGraphic catches and logs ImageException I want to handle myself

I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.

Dropbox Java Api Upload File

How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

Managing trace files on Sql Server 2005

I need to manage the trace files for a database on Sql Server 2005 Express Edition. The C2 audit logging is turned on for the database, and the files that it's creating are eating up a lot of space.
Can this be done from within Sql Server, or do I need to write a service to monitor these files and take the appropriate actions?
I found the [master].[sys].[trace] table with the trace file properties. Does anyone know the meaning of the fields in this table?
Here's what I came up with that is working pretty good from a console application:
static void Main(string[] args)
{
try
{
Console.WriteLine("CcmLogManager v1.0");
Console.WriteLine();
// How long should we keep the files around (in months) 12 is the PCI requirement?
var months = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RemoveMonths") ?? "12");
var currentFilePath = GetCurrentAuditFilePath();
Console.WriteLine("Path: {0}", new FileInfo(currentFilePath).DirectoryName);
Console.WriteLine();
Console.WriteLine("------- Removing Files --------------------");
var fileInfo = new FileInfo(currentFilePath);
if (fileInfo.DirectoryName != null)
{
var purgeBefore = DateTime.Now.AddMonths(-months);
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc.zip");
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
if (PurgeLogFile(fi, purgeBefore))
{
Console.WriteLine("Deleting: {0}", fi.Name);
try
{
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Removed ---------------------");
Console.WriteLine();
Console.WriteLine("------- Compressing Files -----------------");
if (fileInfo.DirectoryName != null)
{
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc");
foreach (var file in files)
{
// Don't attempt to compress the current log file.
if (file.ToLower() == fileInfo.FullName.ToLower())
continue;
var zipFileName = file + ".zip";
var fi = new FileInfo(file);
var zipEntryName = fi.Name;
Console.WriteLine("Zipping: \"{0}\"", fi.Name);
try
{
using (var fileStream = File.Create(zipFileName))
{
var zipFile = new ZipOutputStream(fileStream);
zipFile.SetLevel(9);
var zipEntry = new ZipEntry(zipEntryName);
zipFile.PutNextEntry(zipEntry);
using (var ostream = File.OpenRead(file))
{
int bytesRead;
var obuffer = new byte[2048];
while ((bytesRead = ostream.Read(obuffer, 0, 2048)) > 0)
zipFile.Write(obuffer, 0, bytesRead);
}
zipFile.Finish();
zipFile.Close();
}
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Compressed ------------------");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
public static bool PurgeLogFile(FileInfo fi, DateTime purgeBefore)
{
try
{
var filename = fi.Name;
if (filename.StartsWith("audittrace"))
{
filename = filename.Substring(10, 8);
var year = Convert.ToInt32(filename.Substring(0, 4));
var month = Convert.ToInt32(filename.Substring(4, 2));
var day = Convert.ToInt32(filename.Substring(6, 2));
var logDate = new DateTime(year, month, day);
return logDate.Date <= purgeBefore.Date;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
public static string GetCurrentAuditFilePath()
{
const string connStr = "Data Source=.\\SERVER;Persist Security Info=True;User ID=;Password=";
var dt = new DataTable();
var adapter =
new SqlDataAdapter(
"SELECT path FROM [master].[sys].[traces] WHERE path like '%audittrace%'", connStr);
try
{
adapter.Fill(dt);
if (dt.Rows.Count >= 1)
{
if (dt.Rows.Count > 1)
Console.WriteLine("More than one audit trace file defined! Count: {0}", dt.Rows.Count);
var path = dt.Rows[0]["path"].ToString();
return path.StartsWith("\\\\?\\") ? path.Substring(4) : path;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
throw new Exception("No Audit Trace File in sys.traces!");
}
You can also set up SQL Trace to log to a SQL table. Then you can set up a SQL Agent task to auto-truncate records.
sys.traces has a record for every trace started on the server. Since SQL Express does not have Agent and cannot set up jobs, you'll need an external process or service to monitor these. You'll have to roll your own everything (monitoring, archiving, trace retention policy etc). If you have C2 audit in place, I assume you have policies in place that determine the duration audit has to be retained.