I am trying to create a Waveform Control Panel to change the properties of its components. I attempted to apply the example in the Redhawk documentation for a Component Control Panel, but for some reason I get a java.lang.NullPointerException when running the plugin. The error occurs when I attempt to bind the text field to a component property, the exact line where the error occurred is in the comments of the code (at the very bottom).
public class TestControlPanel extends AbstractScaContentEditor<ScaWaveform> {
private ScaWaveform waveform;
private ScaComponent myComponent;
private Text propertyValueField;
private EMFDataBindingContext context;
/**
* {#inheritDoc}
*/
#Override
public void createPartControl(final Composite main) {
main.setLayout(new GridLayout(2, false));
Group controlGroup = new Group(main, SWT.SHADOW_ETCHED_OUT);
controlGroup.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).create());
controlGroup.setText("Controls");
createControlGroup(controlGroup);
}
private void createControlGroup(Composite parent) {
parent.setLayout(new GridLayout(2, false));
EObject input = getInput();
if (input instanceof ScaWaveform) {
// make local copy of waveform
waveform = (ScaWaveform) input;
try {
waveform.refresh(null, RefreshDepth.FULL);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
label = new Label(parent,SWT.None);
label.setText("Property Value:");
propertyValueField = new Text(parent, SWT.BORDER | SWT.FILL);
myComponent = waveform.getScaComponent("myComponent_1");
if(myComponent != null)
{
IObservableValue observable = SCAObservables.observeSimpleProperty(myComponent, "propertyId");
IObservableValue targetObservable = WidgetProperties.text(SWT.Modify).observeDelayed(5000,propertyValueField);
if(observable != null && targetObservable != null)
{
// ***** THE BELOW LINE CAUSES A java.lang.NullPointerException ERROR *****
context.bindValue(targetObservable, observable);
// ***** THE ABOVE LINE CAUSES A java.lang.NullPointerException ERROR *****
}
}
}
}
My original guess for the reason for this error was that one of the IObservableValue variables (e.g. targetObservable or observable) was null, which is why I check to make sure the values are not null before binding them. However, this didn't fix the problem and I still got the same error.
From what code I can see it seems as though your field varible "context" was never initialized.
Simply call the no argument constructor:
context = new EMFDataBindingContext();
It appears that the context variable is null. I see that you define "context" at the top of the class, but I didn't see where it has been set.
Related
Hello Liferay Experts,
I have a requirement where I need to stop an Admin from assigning a role, I am trying to implement this with a ModelListener.
Here is the code..
#Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {
#Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ModelListenerException("User creation not allowed");
}
}
When this code executes, the exception is thrown but the UI doesnt handle it correctly, the control panel Menus are not displayed and the exception message is not displayed to the user.
How to throw an exception and handle it correctly in UI and display error message to the user.
Thanks
M
Andre Albert already gave you the correct hints in the comments.
You should keep the ModelListener and override the ActionCommand additionally.
First, read the tutorial about Overriding MVC Comands. When implementing your custom Command, use Liferay's implemenation as basis (don't forget to add the higher service.ranking) and replace the catch block with something like this:
// I took the freedom and refactored Liferay's catch block a little bit
catch (NoSuchUserException | PrincipalException e) {
SessionErrors.add(actionRequest, e.getClass());
actionResponse.setRenderParameter("mvcPath", "/error.jsp");
} catch (MembershipPolicyException e) {
SessionErrors.add(actionRequest, e.getClass(), e);
actionResponse.setRenderParameter("mvcPath", "/edit_user.jsp");
actionResponse.setRenderParameter("screenNavigationCategoryKey", UserFormConstants.CATEGORY_KEY_GENERAL);
actionResponse.setRenderParameter("screenNavigationEntryKey", UserFormConstants.ENTRY_KEY_ROLES);
} catch (ForbiddenRoleAssociationException e) {
// Here you can add a SessionError
// and set some render parameters
} catch (Exception e) {
throw e;
}
The ForbiddenRoleAssociationException does not exist yet. It's purpose is to distinguish this special case of a ModelListenerException from others which might not interest you. You'll have to implement it yourself. Just extend the ModelListenerException:
public class ForbiddenRoleAssociationException extends ModelListenerException {
// here might be some constructors
}
Now adjust your ModelListener so that it throws your new ForbiddenRoeAssociationException:
#Component(immediate = true, service = ModelListener.class)
public class TestUserModelListener extends BaseModelListener<User> {
#Override
public void onBeforeAddAssociation(Object classPK, String associationClassName, Objext accociationClassPK) throws ModelListenerException {
// ...
throw new ForbiddenRoleAssociationException(); // or any other constructor
}
}
This way you should be able to display error messages to admins (depending on your code in the catch block of the ForbiddenRoleAssociationException) and circumvent any other (programmatic) attempt to assign the Role as well.
I have an Xpage application that uses the extension library where the xsp.extlib.convstate is 'null' for one of three users until they manually refresh page. All three users access application via RDP using Citrix and internet options are the same for all three. Trying to figure out why this would be happening. The application is only on one 9.0.1 server.
From the looks of the source code, if there hasn't been a conversationState initialised yet, the conversationState would not be initialised until either:
after the Render Response phase (in the phase listener: com.ibm.xsp.extlib.component.layout.impl.ApplicationPhaseListener)
#SuppressWarnings("unchecked") // $NON-NLS-1$
public void afterPhase(PhaseEvent event) {
if(event.getPhaseId()==PhaseId.RENDER_RESPONSE) {
// After the render phase, we save the conversion state
ConversationState.saveInSession(event.getFacesContext());
}
}
in the setParent method of the UIApplicationLayout, and this seems to be guarded by a 'isRestoringState' condition, which means I don't think this would run on the first view of a page as there wouldn't be any state to restore.
#Override
public void setParent(UIComponent parent) {
super.setParent(parent);
if( null == parent ){ // removing parent
return;
}
// TODO should move this initialization to initBeforeContents instead
FacesContextEx context = (FacesContextEx) getFacesContext();
if(null != context && !context.isRestoringState()) {
ConversationState cs = ConversationState.get(context, FacesUtil.getViewRoot(this), true);
// Initialize the conversation state
// Set the current navigation path to the UserBean
ApplicationConfiguration conf = findConfiguration();
if(conf!=null) {
String navPath = conf.getNavigationPath();
if(StringUtil.isEmpty(navPath)) {
// If there isn't a navigation path that is defined, the use the default one
if(StringUtil.isEmpty(cs.getNavigationPath())) {
navPath = conf.getDefaultNavigationPath();
}
}
if(StringUtil.isNotEmpty(navPath)) {
cs.setNavigationPath(navPath);
}
}
}
}
So this might explain why it wouldn't be initialised until the 2nd page view.
You could try forcing an initialisation of the ConversationState before you try to use it, maybe in beforePageLoad, by calling one of the com.ibm.xsp.extlib.component.layout.ConversationState's get() methods.
Note the boolean parameter tells the method to create the ConversationState if it does not exist.
I don't do much ServerSide Javascript but I guess this works? The sentiment is correct.
#{javascript: com.ibm.xsp.extlib.component.layout.ConversationState.get(facesContext, true); }
If you are doing it in java then:
ConversationState.get(FacesContext.getInstance(), true);
Does this sound like an explanation of why you are seeing your behaviour?
I have to write event receivers for SharePoint lists (SharePoint 2013). For logging purposes, I am declaring my Guid variable (corresponding to a Project) globally and then assigning a value to it whenever required in the event receivers (Item Adding, Item Updating, etc...).
Below is the code sample:
public class ClassName : SPItemEventReceiver
{
Guid prjguid;
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
try
{
prjguid = new Guid(properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString());
.
.
.
}
catch (Exception ex)
{
// Exception Handling
WriteLog(prjguid + ex.message);
}
}
public void WriteLog(string message)
{
// Logging
}
}
This code throws en exception:
Object reference not set to an instance of an object.
Any possible explanations where I am going wrong ?
As you do not mention where this exception is thrown there are several possible reasons for this exception:
Possible reason 1:
If an exception is happening within your properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString()
call the prjguid variable will not get assigned.
Then in your catch WriteLog method you want to print out this *prjguid * variable.
This is where your variable can be null.
Inside your catch you could try to change your code to
catch (Exception ex)
{
// Exception Handling
if(prjguid != null)
{
WriteLog(prjguid + ex.message);
}else
{
WriteLog(ex.message);
}
}
Possible reason 2:
properties.Site.OpenWeb() returns null
Possible reason 3:
properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"] returns null
For case 2 and 3 you have to seperate those calls an check for null for both parts.
1.Trying to display exception message in popup window. Exception message is not appearing.
2.Eg: When i click button a popup window (Second fxml file) is to load with proper exception message in the label
3.Popup window is appearing, But the Label is not loading (Bold one --> ExceptionLabel.setText("Please enter Proper file path")) it says null pointer exception.
4.I am not sure what i missing. Same declared in FX:ID and also in second fxml file linked the main controller. Thanks in advance.
#FXML
public Label ExceptionLabel;
Stage PopupWindow = new Stage();
public void Buttonhandle(ActionEvent event) throws IOException {
try {
if(ESBOutboundFile!=null && OutputFile!=null){
String Output = SBlogpaser.Logpaser(ESBInboundFile,ESBOutboundFile,OutputFile);
System.out.println(Output);
}else{
Window(PopupWindow);
**ExceptionLabel.setText("Please enter Proper file path");**
}
} catch (Exception ex) {
System.out.println(ex);
}
}
public void Window(Stage Popup) throws Exception {
this.Popup=Popup;
final FXMLLoader fxmlLoader = new FXMLLoader();
Parent root= fxmlLoader.load(getClass().getResource("POPUPWindow.fxml"));
Scene scene1 = new Scene(root);
Popup.setScene(scene1);
Popup.show();
}
If i keep the label in "OK" handle button it is getting displayed.
From where are you expecting ExceptionLabel to be instantiated?
Assuming you are pointing the fx:controller attribute of the root of your POPUPWindow.fxml file to the current class, it will just create a new instance of that class, and inject values into that instance. The field ExceptionLabel in the current instance won't be initialized.
You could probably just about make this work by setting the controller of the FXMLLoader to the current object, something like this:
public void window(Stage popup) throws Exception {
this.popup=popup; // why?
final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("POPUPWindow.fxml"));
fxmlLoader.setController(this);
Parent root= fxmlLoader.load();
Scene scene1 = new Scene(root);
popup.setScene(scene1);
popup.show();
}
and then remove the fx:controller attribute from POPUPWindow.fxml.
This seems like a really bad idea, though, because now the current object is acting as a controller for two different FXML files. This will be confusing at best, and under fairly reasonable conditions would produce weird results. It would be much better to write a different controller class for the popup:
public class PopupController {
private final String message ;
#FXML
private Label exceptionLabel ;
public PopupController(String message) {
this.message = message ;
}
public void initialize() {
exceptionLabel.setText(message);
}
}
and then use the window(...) method above, but with
fxmlLoader.setController(new PopupController("Please enter Proper file path"));
Obviously, if you're reusing the window(..) method, you might want to pass the message in as a parameter to that method.
I wanted to debug the Seed() method in my Entity Framework database configuration class when I run Update-Database from the Package Manager Console but didn't know how to do it. I wanted to share the solution with others in case they have the same issue.
Here is similar question with a solution that works really well.
It does NOT require Thread.Sleep.
Just Launches the debugger using this code.
Clipped from the answer
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
The way I solved this was to open a new instance of Visual Studio and then open the same solution in this new instance of Visual Studio. I then attached the debugger in this new instance to the old instance (devenv.exe) while running the update-database command. This allowed me to debug the Seed method.
Just to make sure I didn't miss the breakpoint by not attaching in time I added a Thread.Sleep before the breakpoint.
I hope this helps someone.
If you need to get a specific variable's value, a quick hack is to throw an exception:
throw new Exception(variable);
A cleaner solution (I guess this requires EF 6) would IMHO be to call update-database from code:
var configuration = new DbMigrationsConfiguration<TContext>();
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
This allows you to debug the Seed method.
You may take this one step further and construct a unit test (or, more precisely, an integration test) that creates an empty test database, applies all EF migrations, runs the Seed method, and drops the test database again:
var configuration = new DbMigrationsConfiguration<TContext>();
Database.Delete("TestDatabaseNameOrConnectionString");
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
Database.Delete("TestDatabaseNameOrConnectionString");
But be careful not to run this against your development database!
I know this is an old question, but if all you want is messages, and you don't care to include references to WinForms in your project, I made some simple debug window where I can send Trace events.
For more serious and step-by-step debugging, I'll open another Visual Studio instance, but it's not necessary for simple stuff.
This is the whole code:
SeedApplicationContext.cs
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Data.Persistence.Migrations.SeedDebug
{
public class SeedApplicationContext<T> : ApplicationContext
where T : DbContext
{
private class SeedTraceListener : TraceListener
{
private readonly SeedApplicationContext<T> _appContext;
public SeedTraceListener(SeedApplicationContext<T> appContext)
{
_appContext = appContext;
}
public override void Write(string message)
{
_appContext.WriteDebugText(message);
}
public override void WriteLine(string message)
{
_appContext.WriteDebugLine(message);
}
}
private Form _debugForm;
private TextBox _debugTextBox;
private TraceListener _traceListener;
private readonly Action<T> _seedAction;
private readonly T _dbcontext;
public Exception Exception { get; private set; }
public bool WaitBeforeExit { get; private set; }
public SeedApplicationContext(Action<T> seedAction, T dbcontext, bool waitBeforeExit = false)
{
_dbcontext = dbcontext;
_seedAction = seedAction;
WaitBeforeExit = waitBeforeExit;
_traceListener = new SeedTraceListener(this);
CreateDebugForm();
MainForm = _debugForm;
Trace.Listeners.Add(_traceListener);
}
private void CreateDebugForm()
{
var textbox = new TextBox {Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, WordWrap = false};
var form = new Form {Font = new Font(#"Lucida Console", 8), Text = "Seed Trace"};
form.Controls.Add(tb);
form.Shown += OnFormShown;
_debugForm = form;
_debugTextBox = textbox;
}
private void OnFormShown(object sender, EventArgs eventArgs)
{
WriteDebugLine("Initializing seed...");
try
{
_seedAction(_dbcontext);
if(!WaitBeforeExit)
_debugForm.Close();
else
WriteDebugLine("Finished seed. Close this window to continue");
}
catch (Exception e)
{
Exception = e;
var einner = e;
while (einner != null)
{
WriteDebugLine(string.Format("[Exception {0}] {1}", einner.GetType(), einner.Message));
WriteDebugLine(einner.StackTrace);
einner = einner.InnerException;
if (einner != null)
WriteDebugLine("------- Inner Exception -------");
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _traceListener != null)
{
Trace.Listeners.Remove(_traceListener);
_traceListener.Dispose();
_traceListener = null;
}
base.Dispose(disposing);
}
private void WriteDebugText(string message)
{
_debugTextBox.Text += message;
Application.DoEvents();
}
private void WriteDebugLine(string message)
{
WriteDebugText(message + Environment.NewLine);
}
}
}
And on your standard Configuration.cs
// ...
using System.Windows.Forms;
using Data.Persistence.Migrations.SeedDebug;
// ...
namespace Data.Persistence.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
// Migrations configuration here
}
protected override void Seed(MyContext context)
{
// Create our application context which will host our debug window and message loop
var appContext = new SeedApplicationContext<MyContext>(SeedInternal, context, false);
Application.Run(appContext);
var e = appContext.Exception;
Application.Exit();
// Rethrow the exception to the package manager console
if (e != null)
throw e;
}
// Our original Seed method, now with Trace support!
private void SeedInternal(MyContext context)
{
// ...
Trace.WriteLine("I'm seeding!")
// ...
}
}
}
Uh Debugging is one thing but don't forget to call:
context.Update()
Also don't wrap in try catch without a good inner exceptions spill to the console.
https://coderwall.com/p/fbcyaw/debug-into-entity-framework-code-first
with catch (DbEntityValidationException ex)
I have 2 workarounds (without Debugger.Launch() since it doesn't work for me):
To print message in Package Manager Console use exception:
throw new Exception("Your message");
Another way is to print message in file by creating a cmd process:
// Logs to file {solution folder}\seed.log data from Seed method (for DEBUG only)
private void Log(string msg)
{
string echoCmd = $"/C echo {DateTime.Now} - {msg} >> seed.log";
System.Diagnostics.Process.Start("cmd.exe", echoCmd);
}