Archive for the ‘Architecture’ Category

Ansible playbook snippets

August 18, 2017

tasks/main.yml

Task: Get AMI Ids of AWS ec2 instances:

---
- name: get EC2 facts
  action: ec2_facts
  register: the_facts

– debug: var=the_facts.ansible_facts.ansible_ec2_ami_id

Task: Get python disto in use:

- name: Find the path to the python interpreter
  command: which python
  register: pythonpath

Playbook: Create an EC2 instance

---
- name: AWS connect
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
  - name: Launch new Instance
    become: false
    ec2:
      aws_access_key: AKIAJBSRYRJL4JIWSAGQ
      aws_secret_key: 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
      instance_tags: "Name=AnsibleTest"
      group_id: sg-c8af43ae
      instance_type: t2.micro
      image: ami-10918173
      wait: true
      region: ap-southeast-2
      keypair: ai-apphost
      vpc_subnet_id: subnet-f2011596
    register: ec2

Task: display IDs of running instances:

- ec2_remote_facts:
 region: ap-southeast-2
 register: thefacts

# - debug: var=item.id
 # with_items: "{{thefacts.instances}}"
 
 - debug: var=item.0
 with_together:
 - "{{ thefacts.instances|map(attribute='id')|list }}"

Inspired by : https://github.com/bonovoxly/ansible_snippets

Calling Spring web services from jQuery

November 11, 2011

I love both frameworks because they are awesome. So here is how you can make Spring 3.0 and jQuery 1.5 work smoothly together, letting you forget about integration pain and concentrate on actual functionality.

Annotate your Spring service like:

@Controller
public class BankController extends BaseJSONController implements BankControllerIntf {
	@Autowired
	ConfigurationDaoIntf dao;
	@Override
	@SessionRequired
	@RoleRequired(UserRole.user)
	@RequestMapping("/ebank/paymentList")
	public @ResponseBody Map<String, String> getList(Session session,
			@RequestParam("type") String type,
			@RequestParam(value="report", required = false) String report,
			HttpServletResponse response) {
               // backend functionality here
......}
...}

BTW don’t forget to instruct Spring to resolve the @Controller-annotatated services in the applicationContext.xml:

<context:component-scan ....>
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
...

and include Jsonp filter to the server configuration, just next to the Hibernate Open Session In View Filter.

Then make jQuery call it:

$(document).ready(function(){
		    $.getJSON("/appcontext/ebank/paymentList?callback=?",
					{ "type": $("input[name=type]").val(),
					  "report": $("input[name=report]").val()
					},
				    function(data) {
						// UI manipulation here
						var options = $("#portfolioId");
						$.each(data, function(i, object) {
							options.append($("<option />").val(i).text(object));
						});
						$("#imageLoading").hide();
						$("#portfolioId").fadeIn();
			        });
	    });

and it will deliver the data straight to your web page. That’s it!

Spring 3 dependency management issue

September 28, 2010

In 2010, Spring 3 was released and it was a significant event for all Java devs.

An open issue in Spring 3 is dependency (jar) management. Doc says to use external framework like Maven, ivy or OSGi. Having no experience with ivy, I started digging towards the other twos. Maven is what I love and successfully use for the last 2 years.

Mentioning here OSGi was quite a surprise for me. But the more I learned about the framework, the more I liked the approach it offers. Actually publish-find-bind services model is not new (there was UDDI 10 years ago) but keeping it in line with Java 5 and EJB 3 and being supported by Eclipse, SpringSource, Glassfish, JBoss, Weblogic and Websphere makes it a powerful competitor to Maven.

Also, there’s something interesting gonna happen around web UI in the next versions of Spring. They ditched support for Struts 1 so they have to offer something instead to take care for C in MVC. Webflow seems pretty perspective but  heaps of XML config must go to make the development less painful. It longs to be replaced with annotations – and they started to move towards it with @MVC. Web UI components should be managed and reused somehow and it’s absolutely unclear how to do it with screens, namespaces, templates, .js, .css, etc.

Configuring project properties in Spring

July 6, 2009

It is useful to have all project properties in a text file and make Spring care of objects initialisation, especially if you have multiple environments (dev, stage, prod, etc). For this, I use placeholders like ${mybean.itsproperty} in spring-config.xml – just add a couple of configurers there:

< bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

< property name='location'>< value>config/common.properties< /value>< /property>

< /bean>

< bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">

< property name='location'>< value>config/env.properties< /value>< /property>

< /bean>

Then I can use placeholders like:

< bean id="coolDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

< property name="driverClassName">< value>${coolDS.driverClassName}< /value>< /property>

...

< /bean>

< bean id="config" class="com.mycompany.Config" scope="singleton">

< property name="incoming_directory">< value>${config.incoming_directory}< /value>< /property>

...

< /bean>

Note that placeholders should be in format beanName.propertyName if you want to override some environment-specific properties.

Exception interception

November 14, 2008

Sometimes you need to perform a specific action on some kind of Exception. For example, if you have multiple calls of domainRegistryService, and in case of unsuccessful registration it needs to write the reason to the database. For this task you can use Spring to create an interceptor.

This is the interceptor class. afterThrowing implements ThrowsAdvice and is called in case of Exception, afterReturning implements AfterReturningAdvice and is called in case when method is completed successfully. getOrder is needed if you have more than one interceptor

public class DomainRegistryInterceptor implements ThrowsAdvice,
		AfterReturningAdvice, Ordered {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger
			.getLogger(TransactionDescriptionInterceptor.class);

	public void afterThrowing(Method method, Object[] args,
			DomainRegistryService target, Exception ex) throws Exception {
		logger.debug("=== TransactionDescriptionInterceptor.afterThrowing ===");

		logger.debug("=== target === " + target.getClass().getName());
		logger.debug("=== method === " + method.getName());

		if (args != null && args.length > 0 && args[0] instanceof Domain
				&& ((Domain) args[0]).getTransactionId() != null)

			target.updateTransactionDescription(((Domain) args[0])
					.getTransactionId(), ex.getMessage());
		throw ex;
	}

	@Override
	public void afterReturning(Object arg0, Method method, Object[] args,
			Object target) throws Throwable {

		logger.debug("=== TransactionDescriptionInterceptor.afterReturning ===");

		logger.debug("=== target === " + target.getClass().getName());
		logger.debug("=== method === " + method.getName());

		if (target instanceof DomainRegistryService) {
			DomainRegistryService domainRegistryService = (DomainRegistryService) target;

			if (args != null && args.length > 0 && args[0] instanceof Domain
					&& ((Domain) args[0]).getTransactionId() != null)

				domainRegistryService.updateTransactionDescription(
						((Domain) args[0]).getTransactionId(),
						"Command completed successfully");
		}
	}

	@Override
	public int getOrder() {
		return 3;
	}

}

Then you have to bind this interceptor to your service (or services). Here’s a Spring configuration file:

	< !-- Service-->
	< bean id="service.domain.domainRegistryService"
		class="com.yourcompany.service.domain.impl.DomainRegistryServiceImpl">
	< /bean>

	< !-- INTERCEPTOR -->
	< bean id="domainRegistryInterceptor"
		class="com.yourcompany.spring.DomainRegistryInterceptor">
	< /bean>

	< !-- Auto-Proxy -->
	< bean id="domainRegistryProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		< property name="beanNames">
			< list>
				< idref bean="service.domain.domainRegistryService" />
			< /list>
		< /property>
		< property name="interceptorNames">
			< list>
				< idref bean="txInterceptor" />
				< idref bean="methodCallAccessInterceptor" />
				< idref bean="domainRegistryInterceptor" />
			< /list>
		< /property>
		< property name="order" value="3" />
	< /bean>

The linking is performed in the Auto-proxy part. Service is listed under beanNames property, interceptor goes to interceptorNames property, order defines the order of this proxy among other proxies in the application.

Background of Spring auto-proxy is explained here.

Functionally complete

August 15, 2008

Functionally complete system is the one that covers all necessary operations for some activity.

Functionally complete system is the only one that allows you creating scalable software and not turn support into nightmare.

You need qualitative tertiary education to design functionally complete systems.