вторник, 1 января 2013 г.

понедельник, 31 декабря 2012 г.

Netbeans 7.2.1 change user interface language

I've setup a Netbeans IDE 7.2.1 and by default it's user interface uses your system language. Sometimes it's good, but i prefer to see the IDE in English.

So, let's fix it. Open the <netbeans_install_dir>/etc/netbeans.conf and change the line netbeans_default_options. Append to the end of it "-J-Duser.language=en -J-Duser.region=US". Restart your IDE and you will see english interface.

четверг, 27 декабря 2012 г.

Make friends: Apache CXF client + WSS4J + CryptoPro

Many of you who worked with government webservices know that the information passed to the service should be signed with GOST algorithm. This leads to the use of CryptoPro library. So here is the interesting part. What I have:
  1. jdk 1.6.0.38 + JCP CryptoPro
  2. ready to use keystore
  3. wss4j 1.6.6
  4. apache cxf 2.6.1 
  5. XMLDSigRI.jar
Generate the client to webservice.
Then, configure the crypto.properties file for wss4j: org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.type=HDImageStore
org.apache.ws.security.crypto.merlin.keystore.password=1234567890
org.apache.ws.security.crypto.merlin.keystore.alias=tester
org.apache.ws.security.crypto.merlin.keystore.file=c:/cert.store

Then, configure your client:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
          http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://cxf.apache.org/jaxws 
          http://cxf.apache.org/schemas/jaxws.xsd">
 <!-- The SOAP client bean -->
  <jaxws:client id="client"
                serviceClass="ru.my.IService"
                address="http://test/IService/IdentificationService.svc">
    <jaxws:inInterceptors>
      <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
    </jaxws:inInterceptors>
     <jaxws:outInterceptors>
         <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
         <ref bean="wss4jOutConfiguration" /> 
     </jaxws:outInterceptors>
   </jaxws:client>
 <bean id="wss4jOutConfiguration" class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
  <property name="properties">
  <map>
  <entry key="action" value="Signature"/>
  <entry key="signaturePropFile" value="crypto.properties"/>
  <entry key="signatureKeyIdentifier" value="DirectReference"/>  
  <entry key="user" value="tester"/> 
  <entry key="signatureUser" value="tester"/>
  <entry key="passwordCallbackClass" value="ru.client.KeystorePasswordCallback"></entry> 
     <entry key="signatureDigestAlgorithm" value="http://www.w3.org/2001/04/xmldsig-more#gostr3411"/>
        <entry key="signatureAlgorithm" value="http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"/>       
      </map>
  </property>
</bean>
</beans>

Everything seems good, but your client won't work.
Here is the example of client:
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});

        ru.IService client = (ru.IService) context.getBean("client");

        ru.CryptoPro.JCPxml.XmlInit.init();

        if(!JCPXMLDSigInit.isInitialized()){
            JCPXMLDSigInit.init();
        }

        Result res = client.callMethod(123);


For this to work I had to patch WSS4j. Download the sources for WSS4j 1.6.6 and edit the file org.apache.ws.security.message.WSSecSignature.java. Find the init method and replace it with this code:
  private void init() {
        Provider xmlDSigProvider = new ru.CryptoPro.JCPxml.dsig.internal.dom.XMLDSigRI();
        signatureFactory = XMLSignatureFactory.getInstance("DOM", xmlDSigProvider);//XMLSignatureFactory.getInstance("DOM");
        keyInfoFactory = KeyInfoFactory.getInstance("DOM", xmlDSigProvider);
    }

       
Compile the file and add the compiled class to the wss4j jar.
After this, I could successfully run the client.

вторник, 25 декабря 2012 г.

Server side browser detection

Recently, I've been faced with the task to detect user's devices browsers and redirect users to the different sites accordingly.
So, I've  made a search and found out this script for HTTP server (http://detectmobilebrowsers.com/). This script detects many mobile browsers, even my old symbian E52 was detected.
IPad devices are not detected. It's up to you to decide weather should your users be redirected to the mobile versions of your site. So, the real problem for me is how to detect iPad mini?
Http user agent for iPad 2 and iPad mini are the same. You can check the blog here (http://www.mobilexweb.com/blog/ipad-mini-detection-for-html5-user-agent). If anybody can find the solution to this problem, please, share your knowledge.

четверг, 25 октября 2012 г.

Mixin multiple JVM languages in the enterprise

It is interesting, has anybody tried to mixin multiple languages in the enterprise java project?

Scala, Closure, jRuby or others? 
Did it really help to speedup the the development and support?

пятница, 12 октября 2012 г.

Tomcat 6. Remove version information from error pages.

When Tomcat 6 encounters error like 404 it displays the error page which also reveals Tomcat version. It is bad in production, because some people can attack vulnerabilities in software. So, to make this task difficult it is better to mimic the version information in error page.

In your CATALINA_BASE\lib directory create dirs org/apache/catalina/util. Then, create the file ServerInfo.properties with the following properties:
server.info=Apache
server.number=1.2.3.4
server.built=18 nov 2012 23:59:59
 
Restart the Tomcat. Now Tomcat error pages won't contain version information.

Question to readers

Hi folks! I need your help. Does anybody of you knows the Java User Group in Moscow? I would like to join in to exchange the experience.

I know Google has video presentations from their java related meetings. Are there any meetings like this are held in Moscow?

вторник, 2 октября 2012 г.

Важное объявление.

С целью расширения аудитории  своего блога дальнейшие записи будут вестись на английском языке.

понедельник, 1 октября 2012 г.

Spring и сервлеты. Инъектирование бинов.

Порой очень хочется, чтобы при создании сервлета автоматически инъектировались бины Spring.
Однако стоит отметить важную особенность, что жизненным циклов бинов управляет Spring, а жизненным циклом сервлета управляет контейнер сервлетов.  По этой причине автоматически инъектировать бины в сервлет не получится.



Есть альтернативное решение. Spring содержит интерфейс
org.springframework.web.HttpRequestHandler. В этом интерфейсе есть метод handleRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response). Фактически это один в один метод service сервлета. Мы портируем наш сервлет так, что класс реализует данный интерфейс. Этот класс мы объявляем в spring. Далее в web.xml мы создаём описание сервлета. При этом имя сервлета должно совпадать с именем определённого бина spring, а класс сервлета - org.springframework.web.context.support.HttpRequestHandlerServlet.

Как результат - наш сервлет содержит инъектированные бины spring.

Аналогичное решение есть и для фильтров сервлета. Только в этом случае класс называется org.springframework.web.filter.DelegatingFilterProxy.