Reusing some existing java code in my xpage application now that who is asking is important

I’m not sure what I should have called this little tip but Imagine the scenario:

I have a lot of code I’ve already written and packaged up as a servlet which interacts with Notes/Domino and creates a session using it’s own set of credentials.  

Now what if the situation were a little different and the web application required someone to login and I wanted the Java code to use the credentials of the user that logged in.

I tried various methods, including trying to reuse an LTPAToken nothing worked. 

After talking with Serdar Başeğmez (thanks to you) I came to terms with the fact that I’d have to replace the servlet with a headless XPage (sometimes known as an XAgent). I’ve been doing just that with SSJS for a little while but it’s a shame to use SSJS and I haven’t found a great way to debug it.

I wanted to try another approach on the off chance:  I can use Java code in my headless XPage (either via the Java component or via a jar file), and I have a session object in my SSJS.

So if I create a new class:

package com.test;
import lotus.domino.NotesException;
import lotus.domino.NotesFactory;
import lotus.domino.Session;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.View;
public class Identity {
public Session session=null;

public void setSession(lotus.domino.Session s){
session = s;
}
public Session getSession(){
return this.session;
}

public String whoami(){
try{
return getSession().getEffectiveUserName();
} catch(Exception e){
return e.getMessage();
}

}
}

 

And if I create an XPage:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendered="false">
<xp:this.afterRenderResponse><![CDATA[#{javascript:
try { 
     var identity:com.test.Identity = new com.test.Identity();
     identity.setSession(session);
     print(identity.whoami());
}catch(e){
     print(e);
}
}]]>
</xp:this.afterRenderResponse>
</xp:view>

Now when I build the application, and visit the xpage: /text.xsp?open&login the server console will print the name of the logged in user. I haven’t explored the limitations yet but if that works in anger then I’ll have a mechanism for reusing the Java code I already have, which is nice 🙂

Tagged with: , , , , ,
Posted in Uncategorized

Thanks Bruce Elgort!

Once upon a time I had an idea for a site where we might, in a small way, do for BlackBerry what openNTF had done for Notes & Domino, that was opencod.org (some kind of Japanese backup company uses the URL now).

RIM wasn’t terribly interested (or keen to let me use openBerry.com) but that’s another story.

Lotusphere was on the horizon and I wanted to get something up and running really quick so when I cheekily contacted Bruce to ask if I could steal the openNTF templates and skin them for my purposes I anticipated a polite no.  

What I got was something different.  Not only did Bruce get me the templates but he marshaled help from other openNTF stalwarts when I had questions.  Clearly demonstrating Bruce’s consistent commitment to the ideals of openNTF Bruce made the difference between openCOD being born in time for Lotusphere and not. He’s always had time for me from that day to this. 

Over the years we’ve chatted and I’ve come to admire him.  We have something more in common now; I trained as a school teacher and ended up in IT and now he’s teaching.  I’d like to imagine that Bruce’s skill as a drummer has helped him develop his impeccable timing; going from success to success in IT and now moving into his new career.

So congratulations on your many achievements Professor Elgort! More power to your elbow (which is probably now covered by a nice leather patch over a tweed jacket 🙂 ). 

 

 

* I also owe Bill Buchan a debt of thanks for hosting openCOD and for Declan Lynch’s help when I developed the original openCOD project BBMetaBlog.

 

 

Tagged with: , ,
Posted in Uncategorized

Quick tip: Openlog and the Field is too large (32k) POS.

Openlog is great. The work Paul Withers, Tim Tripcony, Nathan T Freeman, and Julian Robichaux have done in making it available for us to use in our Java programs is great too.

Sadly the “Field is too large …..” error sucks as badly as it ever has.

Capture

I’m writing large chunks of XML into the logMessage field which provokes this error.  I don’t need to see the XML in the view so the solution I’ve implemented is:

Edit the OpenLogItem class;

Find the writeToLog method;

Just before the logDoc.save(true) call insert this:

Item logMsg = logDoc.getFirstItem(“logMessage”);
logMsg.setSummary(false);

and recycle the logMsg Item using your favourite method.

Posted in Uncategorized

Jamie Smart’s Clarity: Review

Clarity by Jamie Smart

I have a busy mind. I often feel that I’m racing from one commitment to another getting stressed because traffic is slow or because I’ve so badly robbed the time I owe Peter that I’ve stolen from Paul as well 🙂

I was working at 4am on the day I left for my most recent holiday. Whilst at the airport I saw this book. I’m not sure what made me buy it perhaps it was the offer:

“What would it mean if you could declutter your mind?”

There’s a huge market in self help books with bold claims about your scope for personal transformation if you’d only apply the method laid out in the book. Jamie Smart says that Clarity is not a self help book. You already have all you need, you just have to get out of your own way.

The premise is simple. You and I were born with wisdom, resilience, creativity and lots of other capacities that allow us to face life’s uncertainties. However, we are conditioned instead to believe that our happiness is dependent on external circumstances.

I’ll be happy when I’ve learnt this new programming language;
I’ll be happier when I’m slim again;
I’ll be happy when I feel like I fit in/belong;
When I reach a thousand or twenty thousand twitter followers I’ll be happy.

These kinds of needs are relentless illusions, if you believe in them you’re never happy because there’s always more to do. ‘Here’ is only a step on the road to ‘there’ where things are so much better. That’s how sales works, how game theory works.

Goals are important but they are a symptom of something more important the causes of those goals: your thinking.

From moment to moment your experience of life is created by your thinking. Your thoughts and therefore your experience is created by your mind. Given the same set of circumstances your experience and mine will be different but equally real for each of us.

Before having children I would go SCUBA diving. In dark or fast water it’s possible to lose your sense of direction. Swimming up whilst actually travelling down or losing the exit in a submerged space can be lethal. It’s not the lack of visibility or the loss of cues that’s lethal it’s that your thinking is based on a misunderstanding of what’s really going on. Smart uses lots of metaphors like this to emphasise his view that outside-in thinking is a misunderstanding.

What if your security, happiness and sense that things are OK begin within you and radiate outward. From thoughts that you generate. Happiness, competence and resilience are your default settings, if you’d only let go of superstitious and habitual thinking.

I’m an Agnostic in the religious sense. Why should trust my thinking? I can create as many Gods or Devils as I like and make them real if I want to. In time I’ll discover the truth and intuitively I know the answer to this question cannot be found in the here and now. If your truth is the polar opposite then yours is no less real.

There’s a level of consciousness that exists below the level of thinking that responds appropriately to life as it really works, apparently. Clear your mind and your innate wisdom will point you in the right direction. That happens to me most on the way to the supermarket at lunchtime, or on the drive home when I’ve failed to spot an obvious solution to a tricky problem for hours. We have all the resilience required to cope with life’s ups and downs. I’ve managed to overcome many downs and appreciate many ups in my life why shouldn’t that continue?

You get the idea.

I believe in the premise that we create our experience of the world around just as we make sense of the images projected at the cinema or the dots on a printed page. And given the many models of life I prefer One where I am happy and OK from the inside out to one where I’m happy because I have this or that or because I’m on my way to some place better down the road.

The book has some useful insights. I like the ideas on leadership, and disrupting the reality my habitual and superstitious thoughts create.

Like food that leaves a bitter aftertaste there is an inconsistency in the book. Some of the language in the book feels contrived and drawn out to me. Jamie Smart has trade marked Innate Thinking, built a business around it and allowed himself to join a circle of “super-coaches” that have the secret to “living the life you want”. Smart is living the life he wants and if that happens to coincide with bringing some benefit to you that’s a win-win I guess.

But the aftertaste I get doesn’t spoil the meal entirely.

We continue to make life harder and more complex for ourselves. We create problems for ourselves so we can create the solutions. Sometimes we run to stand still. We compare what we have to the guy next door and believe the grass is greener where he says it is or because it looks like it. We consistently look for happiness outside and not within.

It’s not a bad thing to challenge your current reality. The world is not flat, disease is not caused by bad smells. Overall I enjoyed this book and the challenge to my habitual thinking and found that it’s not a million miles away from what makes sense to me.

Disclaimer:
I bought this book at the airport.
I need to read this book again but not soon.

Tagged with: , , ,
Posted in books, life

OSGi development from Connect 2013

Paul Fiore has been good enough to share Show112 slides from Connect 2013. So if you want to know how to set up Eclipse to develop OSGi plugins these slides will really help. 

 
You will also want to have a look at slides from Connect 2013 BP207:
 
Posted in Uncategorized

OpenLogging from an OSGi Servlet

Further to the last post on OpenLog which works nicely for Servlets that are contained within an NSF.  What if you want to use OpenLog in your OSGi Plugin Servlet?

If you follow the instructions in the previous post but your Servlet is an OSGi plugin you will hit a runtime error:

18/02/13 22:23: Exception Thrown java.lang.NoClassDefFoundError: com.ibm.xsp.resource.Resource at java.lang.J9VMInternals.verifyImpl(Native Method) at java.lang.J9VMInternals.verify(J9VMInternals.java:72) at java.lang.J9VMInternals.initialize(J9VMInternals.java:134) at com.jasonhookonline.logging.OpenLogItem.getSession(OpenLogItem.java:635) at com.jasonhookonline.logging.OpenLogItem.getLogDb(OpenLogItem.java:256) at com.jasonhookonline.logging.OpenLogItem.writeToLog(OpenLogItem.java:977) at com.jasonhookonline.logging.OpenLogItem.logMsg(OpenLogItem.java:725) ….

You’ll be tempted, no doubt to fix the missing class by finding the right jar and copying it to /jvm/lib/ext but that’s a slippery slope.

Instead you should follow the instructions in the earlier post before applying the following tweaks.

In your Servlet you need to create a session (I’m going to create, use and get rid of the session inside the doGet or doPost method for the purposes of this example) and pass it to the getOpenLogItem method.

In your Servlet Class

public class MyServlet extends ... {
Session _session = null; // a member variable
    try {
         NotesThread.sinitThread();
         _session = getSession();
    } catch (NotesException ne){

    } catch (Exception e){

    } finally {

         try{
            _session = null; 
         }
         NotesThread.stermThread();
   }
private Session getSession() {
 
     if(_session == null) {
        try {
            _session = NotesFactory.createSession("", "some account", "the internet password");
        } catch (NotesException e) {
          // TODO Auto-generated catch block
            e.printStackTrace();
         }
     } else {
       try {
           @SuppressWarnings("unused")
           boolean pointless = _session.isOnServer();
     } catch (NotesException ne) {
          //TODO TO DO A technical problem has occurred
        try{
          _session = NotesFactory.createSession("", "some account","the internet password");
        } catch(Exception e){
           resp.sendRedirect("/error.php?msg=oops!");
        }
     }
    }
 return _session;
 }

} //EO of the class

In your utility class

You need to modify the getOpenLogItem method so it accepts a session object:

package com.jasonhookonline.utility;
import com.jasonhookonline.logging.OpenLogItem;
 import lotus.domino.Session;
public class Utility {
 public static OpenLogItem _oli;
public static OpenLogItem getOpenLogItem(Session _session){
 if (_oli == null) {
 _oli = new OpenLogItem(_session);
 }
 return _oli;
 }
 }

In the OpenLogItem class

Replace the getSession method:

private Session getSession() {

 if(_session == null) {
 try {
 _session = NotesFactory.createSession("", "some account", "the internet password");
 } catch (NotesException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 } else {
 try {
 @SuppressWarnings("unused")
 boolean pointless = _session.isOnServer();
 } catch (NotesException ne) {
 //TODO TO DO A technical problem has occurred
 try{
 _session = NotesFactory.createSession("", "some account", "the internet password");
 } catch(Exception e){
 //TODO TO DO A technical problem has occurred
 }
 }

 }
 return _session;
}

Back in your Servlet:

Utility.getOpenLogItem(_session).logMsg(“Servlet Running doPost”);
Utility.getOpenLogItem(_session).logError(ne);

Tagged with: , , , ,
Posted in Coding, Java, XPages

Adding logging to your Servlet or DOTS task (By Borrowing Code)

I have to thank  Paul Withers, Nathan T. Freeman & Tim Tripcony for the core of this article because they created the Logging Class I steal, borrow and hack modify.  I have to thank the very great Julian Robichaux (and Rob McDonagh who contributed) for OpenLog.

That said if there are any mistakes in what follows they are my own 🙂  I hope I’ve respected the terms of the Apache License, let me know if I haven’t.

The use case for this is quite simple you have a Servlet, or possibly a DOTS tasks (haven’t tried that yet but soon)  beavering away quietly and you want to keep an eye on it.  I suppose you could log to files on the server but that’s not terribly accessible to QA or you perhaps when you’re already very busy.  Since we have Julian’s OpenLog I vote we log messages and errors to an OpenLog database.  If you are with me follow on for the almost step by step instructions. Unlike previous post I’m not going to provide a screenshot for each and every action, if you are here I suspect you know how to use designer.

Pre-Requisites:

  • Domino 8.5.3
  • Domino Designer 8.5.3
  • Notes & Domino Upgrade Pack 1 (Part No. CI5HUEN available from Passport Advantage)
  • Install the Domino 8.5.3 Upgrade Pack
  • OpenLog from OpenNTF.org here’s the current URL: http://www.openntf.org/projects/pmt.nsf/ProjectLookup/OpenLog (Set up OpenLog as per the instructions in the database (for this post I’m allowing anonymous to be a despositor))
  • The XPages Help Application Project from OpenNTF No need to set that up but be ready to open it in Domino Designer for Eclipse (DDE) soon.
  • Some Java knowledge 🙂

Moving on..

If you read this whole post first you can decide whether or not create your own packages, and new class names for the class we’re taking and modifying from the OpenNTF help app.

  • In your Java Servlet/DOTS application create a new package mine would be com.jasonhookonline.logging
  • Right click your new package and create a new class, call it OpenLogItem no need to worry about it’s superclass or what it extends.  The new class should open in an editor for you
  • Open the XPages Help Application in DDE, and then open the Package Explorer view. Expand the src folder and com.paulwithers.openLogClass.  Double click the OpenLogItem class. In the editor copy all of the code, you must retain the copyright notice, and we must add a note that we’ve modified the file to comply with the license.

xpageshelploggingclass

  • Go back to your OpenLogItem class and select all and delete the existing code, paste the new class from the Help App.
  • The editor will point to numerous errors, don’t be alarmed, just log them (Just kidding, don’t do that it’s a waste of time!)
  • Remove import com.timtripcony.util.JSFUtil; whilst his stuff is great we don’t need it we’re not using JSF.
  • First thing to fix is the method getThisAgent() which returns a String:
/**
 * @return the thisAgent
 */
 public String getThisAgent() {
      return "Servlet: com.jasonhookonline.servlets.Servlet1";
 }
  • Fix getSession() The OpenLog ACL would need to allow depositor, and this piece relies on you having installed the upgrade pack. The editor will still point to an error at the getCurrentSession lines.  To fix these keep following.
    private Session getSession() {
       if (_session == null) {
            _session = getCurrentSession();
        } else {
      try {
            @SuppressWarnings("unused")
             boolean pointless = _session.isOnServer();
            } catch (NotesException recycleSucks) {
                 try {
                 _session = getCurrentSession();
                } catch (Exception e) {
                debugPrint(e);
                    }
               }
         }
      return _session;
     }
  • In the project properties find build path, click on the libraries tab and add an external jar com.ibm.xsp.extlib.core_8.5.3.20111208-0717.jar located in <Notes/Domino program dir>/osgi/extlib/eclipse/plugins

logginginservlets-addjar1

  • Add an import statement at the top of your class below package: import static com.ibm.xsp.extlib.util.ExtLibUtil.*;
  • Finally change the value given to _logDbName: private String _logDbName = “OpenLog.nsf”;
  • Save your class.

All of the errors should now have been resolved.

How to use logging in your other classes

  • Open your class (the Servlet one for example) and do the following:
  • Add an import statement to import your new logging class.  My statement would be this: import com.jasonhookonline.logging.OpenLogItem;
  • Add a member variable to your class (just within the start of your class): private OpenLogItem _oli;
  • Add a new method to your class:
    private OpenLogItem getOpenLogItem() {
        if (_oli == null) {
            _oli = new OpenLogItem();
        }
    return _oli;
   }

Now you are ready to log!

    try {
       getOpenLogItem().logMsg("I am very trying");
    } catch(Exception e){
       getOpenLogItem().logError(e);
    }

What next?

You could explore some other ideas like LogLevelling (there’s examples of this if you follow the DebugPrint methods use in the OpenLogItem class.

You could (as Paul Withers suggests) create a utility class to avoid having to add the getOpenLogItem() method to each class:

    package com.jasonhookonline.utility;
    import com.jasonhookonline.logging.*;
    public class Utility {
         public static OpenLogItem _oli;

         public Utility(){
         }

         public static OpenLogItem getOpenLogItem(){
                if (_oli == null) {
                    _oli = new OpenLogItem();
                }
                    return _oli;
                }
   }

Then you can use Utility.getOpenLogItem().logMsg(“”); from any class.

Resources

The new OpenLogItem class file (due to limitations of WordPress I had to upload it as a docx rather than a txt file!)

OpenLogItem

Tagged with: , , , , ,
Posted in Coding, Java, Tips

A visit to the Cambridge Science Centre

 

I took a day off today to spend with Mrs H and the children during the school half term holiday.

We decided to visit the newly opened Cambridge Science Centre (CSC) in Jesus Lane, Cambridge. Despite Cambridge having an international reputation for Science and Mathematics due to the status of the City’s Universities it has lacked a venue to engage people in popular science.

It’s a fair distance from our house to Cambridge and we took a break from a busy morning’s arguing, petulance and disagreement to drive to Cambridge.  What fun school holidays are 🙂

Pardon this little aside, it becomes relevant at the end. We listened to Jeremy Vine’s Radio 2 phone-in show as we drove; the Government’s Workfare programme the topic of discussion.  If you are not familiar this is the programme where unemployed people have been compelled to work to line the pockets of large businesses in order to gain valuable work experience stacking shelves rather than looking for work or doing socially useful voluntary work. Apparently in this country when you complete a degree course you are ready to learn how to correctly stack shelves in Poundland. This prompted yet another discussion about emigration 🙂 What has this country come to?

I confess to knowing Elan Lennard (@glamourgeek) who is married to Chris, a Director of the Charity that founded the centre.  Despite knowing a little about how hard Chris, Elan and the team have worked to create the centre, I didn’t know what to expect.

The centre is a real joy. In a relatively compact space it’s full of interactive exhibits exploring Electricity, Motors, Hearing, Gears, X-Rays, Colour, Sight, Refraction and Lift. With each exhibit there’s an explanation of the science, with the exception of the gears exhibit.  Despite being aimed at older children a few examples of what to build from the various levers, cranks and gears would help smaller children learn the basics.  Volunteers and staff are also on hand to explain and play.  There are (hourly I think) demonstrations, we enjoyed a demo of static electricity given by a very enthusiastic and entertaining scientist. Despite having ambitions to grow, the Cambridge Science Centre punches above it’s weight and has the potential to inspire thousands of future physicists, biologists and chemists.

If only empty High Street shops up and down the country could be filled with exhibits like those we played with today and enthusiastic volunteers recruited to build science clubs.  If they could change the exhibits frequently, attract knowledgable speakers and through guerrilla science inspire children to want to study hard and pursue careers in physics, biology, chemistry and technology.  If, next door, there was a maths club, an entrepreneurs club and a computer science club we wouldn’t have to worry about our children struggling to find shelf stacking jobs in Sainsbury’s.  Instead of aiming for the lowest common denominator our children could realise their very great potential and allow the UK to compete strongly in the future world economy.   

The CSC is well worth a visit if you are in the area, and I would love to see it grow, not just in Cambridge but elsewhere. 

 

 

 

 

Posted in Uncategorized

A couple of quick tips: The Domino Debug Plugin & Eclipse

Because of the security issues that apply to Servlets created with an NSF* I’ve started to develop a new Servlet as an OSGi plugin.

The slide deck from SHOW112 at Lotusphere 2012 (Presented by David Taieb, Paul Fiore and Elizabeth Sawyer) is an invaluable resource btw. I’ve been trying to find a link to the presentation on Slideshare or one of the presenters blogs and I haven’t found one yet.  I’ll try to find one or ask if any of the presenters would share it.

Anyway I needed to install the debug plugin (the 7 Feb 2012 release from here). I downloaded the zip and followed the doc and could get Eclipse to see the software.  Won’t bore you with what I tried but I was close.

Eclipse

Consider installing/upgrading to a later version of Eclipse (that’s tip #1).  I’m using Juno SR1 now after plodding on with Helios in the mistaken belief that I needed to use a older version of Eclipse for the XPages SDK for Eclipse RCP to work.  Nathan Freeman says that Juno SR1 fixes the bug that required you to reselect your target platform each time you started Eclipse.

To install the plugin**

Download the Zip, and Extract it;

In Eclipse click the help menu and choose “Install new software”

ddp-addnew

In the next dialog click Add, give the new software a name and click Local.

ddp-add

Find the folder where you unzipped the plugin and drill down to the updatesite folder, click on OK and OK.

ddp-select

Select the plugin software in the categori(s|z)ed list and follow the remainder of the documentation.

* see https://8b30b0.wordpress.com/2013/02/08/so-you-want-yo…on-from-domino/

** Thanks to Serdar Başeğmez

Tagged with: , ,
Posted in Coding, Tips, XPages

So you want your Servlet to get an authenticated session from Domino

It seems a like a pretty fundamental question, in a running Servlet I want to access Domino resources that I have wisely protected using the the very fine security of IBM Notes and Domino.

I want the Servlet to be able to read and write data to Domino whilst keeping that data from the client that called the Servlet (or xAgent) and preventing the client from writing directly.

I’d be happy to be able to get a session that represented the signer of the application.  I can get a session for a registered user by calling the Servlet using ?open&login and signing in.  That’s not practical.

I’ve looked here: http://stackoverflow.com/questions/11401862/how-can-you-use-sessionassigner-in-a-java-bean-called-from-an-xpage where Mark Leusink (http://stackoverflow.com/users/1177870/mark-leusink) implies the use of ExtLib’s getCurrentSessionAsSigner() could be used.  I’ve tried it, having signed the whole application with a single user id and it doesn’t return a session.  The answer seems to lie in the Servlet’s inability to get a FacesContext object.

This feels like the answer should be obvious but it isn’t to me.

I’ve posted the same question over at StackOverflow…..

http://stackoverflow.com/questions/14771700/i-want-my-domino-servlet-to-get-an-authenticated-user-session

Update

I need to thank Nathan Freeman once again.  It appears that a Servlet running inside an .NSF is subject to security constraints that do not allow new sessions to be created as user sessions.  This is fine if you are happy allowing anonymous access to databases or have a use care where the Servlet can be opened using a ?open&login url.  In many cases neither will be acceptable.  And that means you have to create the Servlet as an OSGi plugin.  More about that in later posts.

Posted in Uncategorized