Thursday, May 23, 2013

When Amazon SQS throws Exception..


When exception occurs when try to execute some data from AWS SQS we can rollback the changes/ do any other stuff like this

1. Write a call extending SimpleMessageListenerContainer

public class BoundryMessageListenerContainer extends SimpleMessageListenerContainer {
protected void rollbackOnExceptionIfNecessary(Session session, Throwable ex) throws JMSException {
try {
if (session != null & ex.getMessage() != null) {

JmsUtils.rollbackIfNecessary(session);

String message = ex.getLocalizedMessage();

if (message != null & message.length() > 0) {
// DO WHAT EVER YOU NEED TO DO 
}
}
} catch (IllegalStateException ex2) {
} catch (JMSException ex2) {
} catch (RuntimeException ex2) {
} catch (Error err) {
}
}
}

2. Add this to spring configuration

<bean id="container"
class="...........BoundryMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="messageListener" ref="listener" />
<property name="destination" ref="boundryQueue" />
</bean>

Number of messages in AWS SQS



1. Spring configuration

<bean id="amazonSQSClient" class="com.amazonaws.services.sqs.AmazonSQSClient">
<constructor-arg>
<bean class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg value="${amazon.access.key}" />
<constructor-arg value="${amazon.access.secret}" />
</bean>
</constructor-arg>
</bean>

2. Write your java code as


@Autowired
AmazonSQSClient amazonSQSClient;

..


public int getNoOfMessagesInQueue() {
AmazonSQS sqs = amazonSQSClient;
sqs.setEndpoint(endPoint);
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(sqsUrl);
Collection<String> attributeNames = new ArrayList<String>();
attributeNames.add("All");
getQueueAttributesRequest.setAttributeNames(attributeNames);
GetQueueAttributesResult queueAttributes = sqs.getQueueAttributes(getQueueAttributesRequest);
return Integer.parseInt(queueAttributes.getAttributes().get("ApproximateNumberOfMessages"));
}

Monday, May 6, 2013

Write to separate Log files using Logback

There may be many instance you may have to write your logs to separate log files. Here are the easy steps to do that


  • Write a new logger in the existing log configuration file
<!-- Plain Text Rolling Appender for Custom logger file -->
    <appender name="SEPERATE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <Append>true</Append>
        <File>seperate.log</File>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>seperate.log.%d{yyyy-MM-dd}</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>
    
    <!-- additivity=false ensures seperate ata only goes to the seperate log -->
    <logger name="seperate" level="DEBUG" additivity="false">
        <appender-ref ref="SEPERATE_FILE"/>
    </logger>

  • Add the new logger where every you need in the java class as 
private static final Logger log = LoggerFactory.getLogger("seperate");
  • Starts logging as log.info..., log.debug..
  • Cool ha

Tuesday, April 30, 2013

Backup/ Restore AWS MySQL RDS

You can back up and restore your AWS MySQL RDS in simple few steps


  1. MySQL should be in the class path
  2. mysqldump -h boundydb.xxxxxxxxxxx.ap-southeast-2.rds.amazonaws.com -u root -p boundydb > dumpdb.sql
  3. mysql -u root -p boundydb < dumpdb.sql


Monday, April 29, 2013

Quartz with Spring 3.2


We can integrated popular scheduler Quarts with Spring 3.2 with Few Steps

1. Write your Java class targating to schedule

@Component
public class BoundryUnlimitedSchedule {
...
public void createReports() {
...............
.......
}
}

2. Configure the spring configuration file 
2.1 Add the scheduler class
       <!-- Quartz Scheduler Configurations -->
  <bean id="boundryUnlimitedSchedule"
    class="com.................BoundryUnlimitedSchedule" />
 
2.2. Add the defined schduler with Quartz
<bean id="methodJobDetailBean"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
p:concurrent="false" p:targetObject-ref="boundryUnlimitedSchedule"
p:targetMethod="createReports" />

2.3 Create the schedule
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean" 
p:jobDetail-ref="methodJobDetailBean" 
p:startDelay="10000" 
p:cronExpression="0 0 8 ? * * *" />

3. More on cron expressions
        seconds | minutes  | hours |  daysOfMonth | months | daysOfWeek | years
 0            0           0          1                       *                ?           *          - 00:00:00 on every month on day 1
 0       10    23 L *          ?           *          - at 11:10 PM on the Last Day of the Month
 0        0     0         1W * ?           *  - first working day of each month at 00:00:00
 0             0          11         ?                       *               3           *          - every 3nd day of the week at 11:00 run this
 0            10          10         ?                       *              *           *          - every day at 10:10 run this

Change Timezone of Amazon EC2 Instance (Linux)



1.logging to EC2 instance remotely

2. Check the time of the ec2 instance date by > date

3. Time zone can be check as 
>cat /etc/sysconfig/clock
ZONE="UTC"
UTC=true

4.Change the time
cp /etc/localtime /etc/localtime.backup
ln -sf /usr/share/zoneinfo/Australia/Sydney /etc/localtime

5.Make the change permanent by adding the following line to the "/etc/sysconfig/clock" file: ZONE="Australia/Sydney"

After this this will show the correct Sydney time.
If you do not do item 5, the system time will reverting back when the EC2 instance restarted

Unit Tests with IN-Memory Database


HSQLDB can be to build framework as a in memory database for unit testing
What to be done
Add following to properties file and this should be loaded to Spring config

# Database properties for library services

datasource.driver.class.name = org.hsqldb.jdbcDriver
datasource.url = jdbc:hsqldb:mem:unittest
datasource.user.name = sa
datasource.user.password = test
hdb.dialect = org.hibernate.dialect.HSQLDialect
hdb.show_sql = true
hdb.hbm2ddl.auto = update

Add following line to Spring configuration

<jdbc:embedded-database id="embedded" type="HSQL" />
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:schema.sql" />
    <jdbc:script location="classpath:data.sql" />
</jdbc:initialize-database>

Add necessary SQL files

schema.sql - SQL to create the tables and its relationships data.sql - Basic data 

Write a JUnit Test class pointing to new Spring config

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:dispatcher-servlet.xml" })
public class BoundryTestClass {
..

}