Archive for the ‘web’ Category

Generate random UUID token that starts with what you want

May 31, 2018

I wanted to personalize my environments by assigning them unique tokens which will be used by consumer APIs. To generate those tokens, I wrote a simple program on Java:

import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {

        while(true) {
            // Creating a random UUID (Universally unique identifier).
            UUID uuid = UUID.randomUUID();
            String randomUUIDString = uuid.toString();

            if (randomUUIDString.startsWith("c001")) {

                System.out.println("UUID token = " + randomUUIDString);
                System.out.println("UUID version       = " + uuid.version());
                System.out.println("UUID variant       = " + uuid.variant());

                break;
            }
        }
    }
}

Output:

UUID token = c001ab8b-4224-4530-bb93-0fab6ad3f83b
UUID version = 4
UUID variant = 2

Process finished with exit code 0

Now, looking at the token I can tell to which environment it belongs. And my log analyzer too 🙂

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!

Using enum in switch statement

July 15, 2008

In CRUD web application I often use search forms and search criteria. I found that using enum to keep the list of search fields helps scalability and future support of the software.

public static enum FieldList {
FIRST_NAME, LAST_NAME, ORGANIZATION, EMAIL
};

then I put search fields list into request in Struts action:

List<FieldList> list = new ArrayList<FieldList>();
for (FieldList field : FieldList.values()) {
list.add(field);
}
request.setAttribute(“contactSearchFieldList”, list);

then I parse user’s input in Struts form:

public ContactCriteria parseCriteria() throws IllegalArgumentException {
ContactCriteria criteria = new ContactCriteria();
parsedCriteria = “”;
if (!(empty(searchField.name())) && !(empty(searchTerm))) {
switch(searchField) {
case FIRST_NAME:
criteria.setFirstName(searchTerm);
case LAST_NAME:
criteria.setLastName(searchTerm);
case ORGANIZATION:
criteria.setOrg(searchTerm);
case EMAIL:
criteria.setEmail(searchTerm);
}
parsedCriteria += searchField + ” = ” + “‘” + searchTerm + “‘”;
} else
throw new IllegalArgumentException(“Please set Contact search parameters properly”);

Note that if I qualify class name for the enum like FieldList.FIRST_NAME, I’ll get “The enum constant FieldList.FIRST_NAME reference cannot be qualified in a case label.” compilation error

Weblogic + Eclipse in DEBUG mode

March 11, 2008

I spent 2 days to make the application running with Oracle 10 XE as a database. The most difficult thing was setup of Hibernate 3 with its HQL parser that hadn’t wanted to start under Weblogic 8.1. The following tricks had helped:

Copying Hibernate’s antlr-2.7.6rc1.jar to Weblogic’s libs and edit startWebLogic.cmd located in bea\user_projects\domains\mydomains. Changed the line for the PRE_CLASSPATH to read:

set PRE_CLASSPATH=%WL_HOME%\common\lib\antlr-2.7.6rc1.jar

Another workaround is configuring Hibernate by adding a line to hibernate.cfg.xml:
<property name=”hibernate.query.factory_class”>org.hibernate.hql.classic.
ClassicQueryTranslatorFactory</property>