Wednesday, 27 November 2013

Hybris Initialize output to log file

Debugging an intialise can be tricky, using the command line output. This command allows the output to be written to a file:

ant initialize > some.file

to append the output to an existing file use this command:

ant initialize >> some-existing.file


Monday, 2 September 2013

Use Code (or something more meaningful) instead of PK in Hybris HMC Editor

By default, when you create and specify an item type in the hmc.xml, the PK will be displayed as the item's identifier. This may not always be appropriate, for example when referencing a user. To use another property as the displayed identifier, i.e the email, use the following construct:

<type>
.
.
.

   <defaultreference mode="replace">
      <itemlayout>
         <attribute name="someOtherPropertyName"/>
      </itemlayout>
   </defaultreference>
</type>

Thursday, 4 July 2013

Select localized value using Flexible Search

If you need to return a localized value from a Hybris Flexible Search, use the example syntax below, placing the locale code in square brackets after the field name:

select {title[en]} from {CMSNavigationNode}

Thursday, 27 June 2013

Example Thread Runner Using the ExecutorService

Here is a simple example of how to create a thread runner using thread pools. This can be useful during testing or when trying to establish the time it takes for a number of threads to complete.

The Thread

package com.blah.thread.runner;



/**
 * This is a sample class to launch a rule.
 */
public class SomeThread implements Runnable {

String name;
public SomeThread(String name) {
this.name = name;
}

@Override
public void run() {
System.out.println(getName() + " is running");
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}

The Runner


package com.blah.thread.runner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SomeThreadRunner {
private static final int THREAD_POOL_SIZE = 5;
private static final int NO_OF_THREADS = 10;

 public static void main(String[] args) {
long start = System.nanoTime(); 
   ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
   for (int i = 0; i < NO_OF_THREADS ; i++) {
     Runnable worker = new SomeThread("Thread " + i);
     executor.execute(worker);
   }
   //Accept no more threads
   executor.shutdown();
   
   // Wait until all threads are finished
   while (!executor.isTerminated()) {}
   
   long elapsedTime = System.nanoTime() - start;
   System.out.println("Threads took " + elapsedTime / 1000000000.0 + " seconds to complete");
 }

}

Friday, 21 June 2013

JDBC DAO Unit Test using Mockito

For some, it's hard to think of unit testing a DAO without actually interacting with a database. This example illustrates a basic unit test for a dao class, that uses a Spring NamedParameterJdbcTemplate, without the need to actully query the underlying database:

package com.blah.test.dao;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.util.ReflectionTestUtils;

public class MockJdbcLookUpDAOTest {

private JdbcLookUpDAODAO dao;

@Mock
private NamedParameterJdbcTemplate namedTemplate;

private static final String SAMPLE_SQL = "SELECT * " +
"FROM SOME_TABLE " +
"WHERE ID = :id";

@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
dao = new JdbcFssCodeLookUpDAO();

//Spring utility class for use in unit and integration testing scenarios.
//Allows mocks to be used where no setters are accessible
ReflectionTestUtils.setField(dao, "namedTemplate", namedTemplate);
}

@Test
public void testGetFssCodeUpByPostcode(){

MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("id", "1");

//Mock the named template call to return a known String, 
//without the need for any db look up, as this would be an integration test
given(namedTemplate.queryForObject(eq(SAMPLE_SQL), refEq(param), eq(String.class))).willReturn("K");

//call the dao method, but trigger the above mock method call
String fssCode = dao.doLookUp(((String) param.getValue("id"));

//check the named template method was called once, with the expected query string and parameter values
verify(namedTemplate, times(1)).queryForObject(eq(FSS_CODE_BY_POSTCODE_SQL), refEq(param), eq(String.class));

//Check the dao method returns the expected value
assertEquals(fssCode, "K");

}


}

Wednesday, 5 June 2013

Extract parameter from URL String

The code below is shows how to extract a parameter from a URL string. This is useful when you need to extract a parameter value from the HTTP referrer string, which itself is a parameter of the HttpServletRequest object.

String searchTerm = null;
String urlString = "http://www.somewebaddress.co.uk/?test=blah+blah+blah&Test2=stuff";
URL url;
try {
url = new URL(urlString);
String queryString = url.getQuery();
//Check for single or multiple params
String[] params = (queryString.split("&").length > 0) ? queryString.split("&"): new String[]{queryString};
for(String param : params){
String[] paramNameValuePair = param.split("=");
if(paramNameValuePair[0].equals("test")){
searchTerm = paramNameValuePair[1];
System.out.println(searchTerm);
}
}
} catch (MalformedURLException e) {
System.out.println("Invalid URL!!");
}

Friday, 27 April 2012

Tomcat and HTTPS redirection

The following example shows how to redirect to HTTPS for a given url pattern using xml configuration.


1. Update web.xml to contain the follwing security constraints(s)



<security-constraint>
   <web-resource-collection>
      <web-resource-name>
         Secure Website Section
      </web-resource-name>
      <description>
        Security constraint for resources in the some/directory
     </description>
     <url-pattern>/some/*</url-pattern>
     <http-method>POST</http-method>
     <http-method>GET</http-method>
   </web-resource-collection>
   <user-data-constraint>
      <description>SSL required</description>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
   </user-data-constraint>
</security-constraint>

2. Add the following attribute to the HTTP connector in server.xml:

redirectPort="443"