Java – Johan Känngård http://johankanngard.net Running, coding and mind dumps Thu, 01 Dec 2016 18:23:26 +0000 sv-SE hourly 1 Managing logging with Log4j and Chainsaw http://johankanngard.net/2007/06/19/managing-logging-with-log4j-and-chainsaw/ Tue, 19 Jun 2007 11:52:32 +0000 http://johankanngard.net/2007/06/19/managing-logging-with-log4j-and-chainsaw/ […]]]> Those of you who haven’t used System.out.println(”My variable: ” + myVariable) in some Java classes to get debug information to the console, raise your hands please. None? 😉

I am very fond of logging as a complement to debugging, since I can ”trace” actions in my programs even if the classes is in production. ”But hey, logging makes the application go slower!” you might think. Well, it’s up to you to decide, a small performance hit is likely to occur, a big hit if you don’t read the documentation of for instance the PatternLayout.
I use Log4j a lot in the Java code I design and write, and haven’t noticed any big difference between logging and not logging.
So, you might have used Log4j a bit and used Chainsaw to look at Log4j logging files. Why not look at the logging in realtime? Here is how to do it.

Setting up Log4j

To see the logging in real time, I use an appender called SocketHubAppender that acts as a server. Create the log4j.xml in the root of your Java application’s directory, or add the vital bits to your own:

< ?xml version="1.0" encoding="UTF-8" ?>
< !DOCTYPE log4j:configuration SYSTEM "log4j.dtd">





When starting your application and outputs some logging messages with the usual logger.debug(”Hello world!”); it will be sent to the appender’s socket, defined above as 1020. The output can’t be read using a telnet session, because the things you will see is the logging events serialized… You need something to look at those serialized logging events with – Chainsaw!

Configure Chainsaw

Create a file (or add the vital bits below to your own…) called chainsaw-config.xml somewhere on your local disk, for instance c:tempchainsaw-config.xml, and change the host from my.remote.host.net to the host where you set up the logging with the SocketHubAppender and that the port matches the one you used:

< ?xml version="1.0" encoding="UTF-8" ?>
< !DOCTYPE log4j:configuration >






Start Chainsaw via Java Web Start by launching the jnlp-file at the homepage. Open the menu ”View”, ”Show Application-wide Preferences”, go to the ”General” tab and enter ”file://c:/temp/chainsaw-config.xml” (leave out the quotation marks) in the ”Automatic Configuration URL” field, or whatever you named your config file. Click ”OK” and restart Chainsaw. You should now see your receiver to the right named ”MyRemoteLogging”.
Try starting up your Java application and output some logging, and you will see them pop up directly in Chainsaw!

So why not use a simple file or database to log to? You can do that too, you are not limited to one appender per application. You can set up as many as you want, for instance a ConsoleAppender, a SocketHubAppender and a JDBCAppender that logs the events to all those targets.
Log4j is powerful, but it doesn’t makes miracles if you don’t use some structured logging. Events like ”Hello world!” is not going to help you, but some well designed NDC.push()’s and other will do good. And don’t forget to add the NotesExceptionRenderer to your class path, so that you get more info from those badly-designed exceptions :-)

]]>
g33k date http://johankanngard.net/2007/05/25/g33k-date/ http://johankanngard.net/2007/05/25/g33k-date/#comments Fri, 25 May 2007 09:59:54 +0000 http://johankanngard.net/2007/05/25/g33k-date/ […]]]> Johan defeating Darth Vader
I was a key speaker at the first g33k date ever yesterday, and it was Ekakan that held the meeting in their small but great office at Saltmätargatan in Stockholm. Quite a lot showed up, many of which I know by name, but not by face, since they are all bloggers with no pictures at their sites! :-) After having slurped down some well-known red-canned sugary liquid, I started my speech using OpenOffice Impress as presenter application. The slides can be found at the bottom of this post. It has not been cleaned up, so some references are to my local file system and applications on my Domino server will not work. I have put the database I used for the web service stuff as an attachment below, but use it at your own risk!
I talked briefly about who I am, what I like, what my shoe size is and other important stuff. A short history on how the web has evolved over time (1.0, 1.5, 2.0) and my own suggestion of the next 3.0 level, which includes web services on the client side. I demonstrated a simple AJAX solution for typeahead with script.aculo.us and Domino and a web service consumer in the browser.
A Midlet with a web service consumer was the next item to show, and it worked as a charm in the emulator!
After my 15 minutes of fame (or rather 40), we had a short drinking and chatting pause.

Joachim Dagerot introduced us into ext.js, a client-side framework with lot’s of goodies like menus, trees, tabbed tables, layouts etc. The framework looked really impressive, and applications based on it was more of a Windows experience. When developing applications with ext.js, almost everything is done in JavaScript, including the templates of the pages. You don’t have to download the complete framework, you can take bits and pieces, if you want only a part of the gadgets.

After more beverages, snacks and more chatting, connections were made, business cards and email addresses exchanged hands. I left rather early though, I hope my fellow bloggers to give the full story 😉 Photos were taking during the meeting, and I would really love to see them, since I didn’t use my own camera.

I hope that this event wasn’t the last of it’s kind in Sweden, it was great fun to see fellow bloggers and geeks!
Thanks for a great event everyone, especially Ekakan who arranged the g33k date!!

Btw, the picture at the top is NOT from the g33k date, it was just a picture I used in the presentation as an illustration of the thin red line between being a geek and a nerd. 😀

[tags]g33k, geek, J2ME, AJAX, Webservice, Ekakan[/tags]

]]>
http://johankanngard.net/2007/05/25/g33k-date/feed/ 7
Sammanfattning av Lotusphere Comes To You http://johankanngard.net/2006/03/14/sammanfattning-av-lotusphere-comes-to-you/ Tue, 14 Mar 2006 13:21:42 +0000 http://johankanngard.net/2006/03/14/sammanfattning-av-lotusphere-comes-to-you/ […]]]> .inlineImageContainer {float:left; margin-right:10px;} H4 {padding-bottom:0px; margin-bottom:0px;clear:both;} P {margin-top:0px;padding-top:0px;}

Detta är i korthet vad som sades under halvdagen den 8:e mars i Kistam som IBM valt att kalla Lotusphere Comes to You. Presentationerna som visades finns att hämta hos IBM.

Inledningstal av Ed Brill

Ed Brill

Det var kul att se Ed Brill på hans första besök i Sverige! Han presenterade siffror som visar att Lotusphere är populärare än någonsin och att Notes knappast är dött! Dessutom drog kort han igenom de nyheter som kommer framöver, vilka presenterades i detalj av de svenska IBM-medarbetarna. Framförandet var innehållsrikt, men lite för kort. Själv hade jag inte möjligheten att tala med honom, och jag hoppas att han återkommer till Sverige vid ett senare tillfälle!

Notes på Linux

Karl Dettner

v.7.0.x av Notes kommer att gå att köra på Linux via Workplace Managed Client. Karl Dettner demonstrerade detta LIVE genom att köra en fönsterhanterare i Linux, och startade Notes samt surfade runt i databaser. Domino Designer kommer inte att kunna köras på Linux (än), vilket gör att man fortfarande är hänvisad till Windows alternativt Wine, en öppen-källkodsimplementation av Windows API på Linux. Dock har det dykt upp ett försök till att skapa en webbbaserad IDE som liknar Domino Designer, vilket kan vara värt att bevaka.

Notes på Mac

Version 7.0.2 kommer att kunna köras på MacOS X. Domino Web Access i samma version kommer att stödja Mozilla Firefox på MacOS X, dock ej Safari.

Notes 8 ”Hannover”

8:an bygger på Eclipse och kan därmed köras på ett flertal plattformar. Publik beta dyker upp i slutet av 2006. Alla befintliga Notesapplikationer kommer att fungera i Hannover (vilket upprepades som ett mantra ett flertal gånger). Fokus på något som kallas aktiviteter, som är en form av delprojekt i en arbetsgrupp. Möjlighet att spara/gruppera dokument, mail, chat etc. i aktiviteter för att senare kunna söka fram informationen. Markering av dokument sker genom att hela raden visas i annan färg, som är standard i alla andra program på de flesta plattformar. Bockarna i kanten kommer således att försvinna.
Notesklienten kommer att kunna köra Webservices, även i lokala applikationer.

Sametime 7.5

Anders Kjellner

Anders Kjellner förklarade att även denna nya release är baserad på Eclipse, vilket möjliggör olika utseende i olika operativsystem, dvs. det ser ut som en MacOS-applikation på MacOS, och ser ut som en Windowsapplikation i Windows. Pluginarkitekturen från Eclipse gör att tredjepartsutvecklare kan ta fram produkter för att utöka funktionaliteten. Till en början finns t.ex. plugins för att koppla Sametime till videokonferensutrustning (Tandberg) och IP-telefoni (Avaya).
Det bakomliggande nätverksprotokollet är förbättrat pÃ¥ mÃ¥nga punkter, bl.a. har mängden data som skickas minskats, samt att den använder ”intelligent” teknik för att hitta det mest optimala sättet att kommunicera med servern.
Några användarnyheter är bl.a. möjligheten att använda olika stilar på chattmeddelanden, stavningskontroll (endast engelska till att börja med), smileys, kunna skicka Noteslänkar och historik som behåller formattering. Positionsmedvetande gör att Sametime känner av i vilket nät du kopplat upp dig i, och frågar efter den exakta adressen. Detta gör att applikationen kan hjälpa till med t.ex. val av rätt skrivare, hitta rätt till restauranger etc.
Numera krävs en JVM pÃ¥ minst 1.4 för att använda Sametime, vilket betyder att Internet Explorers MS JVM inte kommer att fungera, utan man mÃ¥ste ladda ner ”en annan”, förslagsvis Suns.

Workplace Designer 2.6

Erik Söderholm

Utvecklingsmiljön för Workplace Collaborative Services, Workplace Designer, är väldigt likt Domino Designer, och arbetssättet är lika intuitivt och enkelt, men skiljer på några punkter. Bl.a. har WD stöd för dra-och-släpp av element, exakt positionering och databasmodellering. För att göra livet ännu enklare, använder sig WD av @funktioner i kod i t.ex. knappar. Alla @funktioner från Notes/Domino är inte implementerade, men de mest basala. En inbyggd Java-brygga medger åtkomst av Javaobjekt och klasser på servern direkt från Javascript.

Innovation Pack

Ny funktionalitet till Notes och Domino 7 genom nya mallar/databaser, ingen uppdatering av koden i Notes/Domino. Dessutom en ny installation som tillåter Notes att installeras på USB-minne (som dock kan göras idag men lite mer omständligt). Släpps under tredje kvartalet 2006.
Några av mallarna som kommer att följa med:
Blog, för att skapa en webblogg
RSS, för att skapa RSS-flöden från befintliga databaser

Bowstreet Portal Factory

Patrik

Bowstreet köptes av IBM dÃ¥ produkten Portal Factory var intressant. Den används för att bygga portlets utan att koda en enda rad, utan man följer ett antal guider eller sÃ¥ kallade builders. Portal Factory är en plugin som kan användas i RAD eller Eclipse. I paketet ingÃ¥r 120 builders, som i bakgrunden skapar JEE-kod. Denna kod kan självklart ändras, men det behövs ej, dÃ¥ i stort sett allt kan konfigureras. Patrik (antecknade ej efternamnet, tyvärr…) visade ett exempel genom att använda builders för Dominovyer och formulär, för att hämta och visa information frÃ¥n Dominoapplikationer i en JEE-applikation.
Man behöver inte använda Portal Server för att använda de byggda applikationerna, utan man kan generera dessa för vanliga JEE-servrar, som t.ex. Apache Tomcat, Borland AppServer och självklart Websphere Application Server.
Portal Factory är ännu inte paketerad med IBMs namn, men kan redan idag köpas. En inte allt för vågad gissning är att denna produkt kommer att integreras med RAD och förhoppningsvis paketeras med Domino!?!

Till sist

Lotusphere Comes to You är ett bra initiativ av IBM, vi är många som inte har möjlighet att åka över Atlanten för att närvara på Lotusphere, men ändå vill få information. Visst finns det mesta tillgängligt på nätet, men det kan vara svårt att skilja godbitarna från allt brus därute! Glöm inte att titta på presentationerna, speciellt den som avhandlar Bowstreet!

Gula boxningshandskar
Efter inlämnad utvärdering fick vi en nyckelring med de berömda gula boxningshandskarna! :-)

[tags]Lotus Notes, Lotus Domino, Workplace, Bowstreet, RAD, Sametime, Hannover[/tags]

]]>
Remove characters in a Java String http://johankanngard.net/2006/03/06/remove-characters-in-a-java-string/ http://johankanngard.net/2006/03/06/remove-characters-in-a-java-string/#comments Mon, 06 Mar 2006 14:59:44 +0000 http://johankanngard.net/2006/03/06/remove-characters-in-a-java-string/ […]]]> Here is a simple method (actually two) for removing multiple characters from a String:

/**
* Removes the specified characters from the supplied String.
*
* @param s the String to remove characters in.
* @param a the characters to remove from the supplied String.
* @return the String stripped from all the supplied characters.
*/
public static String removeChars(String s, char[] a) {
StringBuffer r = new StringBuffer();
for (int i = 0; i < s.length(); i ++) { if (!contains(s.charAt(i), a)) { r.append(s.charAt(i)); } } return r.toString(); } /** * Searches a char array for the specified character. * * @param c the char to find in the char array. * @param a the char array to search in. * @return true if the char is found in the char array, * false if not. */ public static boolean contains(char c, char[] a) { for (int i = 0; i < a.length; i++) { if (c == a[i]) { return true; } } return false; }


The above can be used like this to check if a String is a valid phone number:

/**
* Checks if the String is a valid phone number.
* It is valid if it only contains numbers or any of the characters
* +-() and space
*
* @param s the String to test for a valid phone number.
* @return true if the supplied String is a valid phone number,
* false if not.
*/
public boolean isValidPhoneNumber(String s) {
char[] a = {'-', '+', '(', ')', ' '};

try {
Double.parseDouble(removeChars(s, a));
return true;
} catch (NumberFormatException e) {
return false;
}
}

Apache Jakarta Commons Lang StringUtils has a variant of the removeChars method above called replaceChars that also can be useful.
[tags]Java[/tags]

]]>
http://johankanngard.net/2006/03/06/remove-characters-in-a-java-string/feed/ 1
Echo XML from a file, String or InputStream in Java with SAX http://johankanngard.net/2006/02/13/echo-xml-from-a-file-string-or-inputstream-in-java-with-sax/ Mon, 13 Feb 2006 13:51:06 +0000 http://johankanngard.net/2006/02/13/echo-xml-from-a-file-string-or-inputstream-in-java-with-sax/ […]]]> Here is an example how to use the XMLEchoer class, that I have refurbished from Sun’s tutorial Echoing an XML File with the SAX Parser. It is of limited use, but can be a good start learning SAX.

import java.io.PrintWriter;
import lotus.domino.AgentBase;
import net.kanngard.xml.XMLEchoer;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try {
String xml = "Hello World";
PrintWriter writer = getAgentOutput();
writer.println("Content-type: text/xml");
XMLEchoer echoer = new XMLEchoer(writer);
echoer.start(xml);
} catch(Exception e) {
e.printStackTrace();
}
}
}

To get it working, you need a SAX implementation, like Apache Xerces 2. Just drop the JAR files from Xerces 2 into the jvm/lib/ext directory in your Notes or Domino installation. Restart the http task if you are testing with Domino.

[tags]Java, XML, SAX[/tags]

]]>
String to InputStream http://johankanngard.net/2006/02/09/string-to-inputstream/ http://johankanngard.net/2006/02/09/string-to-inputstream/#comments Thu, 09 Feb 2006 16:15:44 +0000 http://johankanngard.net/2006/02/09/string-to-inputstream/ Arguments in many methods in the Java APIs are of the type InputStream. This is how to get an InputStream from a String, where argument to getBytes, UTF-8, is the encoding to use:

InputStream is = new ByteArrayInputStream(myString.getBytes("UTF-8"));

[tags]Java[/tags]

]]>
http://johankanngard.net/2006/02/09/string-to-inputstream/feed/ 15
Java versions in Lotus Domino and Notes http://johankanngard.net/2006/02/09/java-versions-in-lotus-domino-and-notes/ http://johankanngard.net/2006/02/09/java-versions-in-lotus-domino-and-notes/#comments Thu, 09 Feb 2006 14:31:50 +0000 http://johankanngard.net/2006/02/09/java-versions-in-lotus-domino-and-notes/
1.0 to 3.x:
N/A
4.5 to 4.6.7a:
JRE/JDK 1.1
5.0 to 5.0.13a:
JRE/JDK 1.1.8
6.0 to 6.5.6:
JRE/JDK 1.3.1
7.0 to 7.0.3:
JRE/JDK 1.4.2
8.0 to 8.0.1:
JRE/JDK 1.5.0

IBM also has a list of supported JDKs and JREs.

Old JDK/SDK/JRE versions can be downloaded at java.sun.com.
[tags]Java, Lotus Domino, Lotus Notes[/tags]

]]>
http://johankanngard.net/2006/02/09/java-versions-in-lotus-domino-and-notes/feed/ 5
StringUtils class in Java http://johankanngard.net/2006/01/24/stringutils-class-in-java/ http://johankanngard.net/2006/01/24/stringutils-class-in-java/#comments Tue, 24 Jan 2006 11:22:23 +0000 http://johankanngard.net/?p=58 Goodies like explode, leftback, rightback, switchcase, implode, middle, trim, unique etc. can be found in this utility class.

The Commons Lang project at Apache Jakarta also has some really great stuff.

Chad Schelfhout gave me a correction for the implode(Object[], String):String method and the new method word(String, String, int):String.

]]>
http://johankanngard.net/2006/01/24/stringutils-class-in-java/feed/ 2
Creating Domino agents with Netbeans http://johankanngard.net/2002/02/03/creating-domino-agents-with-netbeans/ Sun, 03 Feb 2002 10:07:07 +0000 http://johankanngard.net/wordpress/?p=6 […]]]> Introduction

Netbeans is an open source IDE, that is created and executed in a Java environment. It is a flexible and powerful IDE, and if you are tired of the lack of debugging capabilities for Java in the Lotus Domino Designer client, you may want to look at Netbeans.
In this short tutorial, I will try to explain how you can set up your environment, to allow you to create, debug and run your agents from Netbeans.

Before we start

To follow the tutorial, you will have to download the latest version of Netbeans, that was version 3.3 when this article was written. Please refer to the Netbeans documentation on how to install it.
I assume that you have installed Lotus Domino Designer R5 and Lotus Notes R5. If not, please buy it, or download an evaluation copy from notes.net.

You also need the Java Development Kit 1.1.8 to compile Java files in the format that Domino / Notes uses internally, AND the Java Development Kit 1.3.x to be able to start Netbeans. In Lotus Domino Rnext, the Java Virtual Machine will be upgraded to 1.3x.
There might be differences in platform specific things, like environment variables. This tutorial is aimed towards the MS Windows 2000 platform.

Configuring Agent Runner

The main subject when designing agents outside the Lotus Domino Designer, is the AgentRunner. The AgentRunner is a part of the Lotus Domino Java package, and allows external Java programs to communicate with Domino as if it were an agent. There is an AgentRunner database in the Notes data directory. This database is used to keep track of the AgentContexts we will create. Let´s head straight for the code!

  • Make sure you have a local AgentRunner.nsf database. If it does not exist, create it!
  • Create a new local database with the filename AgentRunnerTests.nsf.
  • Create a ”dummy agent” (which should be a ”Run once”-agent) in this test database, with the following code:

import lotus.domino.*;

public class AgentRunnerTest extends DebugAgentBase {
public void NotesMain() {
}
}

AgentRunnerTest.java

  • Name the agent ”AgentRunner Test”.
  • Save and run it.
  • Look at the Java Debug console in the FileTools menu. Note that it says ”AgentContext dumped to file AgentRunner.nsf for agent: AgentRunner Test AgentRunnerTests.nsf Local”
  • Open the AgentRunner.nsf database.
  • Look in the view ”AgentContext”, and you will see a document that has been created for you! Open it in edit mode. You will see something like this:
  • Make sure that ”Agents runs on” is ”Run once” for now. In the future, set this field to a value matching the real agent.
  • Save your changes

Configuring Netbeans

To let Netbeans know about the Java-classes that we are about to use, we must mount a JAR file as a Netbeans filesystem.

  • In the FileSystem browser, right click on ”FileSystem”, and select ”Mount”, ”Archive (JAR, zip)”.
  • Browse to your Lotus Notes program directory, usually c:LotusNotes, and select the file ”Notes.jar” and click OK.
  • Netbeans adds the JAR file to the FileSystem browser, and also adds it to the internal CLASSPATH.

Configuring JAVA_HOME environment variable

We also have to set up Netbeans to use the external JDK when compiling. This is because you can not run Lotus Domino agents that has been compiled with a JDK that is newer than version 1.1.8, and Netbeans uses JDK 1.2 or higher for internal compiling. There are two ways to set up Netbeans to use an external compiler. The first is to set the environment variable JAVA_HOME to the JDK 1.1.8 directory (i.e. c:jdk1.1.8) and specify which class that should be compiled with the external compiler. The second is to configure Netbeans to use a specific javac program when compiling the Java class. The first is the simplest, so I will explain that here. If you know how to set up an environment variable, please skip this section.

  • Open the ”System” item in the ”Control Panel”.
  • Go to the ”Advanced” tab.
  • Click ”Environment Variables…”
  • In the ”System variables” section, find the ”JAVA_HOME” variable. If it does not exist, click ”New…”.
  • Make sure the ”JAVA_HOME” variable value is set to the path where your JDK 1.1.8 is installed, i.e. c:jdk1.1.8 (note that there should not be any backward slash at the end).
  • Click ”OK” in all dialog boxes.
  • A reboot might be necessary in some circumstances…

One thing remains, and that is to tell Netbeans what source files to compile with the external compiler. I will come to this in a moment…

Our first agent

When all is configured, let us create an agent OUTSIDE of the Lotus Domino Designer!

  • Create a new Java main class in Netbeans using the wizard, but press finish right after naming the class to ”DominoAgentTest”
  • Import the lotus.domino package and make the agent extend DebugAgentBase
  • To run an agent from outside of Domino, we must make a call to the static main method in lotus.domino.AgentRunner, something like this:


public static void main(String args[]) {
try {
AgentRunner.main(new String[] {
"AgentRunner Test", // Agent name
"AgentRunnerTests.nsf", // Database
"local"}); // Server
} catch(Exception e) {
e.printStackTrace();
}
}

  • Write the NotesMain method as you would in a ”normal”, agent that you create in the Lotus Domino Designer, for example:


public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Database currentDb = agentContext.getCurrentDatabase();
System.out.println("Current database: " +
currentDb.getTitle());
} catch(Exception e) {
e.printStackTrace();
}
}

Full source of the first agent, with some extra code: DominoAgentTest.java

  • Save the file.
  • Show the property box of your class, by right clicking on the file in the FileSystem, and selecting ”Properties”.
  • Go to the ”Execution” tab
  • At the ”Compiler” option, select ”External Compilation”. By default, this option uses the JAVA_HOME environment variable explained above.
  • Compile the file by choosing ”Compile” in the ”Build” menu.
  • If the compilation went alright, you can now try to run it! Choose ”Execute” in the ”Build” menu.
  • The ”Output window” should now show some printed text from your agent, that has retrieved information from the Notes environment!

Useful links

]]>