Thursday, October 30, 2014

How to read Configuration Property File Keys : Java configuration.properties File


I needed some predefined values in my system. For that, I have declared a property file containing all these values. My configuration.properties looks like this:



1
2
3
threads=5
configurationProfile=default_profile
autostartup=true


In order to load this property file using Java, we need first to put the file under: src/main/resources. Then we use this code:


private Properties configProp=null;
...
public String getProperty(String key, String returnType) throws LoaderException {
 String result = null;
 // the returnType can only be null or STRING return type  
 if((returnType!=null)&&(!returnType.equalsIgnoreCase(STRING_RETURN_TYPE)))
 {
  logger.error("Invalid return type, should be string !! ");
  throw new LoaderException(" Invalid return type, should be string !! ", LoaderErrorEnum.RETURN_TYPE_ERROR);
 }
 try {
  loadFileInMemory();
  result = this.configProp.getProperty(key);
 } catch (Exception e) {
  logger.error("EXCEPTION WHILE GETTING PROPERTY ["+key+ "]" , e);
 }

 return result;
}


So in order to get a property by Key, we need to use :


public String getProperty(String key, String returnType) throws LoaderException {
 String result = null;
 
 if((returnType!=null)&&(!returnType.equalsIgnoreCase(STRING_RETURN_TYPE)))
 {
  logger.error("Invalid return type, should be string !! ");
  throw new LoaderException(" Invalid return type, should be string !! ", LoaderErrorEnum.RETURN_TYPE_ERROR);
 }
 try {
  loadFileInMemory();
  result = this.configProp.getProperty(key);
 } catch (Exception e) {
  logger.error("EXCEPTION WHILE GETTING PROPERTY ["+key+ "]" , e);
 }

 return result;
}


That's all for today. Don't forget to share :)

Monday, October 27, 2014

JBoss 7 WSConsume with Maven : Generate Web Service Client with WSconsume

I have an application running on JBoss EAP 6. I wants to cnsume a Web service. So I need to generate Web Service Client using maven. For that reason I need to declare this lines in my pom.xml :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<dependencies>
 <dependency>
  <groupId>org.jboss.ws.cxf</groupId>
  <artifactId>jbossws-cxf-client</artifactId>
  <version>4.1.1.Final</version>
  <scope>provided</scope>
 </dependency>

</dependencies>

<plugins>
 <plugin>
  <groupId>org.jboss.ws.plugins</groupId>
  <artifactId>maven-jaxws-tools-plugin</artifactId>
  <version>1.1.1.Final</version>
  <executions>
   <execution>
    <id>myService</id>
    <goals>
     <goal>wsconsume</goal>
    </goals>
    <configuration>
     <wsdls>
     
      <wsdl>http://localhost:8080/test_project/myService.ws?wsdl</wsdl>
      <wsdl>http://localhost:8080/test_project/mySecondService?wsdl</wsdl>
     </wsdls>
     <targetPackage>org.dcp.clients.myservice</targetPackage>
     <sourceDirectory>${project.basedir}/src/main/java
     </sourceDirectory>
     <extension>true</extension>
     <verbose>true</verbose>
     <goalPrefix>wsconsume</goalPrefix>
    </configuration>
   </execution>

   <execution>
    <id>userService</id>
    <goals>
     <goal>wsconsume</goal>
    </goals>
    <configuration>
     <wsdls>
      <wsdl>http://localhost:8080/user_project/UserService.ws?wsdl</wsdl>
     </wsdls>
     <targetPackage>org.dcp.clients.userservice</targetPackage>
     <sourceDirectory>${project.basedir}/src/main/java
     </sourceDirectory>
     <extension>true</extension>
     <verbose>true</verbose>
     <goalPrefix>wsconsume</goalPrefix>
    </configuration>
   </execution>
  </executions>
 </plugin>

 <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
   <failOnMissingWebXml>false</failOnMissingWebXml>
  </configuration>
 </plugin>

</plugins>


So next, just need to run clean install and all the classes will be generated. Some problems may accur when your web service throws some User Exceptions. This will be discussed later.




Sunday, October 26, 2014

Fixed Error assembling WAR: webxml attribute is required

Using Maven, I was building my application, but I get this error.


[ERROR] Failed to execute goal 
org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project myProject: 
Error assembling WAR: webxml attribute is required
 (or pre-existing WEB-INF/web.xml if executing in update mode)

In fact, with Servlet 3, I am no more supposed to specify my Web.xml and I can use annotations like @WebServlet, @WebFilter.

So two solutions are possible :


Solution 1 : Add web.xml path
:



<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-war-plugin</artifactId>
 <configuration>
   
          <webXml>src\main\webapps\WEB-INF\web.xml</webXml>
    
 </configuration>
</plugin>

Solution 2 : Ignore the Web.xml as you don't have it



<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-war-plugin</artifactId>
 <configuration>  
  <failOnMissingWebXml>false</failOnMissingWebXml>
 </configuration>
</plugin>



Sunday, October 19, 2014

JSefa tutorial and how to Support for Double, Short Data Type Mapping and Custom String separator

Having a Java Bean object, I wanted to create a CSV file. For that reason, I have used JSEFA which is a Java Simple exchange format API. So JSEFA allows us to convert our Java Bean to CSV file using few lines.

So first, I have created my bean  :


import org.jsefa.csv.annotation.CsvDataType;
import org.jsefa.csv.annotation.CsvField;


@CsvDataType
public class UserInfo {

 @CsvField(pos = 1)
 String userId;
 @CsvField(pos = 2)
 String userPassword;
 @CsvField(pos = 7, converterType = ShortConverter.class)
 Short bloodType;
 @CsvField(pos = 12, converterType = DoubleConverter.class)
 Double altitude;

}

Here if you don't put the Converted, you will get an error of type :

org.jsefa.IOFactoryException: Failed to create an CsvIOFactory
at org.jsefa.csv.CsvIOFactory.createFactory(CsvIOFactory.java:113)
at org.jsefa.csv.CsvIOFactory.createFactory(CsvIOFactory.java:87)
.....
Caused by: org.jsefa.common.mapping.TypeMappingException: Can not create a type mapping for field bloodType of class org.quwic.itms.dal.expression.UserInfo
at org.jsefa.rbf.annotation.RbfTypeMappingFactory.createFieldMappings(RbfTypeMappingFactory.java:181)
at org.jsefa.rbf.annotation.RbfTypeMappingFactory.createComplexTypeMappingIfAbsent(RbfTypeMappingFactory.java:129)

For that reason I have added the convertType = ShortConverter.class. The same thing for the Double type which is not supported by JSEFA.
So the ShortConverter and DoubleConverter classes should be provided. and they need to implements the JSefa Interface SimpleTypeConverter.



import org.jsefa.common.converter.SimpleTypeConverter;

public class DoubleConverter implements SimpleTypeConverter {
 
 private static final DoubleConverter INSTANCE = new DoubleConverter();
 public static DoubleConverter create() {
 return INSTANCE;
 }
 private DoubleConverter() {
 }
 @Override
 public Object fromString(String s) {
 return new Double(s);
 }
 @Override
 public String toString(Object d) {
 return d.toString();
 }

}

Once this is done, you need then to map your beans one by one and create the CSV (or XML file) in your main class:


import java.io.StringWriter;
import org.jsefa.Serializer;
import org.jsefa.csv.CsvIOFactory;
import org.jsefa.csv.config.CsvConfiguration;

public class UsersBeanToCSV {

 public void processUser(List<UserInfo> users){
  CsvConfiguration config = new CsvConfiguration();
  config.setFieldDelimiter(',');
  config.getSimpleTypeConverterProvider().registerConverterType(Double.class, DoubleConverter.class);
  config.getSimpleTypeConverterProvider().registerConverterType(Short.class, ShortConverter.class);
   
  
  Serializer serializer = CsvIOFactory.createFactory(config,MddNotification.class).createSerializer();
  StringWriter writer = new StringWriter();

  serializer.open(writer);
  for(UserInfo user:users){
   serializer.write(user);
  } 
  
  
  serializer.close(true);
 } 
} 

We use here the CsvConfiguration to register the new Converter.
By default, Jsefa uses the ';' to delimit fields, but as  I want to use ',', I declare that using the setFieldDelimiter.

I have just discovered an other issue, so I update my post. In fact, you need to pay attention when the double or Short value may be null (you will have a NullponterException)

 So if the values are optional, you may have some beans with null values.
So you need to modify the DoubleConverter:



import org.jsefa.common.converter.SimpleTypeConverter;

public class DoubleConverter implements SimpleTypeConverter {
 
  private static final DoubleConverter INSTANCE = new DoubleConverter();
  public static DoubleConverter create() {
  return INSTANCE;
  }
  private DoubleConverter() {
  }
  @Override
  public Object fromString(String s) {
   if(s!=null){
    return new Double(s);
   }else{
    return null
   }    
  }
  @Override
  public String toString(Object d) {
   if(d!= null){
    return d.toString();
   }else{
    return null;
   }
  }

}


That's all, hope it helped you :).

Tuesday, October 14, 2014

Spring Resolve Error : Element 'beans' cannot have character [children], because the type's content type is element-only.

I was working with Spring framework and get this error in the applicationcontext.xml (spring-integration-context.xml with Spring-Integration):

 Element 'beans' cannot have character [children], because the type's content type is element-only.

So something is wrong with my configuration. In fact, after reading carefully again the xml, I have found that I have added a wrong comment. So if you get this error, just check again your xml tags.

I get also this error :

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'int-mqtt:outbound-channel-adapter'.
- schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the 
document is not .

In fact the problem was that the given xsd address don't exists. By checking, I have found the right one:

http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt-4.0.xsd

Normally if you use maven you will not get this error.


Articles les plus consultés