MIMEMessage and MIMEMessage mock test case fails with assertion error on EmailUtil - junit4

What I'm trying to achieve - Simple unit test for my EmailUtil which i have written for a Spring MVC application.
Where I'm stuck - Though i have mocked the MIMEmessage and JavaMailSender, test case failing in MimeMessageHelper.set**** methods.
Appreciate any help on this as I have tried few different ways even using PowerMock and no luck for last couple of days.
EmailUtil.Java
import java.util.List;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.Attachment;
import com.dashboard.domain.Email;
public class EmailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class
.getName());
/**
* Private constructor to make sure that no one creating instance
*/
private EmailUtil() {
}
/**
* Functionality to send the mail. This method used the mail sender
* configuration from spring-context file.
*
* #param email
* #param mailSender
* #throws MessagingException
*/
public static void sendEmail(JavaMailSender mailSender, Email email)
throws MessagingException {
LOGGER.info("Start of the method: sendEmail");
MimeMessage mimeMessage = mailSender.createMimeMessage();
// use the true flag to indicate you need a multi part message
boolean hasAttachments = email.getAttachments() != null
&& !email.getAttachments().isEmpty();
LOGGER.info(" mimeMessage - {} ",mimeMessage);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
hasAttachments);
LOGGER.info(" MimeMessageHelper - {} ",helper);
helper.setTo(email.getTo());
helper.setFrom(email.getFrom());
helper.setCc(email.getCc());
helper.setSubject(email.getSubject());
helper.setText(email.getText(), true);
List<Attachment> attachments = email.getAttachments();
if (!attachments.isEmpty()) {
for (Attachment attachment : attachments) {
String filename = attachment.getFilename();
DataSource dataSource = new ByteArrayDataSource(
attachment.getData(), attachment.getMimeType());
if (attachment.isInline()) {
helper.addInline(filename, dataSource);
} else {
helper.addAttachment(filename, dataSource);
}
}
}
mailSender.send(mimeMessage);
LOGGER.info("End of the method: sendEmail");
}
}
EmailUtilTest.Java
import static org.easymock.EasyMock.expect;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.easymock.EasyMock;
import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.dashboard.domain.ApplicationConstant;
import com.dashboard.domain.Email;
/**
* PowerMockDemo
* #author s.arumugam
*
*/
#RunWith(PowerMockRunner.class)
#PrepareForTest(EmailUtil.class)
public class EmailUtilTest {
Email email = new Email();
#Mock
JavaMailSender javaMailSender;
#Mock
MimeMessage mimeMessage;
#Mock
MimeMessageHelper mimeMessageHelper;
#Before
public void initList() {
email.setFrom(ApplicationConstant.DEFAULT_MAIL_ID.getValue());
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
}
#Test
public void sendEmailTest() throws Exception{
mimeMessageHelper.setSubject(email.getSubject());
mimeMessageHelper.setFrom(new InternetAddress(email.getFrom(), true));
mimeMessageHelper.setCc(new InternetAddress(email.getCc()[0], true));
mimeMessageHelper.setTo(new InternetAddress(email.getTo()[0], true));
mimeMessageHelper.setText(email.getText());
expect(javaMailSender.createMimeMessage()).andReturn(mimeMessage);
Address sendTo[]={new InternetAddress(email.getTo()[0])};
mimeMessage.setRecipients(RecipientType.TO,sendTo);
EasyMock.expectLastCall().times(1);
EasyMock.replay(mimeMessage);
EasyMock.replay(javaMailSender);
EmailUtil.sendEmail(javaMailSender, email);
EasyMock.verify(mimeMessage);
EasyMock.verify(javaMailSender);
}
}
Error Message:
java.lang.AssertionError: Unexpected method call MimeMessage.setRecipients(To, [to.email#userdomain.com]):
MimeMessage.setRecipients(To, [to.email#userdomain.com]): expected: 1, actual: 0 at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44) at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94) at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97) at $javax.mail.internet.MimeMessage$$EnhancerByCGLIB$$a6025b60.setRecipients(<generated>) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:581) at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:595) at com.dashboard.util.EmailUtil.sendEmail(EmailUtil.java:50)

Ohh.. I managed to fix the issue.. purely by random trial and error..! That says I need to get into deep understanding of how these mock utils works.. Working test case below with a hope someone can find a complete working example with test case;
#RunWith(EasyMockRunner.class)
public class EmailUtilTest extends EasyMockSupport{
#Mock
JavaMailSender mailSender;
#Mock
MimeMessage mimeMessage;
#Test
public void testSendEmail() throws MessagingException{
Email email = new Email();
email.setFrom("from.email#dashboard.com");
email.setSubject("Subject");
email.setTo("to.email#userdomain.com");
email.setCc("admin#dashboard.com");
email.setText("Body of the email");
EasyMock.expect(mailSender.createMimeMessage()).andReturn(mimeMessage);
mailSender.send(mimeMessage);
EasyMock.expectLastCall();
EasyMock.replay(mailSender);
EmailUtil.sendEmail(mailSender, email);
EasyMock.verify(mailSender);
}
}

The reason you are getting java.lang.AssertionError is because EasyMock uses the equals() method to compare parameters passed to methods, and you cannot use equals() to compare arrays.
Address toAddress = new InternetAddress("a#b.com");
Address[] a1 = { toAddress };
Address[] a2 = { toAddress };
if (a1.equals(a2)) { // this will be false
// so this won't happen
}
Thankfully, EasyMock provides us with several different argument matchers. In this case we should use EasyMock.aryEq(). So in order to mock out the call to setRecipients() method:
mimeMessage.setRecipients(EasyMock.eq(RecipientType.TO) , EasyMock.aryEq(sendTo));
I'm not sure how the accepted answer is working without changes to the EmailUtil class.

Related

Error setting database config property for IDatabaseConnection (HSQLDB)

I've included fully testable code below, which generates the following error when supplied with a dataset xml containing empty fields. A sample dataset.xml is also below.
java.lang.IllegalArgumentException: table.column=places.CITY value is
empty but must contain a value (to disable this feature check, set
DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS to true)
The thread here is similar but is different since it uses multiple dbTester.getConnection() whereas my code only uses one, yet has the same error. The main problem relates to this line databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE); .
It seems to be ignored entirely. I've tried putting the init code inside the #Test method but the error remains.
dataset.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<places address="123 Up Street" city="Chicago" id="001"/>
<places address="456 Down Street" city="" id="002"/>
<places address="789 Right Street" city="Boston" id="003"/>
</dataset>
Code:
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBConnectionIT {
IDatabaseTester databaseTester = null;
IDatabaseConnection iConn = null;
Connection connection = null;
#Before
public void init() throws Exception {
databaseTester = new JdbcDatabaseTester(org.hsqldb.jdbcDriver.class.getName(), "jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true", "sa", "");
iConn = databaseTester.getConnection();
DatabaseConfig databaseConfig = iConn.getConfig();
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
connection = iConn.getConnection();
createTable(connection);
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File("dataset.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onSetup();
}
#Test
public void testDBUnit() {
try {
PreparedStatement pst = connection.prepareStatement("select * from places");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createTable(Connection conn) throws Exception {
PreparedStatement pp = conn.prepareStatement(
"CREATE TABLE PLACES" +
"(address VARCHAR(255), " +
"city TEXT, " +
"id VARCHAR(255) NOT NULL primary key)");
pp.executeUpdate();
pp.close();
}
}
EDIT (based on César Rodríguez's answer):
I've now refactored out this method in the parent class:
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
}
and created a sub-class which #Overrides this method, but it's saying this sub-class is not being used. How do I address this class (DBConnectionOverride) in the parent class, to solve my problem?
class DBConnectionOverride extends DBConnectionIT {
#Override
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
}
I've stumbled upon the correct answer, at least the one which solves my problem. It related to this line all along databaseTester.onSetup() which could simply be replaced with DatabaseOperation.CLEAN_INSERT.execute(iConn, dataSet);. Feel free comment on why this seemed to have fixed the error.
You must override method setUpDatabaseConfig(DatabaseConfig config) as follows:
#Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
Hope it helps
for me it's work:
IDatabaseConnection dbConn = new DatabaseDataSourceConnection(getDataSource());
dbConn.getConfig().setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
DatabaseOperation.CLEAN_INSERT.execute(dbConn, getiDataSet(loadDBData.source()));

Eclipse 4 RCP - application does not have active window

I want to have some helper functions for manipulating UI.
I don't want to pass to them any parameters except what is necessary by my domain model (i don't want to pass EModelService, EPartService etc.)
Question: The problem is i am getting exception application does not have active window.
I found where the problem is.
It happend because i am manipulating parts via EPartService accessed from the application context IWorkbench.getApplication().getContext().get(EPartService.class).
THIS IS IMPORTANT: Currently i am getting that exception when i am trying to modify my UI AFTER i read inputs from dialog. Pleas note that the error does not happened when i am trying to modify the UI just BEFORE i
opened the dialog. Look at the code, i added some comments.
NewFromDirectoryDialog.java
package cz.vutbr.fit.xhriba01.bc.handlers;
import javax.inject.Named;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import cz.vutbr.fit.xhriba01.bc.BcModel;
import cz.vutbr.fit.xhriba01.bc.resolvers.filesystem.FileSystemResolver;
import cz.vutbr.fit.xhriba01.bc.ui.dialogs.NewFromDirectoryDialog;
import cz.vutbr.fit.xhriba01.bc.ui.UI;
public class NewFromDirectoryHandler {
#Execute
public void execute(MApplication application, EPartService partService, #Named(IServiceConstants.ACTIVE_SHELL) Shell shell) {
FileSystemResolver fsr = new FileSystemResolver("/home/jara/git/cz.vutbr.fit.xhriba01.bc/bc/src",
"/home/jara/git/cz.vutbr.fit.xhriba01.bc/bc/bin");
BcModel.setResolver(fsr);
// THIS CALL IS OK AND EVERYTHING WORKS
UI.changeExplorerView("bc.partdescriptor.filesystemview", fsr);
NewFromDirectoryDialog dialog = new NewFromDirectoryDialog(shell);
dialog.create();
if (dialog.open() == Window.OK) {
String sourceDir = dialog.getSourceDir();
String classDir = dialog.getClassDir();
FileSystemResolver fsr = new FileSystemResolver(classDir, sourceDir);
//THIS CALL LEADS TO EXCEPTION: application does not have active window
UI.changeExplorerView("bc.partdescriptor.filesystemview", fsr);
}
}
}
That EPartService from application context is based on org.eclipse.e4.ui.internal.workbench.ApplicationPartServiceImpl
and not on org.eclipse.e4.ui.internal.workbench.PartServiceImpl
as EPartService instance you get when injected to #PostConstruct annotated method on Part's view.
org.eclipse.e4.ui.internal.workbench.ApplicationPartServiceImpl (not entire source code)
You can see that the error probably happened because at the time ApplicationPartServiceImpl.createPart is called in my UI.changeExplorerView, the Eclipse runtime does not know what window
is currently active.
package org.eclipse.e4.ui.internal.workbench;
import java.util.Collection;
import javax.inject.Inject;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.model.application.ui.advanced.MPlaceholder;
import org.eclipse.e4.ui.model.application.ui.basic.MInputPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.e4.ui.workbench.modeling.IPartListener;
public class ApplicationPartServiceImpl implements EPartService {
private MApplication application;
#Inject
ApplicationPartServiceImpl(MApplication application) {
this.application = application;
}
private EPartService getActiveWindowService() {
IEclipseContext activeWindowContext = application.getContext().getActiveChild();
if (activeWindowContext == null) {
throw new IllegalStateException("Application does not have an active window"); //$NON-NLS-1$
}
EPartService activeWindowPartService = activeWindowContext.get(EPartService.class);
if (activeWindowPartService == null) {
throw new IllegalStateException("Active window context is invalid"); //$NON-NLS-1$
}
if (activeWindowPartService == this) {
throw new IllegalStateException("Application does not have an active window"); //$NON-NLS-1$
}
return activeWindowPartService;
}
#Override
public MPart createPart(String id) {
return getActiveWindowService().createPart(id);
}
}
LifeCycleManager.java (how i initialize the UI helper class)
You can see i am injecting IWorkbench to my UI class.
IWorkbench allows me to access MApplication, so that is all i should
need to modify app UI.
package cz.vutbr.fit.xhriba01.bc;
import javax.inject.Inject;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.UIEvents;
import cz.vutbr.fit.xhriba01.bc.ui.UI;
public class LifeCycleManager {
#Inject
#Optional
private void appCompleted(#UIEventTopic(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE) Object event, IWorkbench workbench) {
ContextInjectionFactory.inject(UI.getDefault(), workbench.getApplication().getContext());
}
}
UI.java
package cz.vutbr.fit.xhriba01.bc.ui;
import javax.inject.Inject;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPartStack;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.e4.ui.workbench.modeling.EPartService.PartState;
import org.eclipse.jface.text.IDocument;
import cz.vutbr.fit.xhriba01.bc.BcModel;
import cz.vutbr.fit.xhriba01.bc.resolvers.ISourceAndClassResolver;
public class UI {
public static final String PART_EXPLORER_ID = "bc.part.inspector";
public static final String PART_EXPLORER_CONTAINER_ID = "bc.partstack.explorer_stack";
public static final String PART_JAVA_SOURCE_VIEWER_ID = "bc.part.javasourceview";
private static UI fInstance = new UI();
#Inject
private IWorkbench fWorkbench;
private UI() {
}
public static void changeExplorerView(String partDescriptorId, ISourceAndClassResolver resolver) {
EModelService modelService = fInstance.fWorkbench.getApplication().getContext().get(EModelService.class);
EPartService partService = fInstance.fWorkbench.getApplication().getContext().get(EPartService.class);
MApplication application = fInstance.fWorkbench.getApplication();
MPart part = partService.createPart(partDescriptorId);
MPart oldPart = partService.findPart(UI.PART_EXPLORER_ID);
MPartStack partStack = (MPartStack) modelService.find(UI.PART_EXPLORER_CONTAINER_ID, application);
partStack.setVisible(true);
if (oldPart != null) {
partService.hidePart(oldPart);
}
part.setElementId(UI.PART_EXPLORER_ID);
partStack.getChildren().add(part);
BcModel.setResolver(resolver);
partService.showPart(part, PartState.VISIBLE);
}
public static UI getDefault() {
return fInstance;
}
public static void setJavaSourceLabel(String label, EPartService partService) {
MPart part = partService.findPart(UI.PART_JAVA_SOURCE_VIEWER_ID);
if (part != null) {
part.setLabel(label);
}
}
public static void setJavaSourceText(String source) {
IDocument document = BcModel.getJavaDocument();
if (document != null) {
document.set(source);
}
}
}
I think the problem is when i open the dialog, the activeChild changes somehow to that new opened dialog and when i close it and try immediately change my UI, it does not work because the activeChild is still not properly setup back. Otherweise i don't know why it works fine just before i opened the dialog and doesn't work just after the dialog is closed.
Does anyone know if it is bug?

Reading xls file in gwt

I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.

Control Netbeans from Commandline: attach Debugger from Shell-script

I'm using a daemon-script which is monitoring a remote server. When the remote server is up, i want that Netbeans automatically connects it's Debugger to the remote Server.
Is it possible to control this behavior from commandline?
To type Something like
netbeans --attach-debugger 192.168.178.34:9009
inside a terminal to do that? Or what other ways do i have to get access to Netbeans-internal stuff? (until now, i was just a "user" of Netbeans so i don't know the internals and how to access them very well)
Or will i have to write a Netbeans Plugin to do that? If yes, can you give me a good starting point to add that functionality?
Ok since there is no option to attach the Debugger from commandline, i wrote a Netbeans Plugin with the help of this blog entry and this thread from the NB-mailinglist. Now i'm able to call my plugin actions from the Commandline.
So build a simple NetBeans Module, which contains 2 important classes.
This is the class which gets the commandline parameters and forwards them to my Action:
import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.Action;
import org.netbeans.api.sendopts.CommandException;
import org.netbeans.spi.sendopts.Env;
import org.netbeans.spi.sendopts.OptionProcessor;
import org.netbeans.spi.sendopts.Option;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.WindowManager;
#ServiceProvider(service = OptionProcessor.class)
public class TriggerActionCommandLine extends OptionProcessor {
//Here we specify "runAction" as the new key in the command,
//but it could be any other string you like, of course:
private static Option action = Option.requiredArgument(Option.NO_SHORT_NAME, "debug");
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
#Override
public Set<org.netbeans.spi.sendopts.Option> getOptions() {
return Collections.singleton(action);
}
#Override
protected void process(Env env, Map<Option, String[]> values) throws CommandException {
final String[] args = (String[]) values.get(action);
if (args.length > 0) {
//Set the value to be the first argument from the command line,
//i.e., this is "GreetAction", for example:
final String ip = args[0];
//Wait until the UI is constructed,
//otherwise you will fail to retrieve your action:
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
#Override
public void run() {
//Then find & perform the action:
Action a = findAction(AttachDebugger.ACTION_NAME);
// forward IP address to Action
ActionEvent e = new ActionEvent(this, 1, ip);
a.actionPerformed(e);
}
});
}
}
public Action findAction(String actionName) {
FileObject myActionsFolder = FileUtil.getConfigFile("Actions/PSFActions");
FileObject[] myActionsFolderKids = myActionsFolder.getChildren();
for (FileObject fileObject : myActionsFolderKids) {
logger.info(fileObject.getName());
//Probably want to make this more robust,
//but the point is that here we find a particular Action:
if (fileObject.getName().contains(actionName)) {
try {
DataObject dob = DataObject.find(fileObject);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
}
return null;
}
}
This is my Plugin Action which attaches the Debugger to the given remote address:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.debugger.jpda.DebuggerStartException;
import org.netbeans.api.debugger.jpda.JPDADebugger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.python.util.PythonInterpreter;
#ActionID(category = "PSFActions", id = "de.mackaz.AttachDebugger")
#ActionRegistration(displayName = "#CTL_AttachDebuggerAction")
#ActionReferences({
#ActionReference(path = "Menu/Tools", position = 1800, separatorBefore = 1750, separatorAfter = 1850)
})
public final class AttachDebugger implements ActionListener {
private static final Logger logger = Logger.getLogger(AttachDebugger.class.getName());
public static final String ACTION_NAME="AttachDebugger";
#Override
public void actionPerformed(ActionEvent e) {
String ip;
if (!e.getActionCommand().contains("Attach Debugger")) {
ip = e.getActionCommand();
} else {
ip = lookupIP();
}
try {
logger.log(Level.INFO, "Attaching Debugger to IP {0}", ip);
JPDADebugger.attach(
ip,
9009,
new Object[]{null});
} catch (DebuggerStartException ex) {
int msgType = NotifyDescriptor.ERROR_MESSAGE;
String msg = "Failed to connect debugger to remote IP " + ip;
NotifyDescriptor errorDescriptor = new NotifyDescriptor.Message(msg, msgType);
DialogDisplayer.getDefault().notify(errorDescriptor);
}
}
}
Now i can attach the Netbeans debugger to a specific address by calling netbeans/bin/netbeans --debug 192.168.178.79

Unable to find the org.drools.builder.KnowledgeType drrols class

While am trying to execute the Helloword process example from the section 2.3 in
https://hudson.jboss.org/hudson/job/drools/lastSuccessfulBuild/artifact/trunk/target/docs/drools-flow/html_single/index.html#d4e24 site am unable to find the below mentioned class.
org.drools.builder.KnowledgeType
Could anyone please tell from which package can i get this class?
Thanks!
That part of the documentation seems a little outdated. You should use ResourceType. I've updated the docs with the following code fragment instead (should also appear on the link you're using once the build succeeds):
package com.sample;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
/**
* This is a sample file to launch a process.
*/
public class ProcessTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
// start a new process instance
ksession.startProcess("com.sample.ruleflow");
logger.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
private static KnowledgeBase readKnowledgeBase() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("ruleflow.rf"), ResourceType.DRF);
return kbuilder.newKnowledgeBase();
}
}