2013/12/26

Windows XP Update Agent Takes Over The Machine

Microsoft has known issue in Auto Update Agent when wuauclt.exe takes 100% of CPU. It can cause that notification icon will not be shown. Here is solutiuon which works for me. Open Console and enter these commmands one by one:
net stop bits 
net stop wuauserv 
regsvr32 /u wuaueng.dll /s
del /f /s /q %windir%\SoftwareDistribution\*.*
del /f /s /q %windir%\windowsupdate.log
regsvr32 wuaueng.dll /s
net start bits
net start wuauserv
wuauclt.exe /resetauthorization /detectnow
After these steps leave computer running for one hour. Notification icon should appear. ;)
▼ Click here to say thanks ▼

2013/10/02

Generic entity converter in JSF 2 and EE 6

In this post I would like to show you how you can create universal entity converter for most of your entities. Steps to do:

  1. Create EntityConverter class which implements javax.faces.convert.Converter interface
  2. Override getAsObject() and getAsString() methods
How this converter works:
  • If you need to convert entity to String, converter will create it from class canonical name and from value of id field. This field is annotated by @Id in your entity class. 
  • In case of other direction (convert to Object), it will split created string to class name and id value and try to load object from persistence storage.
Here is example of this converter:



import java.lang.reflect.Field;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Id;

@Named
public class EntityConverter implements Converter {

 @Inject
 private EntityManager em;

 public Object getAsObject(FacesContext fc, UIComponent component, String string) {
  try {
   String[] split = string.split(":");
   return em.find(Class.forName(split[0]), Long.valueOf(split[1]));
  } catch (NumberFormatException | ClassNotFoundException e) {
   return null;
  }
 }

 public String getAsString(FacesContext fc, UIComponent component, Object object) {
  try {
   Class<? extends Object> clazz = object.getClass();
   for (Field f : clazz.getDeclaredFields()) {
    if (f.isAnnotationPresent(Id.class)) {
     f.setAccessible(true);
     Long id = (Long) f.get(object);
     return clazz.getCanonicalName() + ":" + id.toString();
    }
   }
  } catch (IllegalArgumentException | IllegalAccessException e) {
  }
  return null;
 }
}
And how to uset it? Not so big issue. In this example we want to show all user roles and user can choose from them:
<h:selectmanycheckbox converter="#{entityConverter}" value="#{bean.roles}">
  <f:selectitems itemlabel="#{role.rolename]}" itemvalue="#{role}" 
    value="#{bean.allRoles}" var="role">
  </f:selectitems>
</h:selectmanycheckbox>
If you have different Id types in different classes you can use converter like this. It will call valueOf method on your Id field type class. For example you have field userId which is Integer type, it will call Integer.valueOf(valueFromPage). This way you can load entity from entityManager because you have type of your entity and id of this entity with correct type.

@Named
public class EntityConverter implements Converter {

 @Inject
 private EntityManager em;

 @Inject
 Logger log;

 public Object getAsObject(FacesContext fc, UIComponent component,
   String string) {
  try {
   String[] split = string.split(":");
   Class clazz = Class.forName(split[0]);
   for (Field f : clazz.getDeclaredFields()) {
    if (f.isAnnotationPresent(Id.class)) {
     Method valueOfMethod = f.getType().getMethod("valueOf",
       String.class);
     return em.find(clazz, valueOfMethod.invoke(null, split[1]));
    }
   }
  } catch (ClassNotFoundException | NoSuchMethodException
    | SecurityException | IllegalAccessException
    | IllegalArgumentException | InvocationTargetException e) {
   log.warn("Cannot convert", e);
  }
  return null;
 }

 public String getAsString(FacesContext fc, UIComponent component,
   Object object) {
  try {
   Class clazz = object.getClass();
   for (Field f : clazz.getDeclaredFields()) {
    if (f.isAnnotationPresent(Id.class)) {
     f.setAccessible(true);
     return clazz.getCanonicalName() + ":" + f.get(object);
    }
   }
  } catch (IllegalArgumentException | IllegalAccessException e) {
   log.warn("Cannot convert", e);
  }
  return null;
 }
▼ Click here to say thanks ▼

2013/09/17

Https SoapUI mock service standalone

This post will try to show you how you can create secure SOAP service. We need to have few things before start:

  1. SoapUI - Download
  2. Your certificate - How to create it
  3. WSDL - Simple WSDL example
Start your SoapUI and create new soapUI project lik this:


Click OK to all questions. Your workspace now contains 'test-project' soapUI project under which you can find 'exampleSOAP' interface and 'exampleSOAP MockService'.


Start mock service by righ-click on 'exampleSOAP MockService' and select 'Start minimized'. If you have clean workspace without any changes in Preferences in SoapUI, mock service should listen on:

 http://COMPUTER_NAME:8088/mockexampleSOAP

You can also open WSDL file in you browser by following URL:

 http://COMPUTER_NAME:8088/mockexampleSOAP?WSDL

Next we can test your mock service by some request. Open 'Request1' under 'exampleSOAP/NewOperation':


You can see message '-no endpoint set-' or something like 'http://www.example.org/' in list box above request body. We need to add URL of our mock service to this list. Right-click on 'exampleSOAP MockService' and select 'Add Endpoint to Interface'.


Select new URL of our mock service in list box in request1 window.


Here is output:


We have running mock service and we can test it by SoapUI now. Save our project and open Preferences (Ctrl+Alt+P). Here we need to configure SSL for our mock service:


SSL port is different from port of your mock service (SSL = 18088, Service = 8088). Save preferences (File > Save preferences) and restart whole SoapUI. It has some issue with loading of certificates if you do not restart.

Start mock service againt.

Change endpoint protocol from https to http in URL and port from 8088 to 18088. Test you mock service. Is it working?

If you need to start you mock service without GUI, you can do it. Go to bin directory and try follow command:

mockservicerunner.bat -m "exampleSOAP MockService" test-project-soapui-project.xml

Argument -m contains name of the MockService and xml file is your project file. More info about arguments can find here.
▼ Click here to say thanks ▼

2013/09/05

Selenium with Arquillian as Maven project

Today we will try to test google.com page by Selenium. You can see structure of environment on following picture:

Selenium server installation

We will start by Selenium server which is connected to browser. In my example is used Internet Explorer. 
Download Selenium server from Selenium. It will be only simple jar like selenium-server-standalone-2.35.0.jar. Next we need WebDriver driver for IE. It is under "The Internet Explorer Driver Server" on the same page. You will download IEDriverServer_Win32_2.35.1.zip file, which contains IEDriverServer.exe.

Copy both files into one directory and create starting script, for example start.bat:

SET JAVA_HOME="c:\progra~2\Java\jdk1.7.0_17"
SET PATH=%JAVA_HOME%\bin;%PATH%
java -jar selenium-server-standalone-2.35.0.jar -Dwebdriver.ie.driver=IEDriverServer.exe -port 14444

Start server by created script. Result can be something like:


You can see line with Selenium server URL in console:
INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:14444/wd/hub
We will use it later. Server side is ready.

Create Maven project

Now we need some test. Create directory structure. Maven can help you:
mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart
 -DarchetypeGroupId=org.apache.maven.archetypes 
 -DgroupId=com.mil -DartifactId=selenium-test -Dversion=1.0.0


Create class GooglePage.java under src/test/java/com.mil.selenium.page. This class represents "Page Object" pattern so it models page (Google.com) to object.


package com.mil.selenium.page;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class GooglePage {

 @FindBy(name = "q")
 private WebElement search;

 public void search(String query) {
  search.sendKeys(query);
  search.sendKeys(Keys.RETURN);
 }
}
Next class is TestNG test which will call Page Object class.
package com.mil.selenium.test;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.testng.Arquillian;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

import com.mil.selenium.page.GooglePage;

public class GoogleTest extends Arquillian {
 @Page
 GooglePage page;

 @Drone
 private WebDriver driver;

 @Test
 public void testSearch() {
  try {
   driver.manage().timeouts()
     .setScriptTimeout(Integer.valueOf(10), TimeUnit.SECONDS);
   driver.manage().timeouts()
     .implicitlyWait(Integer.valueOf(10), TimeUnit.SECONDS);
   driver.manage().timeouts()
     .pageLoadTimeout(Integer.valueOf(10), TimeUnit.SECONDS);

   driver.get("http://google.com");

   page.search("test query");

   List resultOfSearch = driver.findElements(By
     .cssSelector("li[class='g']"));
   Assert.assertTrue(resultOfSearch.size() > 0);
  } catch (Exception e) {

  }
 }

 @AfterClass
 public void afterClass() {
  driver.quit();
 }
}

Check testSearch() method. We open Google page, enter some query and check if there is some result. Simple.

If you want to close Internet Explorer browser after test, you need to call driver.quit(). See afterClass() method.

This test class cannot be started without Arquillian configuration. The following file is located in:
src\test\resources\arquillian.xml

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

 <!-- Uncomment to have test archives exported to the file system for inspection -->
 <!-- <engine> -->
 <!-- <property name="deploymentExportPath">target/</property> -->
 <!-- </engine> -->

 <!-- Force the use of the Servlet 3.0 protocol with all containers, as it 
  is the most mature -->
 <defaultProtocol type="Servlet 3.0" />

 <!-- Example configuration for a remote JBoss AS 7 instance -->
 <container qualifier="jboss" default="true">
  <!-- If you want to use the JBOSS_HOME environment variable, just delete 
   the jbossHome property -->
  <!-- configuration>
   <property name="jbossHome">PATH_TO_JBOSS</property>
  </configuration-->
 </container>
 
 

 <extension qualifier="webdriver">
  <property name="browserCapabilities">internetExplorer</property>
  <property name="javascriptEnabled">true</property>
  <property name="remoteReusable">true</property>
  <property name="remoteAddress">http://localhost:14444/wd/hub</property>
 </extension>

 <extension qualifier="graphene">
  <property name="waitAjax">5</property>
  <property name="waitGui">5</property>
  <property name="waitModel">10</property>
 </extension>

 <!-- this is because of the dependency on testng-listener containing graphene 
  and drone, which automatically starts selenium server -->
 <extension qualifier="selenium-server">
  <property name="skip">true</property>
 </extension>

</arquillian>

You do not need to change anything in this file. Only remoteAddress if you have Selenium server on different computer (mentioned previously).

Test run

Now you can test it. Try it by:
   mvn clean test

Your test will conect to configured Selenium server which will open Internet Explorer browser for your test.
Any issues? Ask please.

Maven project to download: selenium-test.zip
▼ Click here to say thanks ▼

2013/09/04

OSGi example in Eclipse 4.3 for JBoss 7

Do you have any experiences with OSGi? Do you know how to create OSGi bundle in Eclipse? Do you know how to start JBoss AS with OSGi support? You will know now ;)

Eclipse configuration

We need to configure Eclipse first. In my case it is Eclipse 4.3. You need to configure OSGi Framework under Preferences > Plug-in Development > Target Platform. Currently all plug-ins are included and it can cause many exceptions. So select (Active) platform, click Edit.


Click Content tab and select only these plug-ins:
  • org.eclipse.osgi
  • org.eclipse.equinox.console
  • org.apache.felix.gogo.runtime
  • org.apache.felix.gogo.shell

Creating bundle

Now we need to create our bundle (plug-in) under New > Plug-in Project like this:


Choose "Hello OSGi Bundle" as template. Your project will contain one simple activator which writes some message to System.out in case of start and stop of bundle.

Start OSGi framework in Eclipse

It is time to test our bundle. Right click on MANIFEST.MF file and choose Run As > OSGi Framework. If everything is OK, you should see start message from activator in console.

Try ss command to list all bundles:

We can try to export your new bundle to jar file. Righ click on bundle-test project, Export > Plug-in Development > Deployable plug-ins and fragments, choose your directory where jar will be created. Done.

Deploy bundle to JBoss AS

Start your JBoss 7 like: standalone.bat -c standalone-osgi.xml and copy your bundle jar into deployment directory. Quite simple, isn't it.

If you need Maven in your project, you can do it. Here is example of pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.test</groupId>
 <artifactId>osgi-test</artifactId>
 <version>0.0.1</version>
 <packaging>bundle</packaging>

 <dependencies>
  <dependency>
   <groupId>org.osgi</groupId>
   <artifactId>org.osgi.core</artifactId>
   <version>4.1.0</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <version>2.0.1</version>
    <extensions>true</extensions>
    <configuration>
     <instructions>
      <Import-Package>
       org.osgi*
      </Import-Package>
      <Bundle-Activator>com.bundle.Activator</Bundle-Activator>
      <Bundle-SymbolicName>${project.groupId}.${project.artifactId};singleton:=true</Bundle-SymbolicName>
      <Bundle-RequiredExecutionEnvironment>JavaSE-1.7</Bundle-RequiredExecutionEnvironment>
     </instructions>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>
One note to Maven, you need to remove MANIFEST.MF file and change directory structure ;).

Hopefully it will help you to begin with OSGi in Eclipse. In case of any question ask please.
▼ Click here to say thanks ▼

2013/08/14

DIGITAL CERTIFICATES

What is digital certificate

  • An electronic document which uses a digital signature to bind together a public key with an identity information such as the name of a person or an organization, their address, and so forth
  • The certificate can be used to verify that a public key belongs to an individual

Contents of a typical digital certificate

  • Serial Number: Used to uniquely identify the certificate.
  • Subject: The person, or entity identified.
  • Signature Algorithm: The algorithm used to create the signature.
  • Issuer: The entity that verified the information and issued the certificate.
  • Valid-From: The date the certificate is first valid from.
  • Valid-To: The expiration date.
  • Key-Usage: Purpose of the public key (e.g. encipherment, signature, certificate signing...).
  • Public Key: The public key to encrypt a message to the named subject or to verify a signature from the named subject.
  • Thumbprint Algorithm: The algorithm used to hash the certificate.
  • Thumbprint: The hash itself to ensure that the certificate has not been tampered with

Public and private key - Asynchronous encryption

  • Use of these keys allows protection of the authenticity of a message by creating a digital signature of a message using the private key, which can be verified using the public key. 
  • It also allows protection of the confidentiality and integrity of a message, by public key encryption, encrypting the message using the public key, which can only be decrypted using the private key.

Asymmetric key encryption

Source: http://cxf.apache.org

Protection of the authenticity

Source: http://cxf.apache.org

SSL

  • the most common use of digital certificate
  • allows to communicate over secure connection
  • it's layer between transport (TCP/IP) and presentation (HTTP) layer
  • data is encrypted and then decrypted
SSL addresses the following security considerations:
  1. Authentication – server will present his certificate, it verify that server (site) is who and what it claims to be. Server may request clients certificate too.
  2. Confidentiality – data can be read by third party but it cannot be deciphered
  3. Integrity – SSL helps guarantee that data will not be modified

SSL sub protocols

Source: http://beefchunk.com

Establishing connection

Source: http://beefchunk.com

SSL, PCT, TLS and WTLS (not SSH)

  • SSL v2.0 Released by Netscape Communications in 1994. The main goal of this protocol was to provide security for transactions over the World Wide Web. Unfortunately, very quickly a number of security weaknesses were found in this initial version of the SSL protocol, thus making it less reliable for commercial use:
    • weak MAC construction, possibility of forcing parties to use weaker encryption, no protection for handshakes, possibility of an attacker performing truncation attacks
  • PCT v1.0 Developed in 1995 by Microsoft. Privacy Communication Technology (PCT) v1.0 addressed some weaknesses of SSL v2.0, and was aimed to replace SSL.
  • SSL v3.0 Released in 1996 by Netscape Communications. SSL v3.0 solved most of the SSL v2.0 problems, and incorporated many of the features of PCT. Pretty quickly become the most popular protocol for securing communication over WWW.
  • TLS v1.0 (also known as SSL v3.1) Published by IETF in 1999 (RFC 2246). This protocol is based on SSL v3.0 and PCT and harmonizes both Netscape's and Microsoft's approaches. It is important to note that although TLS is based on SSL, it is not a 100% backward compatible with its predecessor. IETF did some security improvements. The end result of these improvements is that these protocols don't fully interoperate. Fortunately enough, TLS has also got a mode to fall back to SSL v3.0.
  • WTLS "Mobile and wireless" version of the TLS protocol that uses the UDP protocol as a carrier. It is designed and optimized for the lower bandwidth and smaller processing capabilities of WAP-enabled mobile devices.  However, after the introduction of the WAP 2.0 protocol, WTLS has been replaced by a profiled version of the TLS protocol, which is much more secure -- mainly because there is no need for decryption and re-encryption of the traffic at the WAP gateway.

SSL installation

Before we can use SSL with Tomcat for example, we need to install the following:
  1. A server certificate keystore
  2. An HTTPS connector

Creating the server certificate

To create a server certificate follow these steps:
  1. Create the keystore.
  2. Export the certificate from the keystore.
  3. Sign the certificate.
  4. Import the certificate into a trust-store

Generating server certificate

keytool -genkey -alias server-alias -keyalg RSA -keypass changeit -storepass changeit -keystore keystore.jks
  • Generates the server keystore keystore.jks
  • Generates a key pair (a public key and associated private key)
  • Wraps the public key into an X.509 v3 self-signed certificate, which is stored as a single-element certificate chain

Importing the Certificate

Now that you have your Certificate you can import it into you local keystore. First of all you have to import a so called Chain Certificate or Root Certificate into your keystore. 

keytool -import -alias root -keystore keystore-file.abc -trustcacerts -file received-file.abc

After that you can proceed with importing your Certificate.

keytool -import -alias tomcat -keystore keystore-file.abc -trustcacerts -file received-file.abc

Displaying certificates

To print out the content of a keystore entry, use the following command: 

keytool -list -keystore keystore.jks

To display the contents of a certificate stored in a file, use the following command:

keytool -printcert -file server.cer

Install HTTPS connector

Add following lines into $CATALINA_HOME/conf/server.xml configuration file
<-- Define an SSL HTTP/1.1 Connector on port 8443--> 
<Connector className="org.apache.catalina.connector.http.HttpConnector" 
  port="8443" minProcessors="5" maxProcessors="75" 
  enableLookups="true" acceptCount="10" debug="0" 
  scheme="https" secure="true" clientAuth="false" 
  protocol="TLS" </Connector>

Export the certificate from keystore

keytool -export -alias server-alias -storepass changeit -file server.cer -keystore keystore.jks

Certificate Signing Request (CSR)

keytool -certreq -keyalg RSA -alias server-alias -file certreq.csr -keystore keystore.jks

References

  • http://www.securityfocus.com/infocus/1818
  • http://www.root.cz/clanky/ssl-autentizacia-s-webovym-serverom-apache/
  • http://slacksite.com/apache/certificate.php
  • http://en.wikipedia.org/wiki/Public_key_certificate
  • http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Security6.html
  • http://tomcat.apache.org/tomcat-4.1-doc/ssl-howto.html

▼ Click here to say thanks ▼

Secure SSH, CVS, SCP Without Password Prompt

  1. Suppose the domain name of your server is server, and your login name loginname.
  2. On the client, generate a public and private key.
     ssh-keygen -C loginname@server -t dsa 
    When asked for a password, simply press return. The private key is stored in
     ~/.ssh/id_dsa

    and the public key in
     ~/.ssh/id_dsa.pub
  3. Copy the public file to the server with
     scp ~/.ssh/id_dsa.pub loginname@server:~/
  4. Login on the server with
     ssh loginname@server
  5. Append the copied file to ~/.ssh/authorized_keys with
     cat ~/id_dsa.pub >>~/.ssh/authorized_keys


▼ Click here to say thanks ▼

Cannot Start Android Studio - No JVM installation found

Do you have problem to start Android Studio on Windows 7 (8) 64 and error message is something like:

   No JVM installation found. Please install a 64-bit JDK.

If yes, reason can be in Java.

In my case:
  • Windows 7 64
  • Java 1.7.0_17-b02 (32 bit)
If I try to start Android studio, following alert occure: 


Reason?

Start icon of Android Studio has link to studio64.exe file. But my Java is not 64 bit.

Solution?

Replace studio64.exe in link by studio.exe. Thats all. ;)
▼ Click here to say thanks ▼