пятница, 5 декабря 2014 г.

Debug ajax requests from local file

Often one has a task of debugging ajax requests from within a file on a local drive.

You cannot do it easily with the browser because of domain policy check, but you can turn it off for Chrome browser.

Start Chrome with the following switch:
Chrome.exe --disable-web-security
 
I could not find the way of how to do it in Firefox.

Now  you can debug ajax requests from within a local file without the need of deploying the file to webserver.

четверг, 6 ноября 2014 г.

WebSphere portal 8.5. Access user profile information in portlet jsp

If you want to output the user first name and last name in portlet jsp here how you can do it:
<c:set var="gName" value="${wp.user['givenName']}"/>
<c:if test="${gName ne null}">
<c:set var="givenName" value="${gName[0]}"/>
</c:if>
<span class="login"><c:out value="${givenName}" /> <c:out value="${wp.user['sn']}" /></span>

Portal provides the wp bean for access in theme and portlets.

среда, 22 октября 2014 г.

вторник, 30 сентября 2014 г.

Bouncy Castle and Crypto Pro. Detach signature from signed data.

In this post I will write how to:

1) detach signature that is attached to the data
2) view the content of signature.

Bouncy Castle is a good library but it is hard to find something in its documentation.

Here is the class that detaches the signature and writes the content of data to the File:

четверг, 25 сентября 2014 г.

Java zip file creation.

I had a task: get the files from database, create the zip file from them and serve the file to user.

The most tricky part of this process is to combine files into zip archive.

On my developer's computer I use windows 7  + Oracle JDK, on the test site we have Cent os and Websphere portal 7.

I have successfully wrote the code, tested it on developer's computer and deployed to test system. I have been surprised by the behavior of the code.
The code is as simple as:
 
ZipOutputStream zipStream = ...
ZipEntry zipEntry = new ZipEntry(zipEntryName);
zipStream.putNextEntry(zipEntry);
zipStream.closeEntry();
zipStream.finish();
zipStream.close();
 
My zip file contains entries made of Cyrillic symbols. But when I had got the file from test system I have found out that the filenames in zip archive have been corrupted.  On developer's computer everything worked fine.

The question is in encoding. I suggest that IBM JRE uses the system encoding for encoding the entry names in archive. Java 7 has the constructor
ZipOutputStream(OutputStream out, Charset charset) 
which accept charset for entry names encoding. But WebSphere Portal comes with java 6.

After googling I have found out the project Apache commons-compress project. It allows you to create zip files with specified zip entries encoding like the following:
zos = new ZipArchiveOutputStream(os);
zos.setEncoding("UTF-8");
zos.setFallbackToUTF8(true);
zos.setUseLanguageEncodingFlag(true);


Change the code to use commons-compress and I could produce identical results on developer's and test computers. Happy coding!

четверг, 18 сентября 2014 г.

Game Theory. An introduction.

I've had a vacation for a week and this time I have read the book "The Compleat Strategyst
Being a Primer on the Theory of Games of Strategy" by John D. Williams. You can find electronic version here

It is an introduction to the game theory and one of aims of the book was to popularize the subject. I can state that it can be understood by any who has a basic math knowledge. It also contains a lot of nice examples. It doesn't contain many theory and proves.

At least this book encourages me to do some research into how modern math programs like Maple, Mathematica have something about game theory. More is yet to come...

вторник, 9 сентября 2014 г.

вторник, 5 августа 2014 г.

Pretty print JSON with Spring REST Service

To enable pretty print functionality with your Spring MVC Controller you can use the following configuration:
<mvc:annotation-driven>
        <mvc:message-converters>
            <bean id="jacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

After this you JSON from Spring REST Service will be nicely indented.

пятница, 25 июля 2014 г.

Standalone Spring 3 JMS client to WebSphere MQ 7.0

There are a lot of blogs about creating JMS clients, but I couldn't find one simple article about connecting to WebSphere MQ 7.0 from java client.

Let's start:

1)  download the following jars from WebSphere MQ 7 installation into your project classpath:
12.08.2010  17:06            13 143 CL3Export.jar
12.08.2010  17:06            33 166 CL3Nonexport.jar
12.08.2010  17:09           356 856 com.ibm.mq.headers.jar
12.08.2010  17:09           440 087 com.ibm.mq.jar
12.08.2010  17:09         1 932 269 com.ibm.mq.jmqi.jar
12.08.2010  17:09           104 492 com.ibm.mq.pcf.jar
12.08.2010  17:09         3 266 359 com.ibm.mqjms.jar
12.08.2010  17:07            17 978 connector.jar
12.08.2010  17:06         2 011 813 dhbcore.jar
12.08.2010  17:08            22 769 fscontext.jar
12.08.2010  17:08            77 116 providerutil.jar
12.08.2010  17:06           893 748 rmm.jar

2) in your application context configure the client:

<!-- WebSphere MQ Connection Factory -->
    <bean id="mqConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
        <property name="hostName">
            <value>host</value>
        </property>
        <property name="port">
            <value>port</value>
        </property>
        <property name="queueManager">
            <value>value</value>
        </property>
        <property name="transportType">
            <value>1</value>
        </property>
    </bean>

    <bean id="jmsQueueConnectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory">
            <ref bean="mqConnectionFactory" />
        </property>
    </bean>
   
    <bean id="jmsContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsQueueConnectionFactory" />
        <property name="destinationName" value="queue_name" />
        <property name="messageListener" ref="inMessageListener" />
    </bean>

<bean id="inMessageListener" class="ru.mq.MyMessageListener" />

Now, you can receive JMS messages in a standalone application from WebSphere MQ.

вторник, 15 июля 2014 г.

Deploy EJB 3 web service to Websphere Application Server 8.5.5

One of the EJB 3.x features is that you can expose stateless EJB as web service.
If you use Rational Application Developer you  can use the following procedure to expose EJB as web service:

  1. Annotate your EJB bean with the @WebService annotation, and any other annotations required for your implementation.
  2. Create JMS or HTTP router modules for the web service as described in: Creating web service router modules. New in WebSphere Application Server v8, if you package your EJB application in a WAR module, you do not need to create router modules.
  3. Publish the application to a server.
Well, I had EJB in web module, which was packaged in EAR. Surprisingly for me EJB started but web service was not exposed, but the conditions were fulfilled. Then I deploy just WAR file and web service becomes available.


Moral: learn and practice as much as you can and double check what is written in documentation. 

вторник, 8 июля 2014 г.

Book I have read recently

is the book I have read recently. It is a good introduction to XML and related technologies. It is not a reference book, but a textbook or tutorial. 
It tells you about XML, namespaces, XML Schema, XPath, XSLT and among interesting things - WSDL and SOAP. This book is a good start to learn XML.

Among XML editors I recommend to use Altova XML Spy. You can download trial version. 
In java you can use IBM java api for XML which provides support for XML standards XSLT 2.0, XPath 2.0, and XQuery 1.0. Link to the book.

четверг, 26 июня 2014 г.

View DB2 version with SQL command

Start from DB2 9.7 developers added the "create or replace" command.
Working from SQL it is possible to get the DB2 version:

SELECT service_level, fixpack_num FROM TABLE
  (sysproc.env_get_inst_info())
  as INSTANCEINFO

пятница, 6 июня 2014 г.

WebSphere Portal 7. Export url mappings with XMLAccess

If you have to move url mappings between your prod and test WebSphere Portal environments, then you can do it like the following. If you have virtual portal then export you url mapping:

<request build="wp7002_132_01" type="export" version="7.0.0.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PortalConfig_7.0.0_2.xsd">
<portal action="locate">

<url-mapping-context action="locate" label="virtual_portal_name">
<url-mapping-context action="export" label="mapping1" />
</url-mapping-context>
</portal>
</request>





Command for export:
xmlaccess -in exportscript.xml -user wpsadmin -password wpsadmin -url http://localhost:10039/wps/config/virtual_portal_name -out script_out.xml




Use the same command for importing that file or use portal admin console to import the xml file.

четверг, 29 мая 2014 г.

Generate javascript with jsp

What if you need to dynamically  generate your javascript file on server? I mean no JSON file, but regular javascript files.

You can achieve this with jsp like so:

1) Set the header on your jsp "<%@page language="java" contentType="text/JavaScript" pageEncoding="UTF-8" isELIgnored="true"%>".

Pay attention to attribute isELIgnored. If you use jQuery or some other js library then you'd better set isELIgnored to true to prevent servlet container to interpret the constructions like ${} as EL constructs.

2) In web.xml create the record for servlet like
  <servlet>
        <servlet-name>initjs</servlet-name>
        <jsp-file>/init.jsp</jsp-file>
    </servlet>

and create servlet-mapping like this:
<servlet-mapping>
        <servlet-name>initjs</servlet-name>
        <url-pattern>/init.js</url-pattern>
    </servlet-mapping>


Deploy your application and access you jsp as if it were js file: /init.js. You will see your javascript file generated by servlet container.

четверг, 22 мая 2014 г.

Use PUMA API from within WebSphere Portal 7 and WebSphere Application Server 7

There is a moment when you need to create users from within portal or application server. PUMA API allows you to do management work with you users.

The crucial interface for working with PUMA API is PumaHome.

Portal
In portlet you will use instance of com.ibm.portal.um.portletservice.PumaHome which you get from com.ibm.portal.portlet.service.PortletServiceHome like this:

pumaHome = psh.getPortletService(com.ibm.portal.um.portletservice.PumaHome.class);


Instance of com.ibm.portal.portlet.service.PortletServiceHome you can obtain from JNDI lookup by name "portletservice/com.ibm.portal.um.portletservice.PumaHome".

In Spring one can do it like this:    <jee:jndi-lookup id="userManagement" jndi-name="portletservice/com.ibm.portal.um.portletservice.PumaHome" resource-ref="true"></jee:jndi-lookup>

Application Server
If you want to manage users from WebSphere Application Server, then you should use instance of com.ibm.portal.um.PumaHome which you can get from JNDI lookup by name "portal:service/usermanagement/Puma".

вторник, 6 мая 2014 г.

WebSphere Application Server 7\Websphere Portal Server 7. Download files containing non-ASCII characters (Cyrillic example).

In portlet applications there is often a need to download files.
Nowadays people want to exchange files named in languages other then english.
In this post I want to describe how to download files, which contain russian characters in their names.

As you know in portlet environment one need to use ResourceResponse class to output any content to the client.

Before you output the content to the client you need to set proper http headers on response.
For file downloading you have to set header Content-disposition: attachment; filename="your file name".

HTTP specification RFC2616 prohibits the use of non-ASCII symbols in HTTP headers, but that doesn't mean you can violate this rule.

RFC2231 provides the mechanism to specify the character set before the attribute, like this filename*=utf-8''uri_encoded_filename.

If you implement this solution you might found out that sometimes Firefox allows you to save the file with the given filename and other times Firefox will allow you to save the file with blank filename.

If you look at the response in sniffer like wireshark you can find out that your header Content-disposition: attachment; filename="your file name" had been magically transferred to Content-disposition: attachment; filename=""some_junk. That's why Firefox asks you save file with a blank name.

I had find out the following workaround: prepend the "your file name" with exclamation mark, so this is the result:
Content-disposition:attachment;  filename="!" + fileName+ "\"; filename*=utf-8''" + encodedFilename

After this modification the server no longer breaks your intentions and doesn't modify your header to Content-disposition: attachment; filename=""some_junk.

This behavior I found out on WAS 7.0.0.21.

четверг, 30 января 2014 г.

Deploy artifacts from Ivy to Artifactory

After some time struggling with deploying jar files to Apache Archiva I decided to throw it out and replace with Artifactory oss version.
The installation of Artifactory is simple - just drop the war file into Tomcat webapp.

What is important for me is that Artifactory supports deployment of artifacts with Ivy.

Use IBM JRE 7 with Tomcat 7 on Windows 7

If you have running Apache Tomcat on Windows you'll most likely run it on Oracle JVM.
What if you need to run Tomcat on IBM JRE?
You can use Apache Service Manager application to change the settings of JRE.
Open Apache Service Manager, goto Java tab.
There you see "Java Virtual Machine" field. My current value for Oracle JRE is  "C:\jre6\bin\client\jvm.dll".
Change it to file jre\bin\j9vm\jvm.dll.
Press apply.
Start Tomcat.
In your server status you can check that Tomcat is running on IBM JRE.

вторник, 28 января 2014 г.

WebSphere Portal. Run XmlAccess on remote hosts.

If you want to automate the configuration and deployment task on WebSphere Portal, eventually, you will use XmlAccess.

IBM provides ant task called XmlAccess. My goal is to achieve the invokation of configuration tasks on remote machine from my machine. I use Windows 7 and ant 1.8.4 . Remote installations of WebSphere Portal use Linux.

четверг, 16 января 2014 г.

Learning jQuery Deferreds

Started to learn Learning jQuery Deferreds.

The aim of the book is to give the high level overview of the deferreds and their implementation in jQuery particularly.
Here are the benefits of this book:
1) Introduction to promises and deferreds (through nice informal analogies). No special skills are necessary.
2) A lot of practical ready recipes. You can apply them immediately.
3) Exercises and answers.
4) The size of the book is rather small. You can read it fast.

After reading this book you will have another tool in your belt. Deffereds  are not the silver bullet, but sometimes is will allow you to write maintainable javascript code.

Some examples on deferreds application can be found on http://learn.jquery.com/code-organization/deferreds/examples/.

Update 08.07.2014: jQuery contains useful method $.when. Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. In practice you can pass it multiple deffereds and the method will resolve as soon as all the Deferreds resolve, or reject as soon as one of the Deferreds is rejected.

So, if you pass some ajax requests and want to wait when ALL of them will be finished with success or failed you can't use $.when.

I have find out the following solution to this in the net:

$(function(){
 $.whenAll = function( firstParam ) {
     var args = arguments,
         sliceDeferred = [].slice,
         i = 0,
         length = args.length,
         count = length,
         rejected,
         deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise )
             ? firstParam
             : jQuery.Deferred();

     function resolveFunc( i, reject ) {
         return function( value ) {
             rejected = true;
             args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
             if ( !( --count ) ) {
                 // Strange bug in FF4:
                 // Values changed onto the arguments object sometimes end up as undefined values
                 // outside the $.when method. Cloning the object into a fresh array solves the issue
                 var fn = rejected ? deferred.rejectWith : deferred.resolveWith;
                 fn.call(deferred, deferred, sliceDeferred.call( args, 0 ));
             }
         };
     }

     if ( length > 1 ) {
         for( ; i < length; i++ ) {
             if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
                 args[ i ].promise().then( resolveFunc(i), resolveFunc(i, true) );
             } else {
                 --count;
             }
         }
         if ( !count ) {
             deferred.resolveWith( deferred, args );
         }
     } else if ( deferred !== firstParam ) {
         deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
     }
     return deferred.promise();
 };
});

This function allows you to pass multiple deffereds and wait until all of them will be resolved or rejected.

среда, 8 января 2014 г.

Thoughts about AspectJ in Action: Enterprise AOP with Spring Applications

Have finished reading book AspectJ in Action.
This is a rather lengthy book, but it covers AOP in depth. First, AOP theory and AspectJ as a reference implementation. Second, Spring AOP and the use of AspectJ and Spring altogether.

The author writes that AOP is not the silver bullet. As always choose the right tool for the right job.

I would also recommend read Spring documentation on AOP together with this book. Also, the book contains the path to gradually adoption of AOP in your projects.