Wednesday, January 21, 2015

Interview Questions

Details on Education and Working Experiences

  •     Education?
  •     Describe the team size of previous positions.
  •     Role on team?
  •     Describe the project management flow of previous positions.
  •     Could you describe the representative project that you had worked on?
  •         What's the achievement?
  •         What's the difficulties?
  •     Experience on communicate with end user?
  •     Interaction with end users?
  •         Product demo?
  •     Approach on problem solving?
  •     How to handle disaster, major bug deployed to production?
  •     Documentations?
  •     Scrum/Agile development experience?  Sprints, PBI, stories, ...
  •     Feature Spec -> Design spec -> Implementation Spec -> Programming...
  •     Overtime?  (I don't encourage, but must focus with good efficiency.)

Key Requirements Review

  •     Team work
  •     Communication
  •     Agile/Scrum
  •     Continues integration
  •     Analysis
  •     Problem solving
  •     Source control
  •     Debugging
  •     Unit tests
  •     QA
  •     User support
  •     Documentation
  •     System administration

Learning Abilities

  •     Ability on learning new programming language.
  •         When and how did you learn programming languages?

Development Knowledge

  •     SDLC experience?
  •         Report issues, bugs.
  •         Experiences on management system such as JIRA.
  •     Experience on unit test.
  •         Has any experience on test driven development?
  •         Test Driven development
  •         Test cases code coverage?
  •         Test automation?
  •     Code refactoring?
  •     Continue integration.
  •     QA testing knowledge?

Technical Know-hows

  •     Hardware knowledge?
  •     RAID 0, 1, 0+1, 5
  •     UDP vs TCP, which protocol is suitable for video streaming?  Why?
  •     IPv4 vs IPv6
  •     Window services or Daemon development experience?
  •     How to debug on Visual Studio Web application?  In case of developer server by VS.  In case of a web application hosted on local IIS.
  •     How to debug on client side, javascript?  (Browser tools like Firebug, Chrome developer tools.)
  •     How do you access database?  Stored Procedure vs Parameterized Query.  Your option?
  •     Tell the different between sql join and left join.
  •     How to debug SQL stored procedure?
  •     System security?
  •     Deployment process details.
  •         By GUI?
  •         By Script?
  •     Experience on version control system, e.g. Svn, Git, Csv?
  •     How to ensure a series of database operations be atomic?
  •     Experience on Linux administration, network configuration.
  •         Cron job
  •         rsync
  •     Experience on AJAX, front-end HTML?
  •     Experience on Cloud?
  •     Experience on NoSQL
  •         e.g. Memcached?
  •     Experience on public web APIs (e.g. Facebook) ?
  •     Web services, restful.  Concept on Restful web service (GET, PUT, POST, DELETE)
  •     What's the difference between static and dynamic programming language.
  •     Regular expression?
  •     Can Apache server serve multiple domain websites with single IP?  With SSL cert?

Others

    Any technical news group do you follows?

Developer's Mindset, Practices

  •     Define top 3 coding practice rules.
  •     Define top 3 team collaboration rules.
  •     What's the most important thing to get things done well? ... It's Passion.
  •     Daily logbook?
  •     Keep knowledge base?
  •     Personal technical blog?
  •     Open source development experience?
  •     How to choose from "Do it well" and "Do it fast" on time pressure?
  •         Technical debt
  •     Code review?

Personal

  •     Career plan?
  •     *** Comfortable with coding convention, guideline and collaboration practice? (e.g. code commit every day, daily scrum meeting, code review)
  •         Play different role on different story.
  •     What's the major achievement on years of development life?
  •     What's the area to be strengthen?
  •     What's the role you want to try in software development industry?
  •     How do you improve yourself?

Programming Tests

    Design a approach to solve a problem in a generic and extendable way ...
        Car service depot - The company has a system with database that takes a car's made, model, year as input.  Customer can check the wanted service.  Then the system can generate a work list for staff.  And cashier charge base on details.
            Car database
                Made
                    Details
                Model
                    Spec
                Year
            Create service list base on made and model.
                refuel_car(car)
                    fuel_diesel(car)
                    fuel_petrol(car)
                    What if we want to support gas in future?
                Cleaning
                    < 1500cc : $200
                    1500cc - 2500cc : $300
                    > 2500cc : $500
                    What if we change the charging plan in future?
                    Configuration file? or store in database?
                Save record with worksheet include worker name and charges.
            Question: What's the problem on the following implementation?  Or what improvement could be made.
                Car -> PetrolCar
                Car -> DieselCar
                Refuel_car(?) { if car is PetrolCar, fuel_petrol; if car is DieselCar, fuel_diesel;}
            Alt Question.
                Create the Refuel_car function.

System design test (Open design, no model answer)

    Online application
        create an online application with private information and file uploads, what's the approach? (on server hardware setup, web security concerns, etc.)
            Upload file handling.
            Prevent web robots - Captcha.
        Security, the basic security for an online application, e.g. loan application?
        CMS, any knowledge?
    Create a simple system including hardware, software to support a DVD lending system at home.
        Hardware
        Software
            ER diagram
        System

        Enhancements:
            Enhance data redundancy, availability
            System security


Introduction to our company and development team.

    Small SME loan.
    Office in Singapore, Philippine, and will be more.
    12 month salary.
    Development team:
        Agile/Scrum development.
        Internal loan management system
        4 developers
        Daily operation support
        System maintenance
        Feature enhancement
        New projects
        Team member will play different role for:
            Analysis
            Coding
            Testing
        Due with change requests.
        Open source learning opportunity
        Comprehensive system development and deployment.

Questions?

Tuesday, January 20, 2015

Extend Ubuntu server disk volume after resizing VM

Check current partitions:
>sudo fdisk -l

Create new partition:
>sudo fdisk /dev/sda
- primary partition
- partition number: 3
- first and last cylinder block
- partition system ID: 8e
- write to disk.

Setup the partition:
>pvcreate /dev/sda3
>vgdisplay
>vgextend [VG Name] /dev/sda3
>pvscan
>lvdisplay
>lvextend [LV Path] /dev/sda3
>resize2fs [LV Path]

DONE

http://www.rootusers.com/how-to-increase-the-size-of-a-linux-lvm-by-expanding-the-virtual-machine-disk/

ssh-copy-id with port

ssh-copy-id "user@host -p 1234"

Monday, January 19, 2015

Fixed Jenkins with upgraded postgresql server and clients

Problem:
pg_dump: server version: 9.3.5; pg_dump version: 9.1.14  pg_dump: aborting because of server version mismatch  rake aborted!  Error dumping database    Solution:  > sudo apt-get remove postgresql-client-8.3  > sudo apt-get remove postgresql-client-9.1  

Jenkins config file

config file: /etc/default/jenkins

Monday, January 12, 2015

Toolbox - Control multiple linux server by ssh - ClusterSSH

mac: brew install csshx
linux: apt-get install cssh/clusterssh

Ubuntu server manual update

sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get autoremove

Upgrade linux problem solved - could not find image

Linux upgrade problem: could not find image vmlinuz...-generic

>sudo apt-get purge linux-image-xxxxxx-generic

Ubuntu server upgrade to latest LTS

Check current version:
>uname -mrs
>lsb_release -a

*Update /etc/apt/source.list if it is necessary.

Do upgrade:
>sudo apt-get update
>sudo apt-get install update-manager-core
>sudo do-release-upgrade

Thursday, January 8, 2015

The Ultimate Guide: 5 Methods For Debugging Production Servers At Scale

Source: http://highscalability.com/blog/2015/1/7/the-ultimate-guide-5-methods-for-debugging-production-server.html




The Ultimate Guide: 5 Methods For Debugging Production Servers At Scale


This a guest post by Alex Zhitnitsky, an engineer working at Takipi, who is on a mission to help Java and Scala developers solve bugs in production and rid the world of buggy software.

How To Approach The Production Debugging Conundrum?

All sorts of wild things happen when your code leaves the safe and warm development environment. Unlike the comfort of the debugger in your favorite IDE, when errors happen on a live server - you better come prepared. No more breakpoints, step over, or step into, and you can forget about adding that quick line of code to help you understand what just happened. In production, bad things happen first and then you have to figure out what exactly went wrong. To be able to debug in this kind of environment we first need to switch our debugging mindset to plan ahead. If you’re not prepared with good practices in advance, roaming around aimlessly through the logs wouldn’t be too effective.

And that’s not all. With high scalability architectures, enter high scalability errors. In many cases we find transactions that originate on one machine or microservice and break something on another. Together with Continuous Delivery practices and constant code changes, errors find their way to production with an increasing rate. The biggest problem we’re facing here is capturing the exact state which led to the error, what were the variable values, which thread are we in, and what was this piece of code even trying to do?

Let’s take a look at 5 methods that can help us answer just that. Distributed logging, advanced jstack techniques, BTrace and other custom JVM agents:

1. Distributed Logging

For every log line we print out, we need to be able to extract the full context to understand what exactly happened there. Some data might come from the logger itself and the location the log is created in, other data needs to be extracted at the moment of the event. One caveat to avoid here is hurting your throughput. The more context you draw out, the bigger performance hit you experience. To test this in practice we ran a benchmark and discovered 7 Logback tweaks to help mitigate this risk (naming the logger by the class name is my favorite one).

What Context Should You Draw Out?

Everything! Where in the code are we, if relevant this can go down to the class we’re in, or even the specific method, which thread is this, and a self assigned transaction ID that’s unique to this request. A transaction ID is key to understanding the full context of an error, since it often travels between your nodes, processes and threads. A good practice to keep here is making sure you generate a UUID at every thread’s entry point to your app. Append the ID into each log entry, keep it for the tasks in your queue, and try to maintain this practice across your machines. We found this to be critical for making sense out of distributed or async logging. It becomes even more powerful when binded together withlog management tools, like Logstash or Loggly, where you can search and tie the knots around the transaction from end to end.

 

When Everything Else Fails - Catch ‘Em All

Uncaught exceptions are where threads go to die. And so does most of the evidence as to what actually happened there. Most of the time the framework you’re using will be able to contain this and show some error message (like YouTube’s custom message dispatching a team of highly trained monkeys to the rescue). For your own way to handle this, the last line of defense would be setting up a Global Exception Handler, like this one in Java:

public static void Thread.setDefaultUncaughtExceptionHandler(

   UncaughtExceptionHandler eh);

void uncaughtException( Thread t, Throwable e) {

   logger.error(“Uncaught error in thread “ + t.getName(), e);

}

This is similar to the things Tomcat or a framework like Akka will give you. Here are 3 ways to extract even more data when an uncaught exception inevitably happens:

  1. Thread names: A nifty little trick is to change your thread name according to the request you’re handling. For example, whenever you’re processing a certain transaction, append its ID to the thread’s name and remove it when you’re done.

  2. Thread-local storage (TLS): A way to keep thread specific data - off the Thread object. You can put there anything that would help identify what went wrong once an error happens. Things like a transaction id, time, or username. Other than this data and the thread name, there’s nothing much you can save when reaching the Uncaught Exception Handler.

  3. Mapped Diagnostic Context (MDC): Similar to the thread-local concept and coming at it from the logging angle, the MDC is part of logging frameworks like Log4j or Logback. It creates a static map at the logger level, and enables a few more advanced features other than TLS.

2. Preemptive Jstack

Most of you Java developers are probably familiar with jstack, a powerful tool that comes with the JDK. In two sentences, it basically allows you to hook into a running process and output all the threads that are currently running in it with their stack trace, frames, either Java or native, locks they’re holding and all sorts of other meta data. It can also analyze heap dumps or core dumps of processes that already don’t exist, a longstanding and super useful toolkit.

BUT… One of the issues it has is that it’s mostly used in retrospect, the bad awful thing has already happened and we’re firing up jstack to recover any clues of what might have caused it. The server isn’t responding, the throughput is dropping, database queries taking forever: A typical output would be a few threads stuck on some nasty database query. No clue of how we got there.

A nice hack that would allow getting the jstack output where it matters most would be activating it automatically when things go south. For example, say we want to set a certain throughput threshold and get jstack to run at the moment it drops:

public void startScheduleTask() {

   scheduler.scheduleAtFixedRate(new Runnable() {

       public void run() {

           checkThroughput();

       }

   }, APP_WARMUP, POLLING_CYCLE, TimeUnit.SECONDS);

}

private void checkThroughput()

{

   int throughput = adder.intValue(); //the adder is inc’d when a message is processed

   if (throughput < MIN_THROUGHPUT) {

       Thread.currentThread().setName("Throughput jstack thread: " + throughput);

       System.err.println("Minimal throughput failed: executing jstack");

       executeJstack();  // See the code on GitHub to learn how this is done

   }

   adder.reset();

}

3. Stateful Jstack

Another issue with jstack is that while it provides very rich meta data about the thread, we’re lacking the actual state that led to the error. This is where manually setting the thread name comes to our rescue again. To be able to understand the source of the error, we need more than just a stack trace. Let’s go back to the nasty database query example, by adding a line like:

Thread.currentThread().setName(Context + TID + Params + current Time, ...);

What once looked like this in jstack’s output and didn’t provide much actionable data:

pool-1-thread-1″ #17 prio=5 os_prio=31 tid=0x00007f9d620c9800 nid=0x6d03 in Object.wait() [0x000000013ebcc000]

Now looks like this:

”Queue Processing Thread, MessageID: AB5CAD, type: AnalyzeGraph, queue: ACTIVE_PROD, Transaction_ID: 5678956, Start Time: 10/8/2014 18:34″ #17 prio=5 os_prio=31 tid=0x00007f9d620c9800 nid=0x6d03 in Object.wait() [0x000000013ebcc000]

Now we have a better sense of what’s going on. You see what the thread was doing and the parameters it received, including the Transaction ID and Message ID. With these parameters the state that led us here becomes clearer. Now we know which message got us stuck, and can retrace our steps back, reproduce the error, isolate and solve it.

4. BTrace - An Open Source Tracing Tool

The next piece of the puzzle is better visibility into the state of a JVM at runtime. How can we get this kind of data about the state of our JVM without logging and code changes?

One interesting way to tackle this is by using the BTrace Java agent (You can find out more about what Java agents are and what’s the difference between them to native agents righthere. BTrace lets us extract data from a running JVM without adding logging or restarting anything. After attaching the agent, you can hook up to it using the BTrace scripting language. Through scripting, you can instrument the code and grab data that runs through it.

Let’s take a look at some code to get a feel of what the scripting language looks like:

@BTrace public class Classload {

   @OnMethod(

       Clazz=”+java.lang.ClassLoader”,

       method=”defineClass”,

       location=@Location(Kind.RETURN)

    )

    public static void defineClass(@Return class cl) {

       println(Strings.strcat(“loaded ”, Reflective.name(cl)));

       Threads.jstack();

      println(“==============================”);

   }

}

Pretty similar to Java, right? Here we’re grabbing all the ClassLoaders and their subclasses. Whenever “defineClass” returns, the script will print out that the class was loaded and run jstack for us.

BTrace is a useful tool for investigating specific issues but it’s not recommended to use it continuously in production. Since it’s a Java agent with a high level of instrumentation, the overhead could often be significant. It also requires writing specific scripts for anything you’d like to measure and has many restrictions to avoid high overhead and not mess up anything important. For example, it cannot create new objects, catch exceptions, or include loops. With all that, it’s pretty cool to be able to edit scripts during runtime without having to restart your JVM.

5. Custom JVM Agents

While pinpointing the pieces of data we need for debugging is a good practice for logging, JVM agents have much more power and less to almost no extra plumbing requirements. To extract variable values for debugging without any code changes to your server, you need an agent in place. Smart use of agents can practically go around the other methods and serve you most of the data you need for debugging in high scalability.

Like BTrace, you can write your own custom Java agent. One way this helped us was when a certain class was instantiating millions of new objects for some reason, what we did to debug this was write a simple Java agent. The agent would hook to the constructor of that object and anytime the object was allocated an instance, it would get its stack trace. Later we analyzed the results and understood where the load was coming from. This is something BTrace couldn’t help us with since it has many restrictions and can only read data, and here we needed to write to file, log and do other operations that it doesn’t support.

If you’d like to get a feel for how an agent works, here are the few lines that get the whole thing rolling:

private static void internalPremain(String agentArgs, Instrumentation inst) throws IOException {

….

   Transformer transformer = new Transformer(targetClassName);

   inst.addTransformer(transformer, true); // the true flag let’s the agent hotswap running classes

}

A transformer object is created and we register it to the instrumentation object that has the power to change classes. The transformer implementation and the agent’s full source code, are available on GitHub.

The Native Agent And Variable Data

Unlike Java agents, native agents go a step deeper: They’re written in platform dependant native C/C++ code. Java agents have access to the code Instrumentation API, while Native Agents can also access the JVM’s low-level set of APIs and capabilities (JVMTI). This includes access to JIT compilation, GC, monitoring, exceptions, breakpoints and more.

At Takipi, we’re building a next generation production debugger that’s based on a native agent. It requires no code or configuration changes and it’s optimized to run on large scale production systems. Takipi analyzes your caught exceptions, uncaught exceptions, and log errors, showing you the exact state that led there down to the variable level. After attaching the agent to your JVM, you’ll be able to see your errors as if you were there when it happened:

Conclusion

It all boils down to this, the more valuable data you have, the quicker it is to solve the problem. Today when a few extra minutes of downtime are more valuable than ever, the drive to build rather than fix bugs is stronger, and the ability to quickly deploy new code without concerns is essential to succeed: A sound production debugging strategy must be in place.

Openssl heartbleed fix

Check:
>openssl version -a

Fix
apt-get update
apt-get upgrade

DONE

Monday, January 5, 2015

Testing on 3 million requests per second

Servers: Linux Virtual Server (Red Hat's load balancer)
Network: 10-gigabit network
Http server: Nginx
Load generator: Tsung load testing tool (http://tsung.erlang-projects.org/)


Reference: http://dak1n1.com/blog/10-3-million-http-cluster

Wednesday, December 31, 2014

Enable SMTP on max OS

sudo postfix start

java send mail using ubuntu local sendmail smtp

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public static void main(String[] args) {

String to="recipient@example.com";
String from="sender@example.com";

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);

// props.put("mail.smtp.host", "localhost"); // optional

String msgBody = "Sending email using JavaMail API...";

try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, "NoReply"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to, "Mr. Recipient"));
msg.setSubject("Welcome To Java Mail API");
msg.setText(msgBody);
Transport.send(msg);
System.out.println("Email sent successfully...");

} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

}

Wednesday, December 24, 2014

Thursday, December 18, 2014

Setup Zabbix on Ubuntu for Postgresql connection

1. Install unixODBC >sudo apt-get install unixODBC
2. Install postgresql odbc driver >sudo apt-get install postgresql-odbc
3. Setup /etc/odbc.ini
[test]
Description = 192.168.8.220 test
Driver = postgresql
Servername = 192.168.8.220
Port = 5432
Database = db_name

4. Setup /etc/odbcinst.ini
[postgresql]
Description = ODBC for postgresql
Driver = /usr/lib/x86_64-linux-gnu/odbc/psqlodbca.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libodbcpsqlS.so

Test:
>isql test your_name your_password -v

In Zabbix, add database monitor:
key = db.odbc.select[some_name,test]

Postgresql usage notes

Revoke:

    REVOKE ALL ON DATABASE db_name FROM user_name;
    revoke all on all tables in schema public from zabbix;

Readonly User:

    revoke all on schema public from public;
    create role zabbix login password 'some_pass';
    grant usage on schema public to zabbix;
    grant select on public.some_table to zabbix;


When you create a new database, any role is allowed to create objects in the public schema. To remove this possibility, you may issue immediately after the database creation:

REVOKE ALL ON schema public FROM public;

Edit: after the above command, only a superuser may create new objects inside the public schema, which is not practical. Assuming a non-superuser foo_user should be granted this privilege, this should be done with:

GRANT ALL ON schema public TO foo_user;


Friday, December 12, 2014

Configure Zabbix to sent alert email

Setup the host to be monitored


Setup Media Type, in this case, use email and local "sendmail" smtp server.  Remember to use 127.0.0.1 on the SMTP server settings.  Otherwise, it may have connection problem.



Ensure the User media email is enabled.



Ensure action is enabled.




Set the trigger.





Thursday, December 11, 2014

Connects zabbix server to agent

* Remember to setup the zabbix-agent configuration to listen to the
right server IP and other settings.

log: /var/log/zabbix-agent/zabbix_agentd.log
config: /etc/zabbix/zabbix_agentd.conf

Check opened ports

netstat -anltp | grep "LISTEN"

ssh-copy-id copy id to remote machine

usage> ssh-copy-id -p 1337 your_name@remote_host

Wednesday, November 12, 2014

Monitor linux process memory or cpu resource usage

Find the process: > ps -ef | grep java

>top -p pid

interactive commands:
"f" - add/drop columns
"c" - command details
"M" - sort by memory
...

Wednesday, November 5, 2014

Tools: SAP Crystal Reports

SAP Crystal Reports

A robust production reporting tool, SAP Crystal Reports turns almost any data source into interactive, actionable information that can be accessed offline or online, from applications, portals and mobile devices.

Friday, August 29, 2014

Postgresql JDBC enum and stored procedure

Simple way to submit postgresql enum from JDBC: Use type casting.

CallableStatement cs = conn.prepareCall("{call
sp_dummy(?::enum_result)}");
cs.setString(1, jobResult.toString());
cs.execute();

Thursday, August 28, 2014

Maven simple java application

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Saturday, August 23, 2014

Work Breakdown Structure


Estimating using Work Breakdown Structure

Work Breakdown Structure (WBS) is probably how 98% of software development projects are estimated. WBS consists of someone sitting down and saying "Okay, how are we going to get this done?", then coming up with a long laundry list like this:
  1. Setting up Development, Test, and Production environments - 8 hours
  2. Creating the Login screen - 4 hours
  3. Creating the Landing Page - 2 days
  4. Developing the XYZ Page - 12 hours
  5. etc., etc., etc.
You then continue with a long laundry list of every task you can imagine, with each task having an associated estimate. At the end you add up the time for all the tasks, and you have your overall time estimate.
Or do you?

WBS accuracy

As a practical matter, most WBS estimates I've seen under-estimate the total time required by a factor of 1.25 to 2.5. That is, if someone tells me that they did a WBS estimate and came up with 100 hours, the real answer is typically 125 to 250 hours.
IFPUG data also supports this. Though I don't have the exact data with me, I do remember that their data shows that estimates created using WBS alone under-estimate project effort by an average of about 50%. The reality is that this ratio actually varies quite a bit from person to person: some developers over-estimate, some under-estimate, some are very close. The good news is that people are consistent, and if they usually under-estimate by a factor of 2.5 they tend to always estimate by a similar ratio, unless ...

Use feedback to improve WBS estimates

If these developers are made to always review their estimates I believe they will eventually get better. For instance, let's say a developer told me a project would take 100 hours, but it really took 250 hours. After the project I would sit down with the developer and say "Okay, you estimated 100 hours, but it really took 250 hours. Now, I'm not here to beat you over the head. In fact, we like you quite a bit and want you on all of our future projects. But we need to take a little time and see where this estimate was off, okay?"
You do this behind closed doors, because everybody I know feels vulnerable when they're estimating. This stuff is hard, and it's not an exact science, I know that. But if you don't go through this process people won't get better.
Getting back to the WBS estimate, let's imagine that we worked through this process and we came up with an estimate of 1,600 hours. Given our team of four developers, this equates to 400 hours per developer. At 35 hours per week this is about 11.4 weeks of development effort.

Don't forget acceptance testing

Historically speaking, the people that I've seen take the WBS effort do not include final acceptance testing in their estimates, so I'll assume that's the case here. I'll use the same ratio of development time to final acceptance testing time that I used before (a 3:1 ratio), so if development takes 11.4 weeks, acceptance testing should take an additional 3.8 weeks (and the 1,600 hour estimate needs to be increased to 2,133 hours).

WBS estimate

Therefore, WBS predicts a total development time of 2,133 hours, or 15.2 weeks.

Thursday, August 21, 2014

Jersey Maven setup Log4j2

1. In pom.xml, add:

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0.1</version>
</dependency>

2. Add log4j configuration file to path: src/main/webapp/WEB-INF/classes
(create the classes folder manually)

3. Code:

Logger logger = LogManager.getLogger();
logger.info("info!!!!!!!!!!!!!!");

Serialize Object to Json indented string with Jersey

1. pom.xml - Use Jackson
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
        </dependency>   

2. Code:

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        String rJson = "";
        try {
            rJson = mapper.writeValueAsString(request);
            System.out.println(rJson);
        } catch (JsonProcessingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

Wednesday, August 20, 2014

Tomcat 7 connection pool with JNDI datasource and postgreSQL

1. Tomcat's content.xml

<Context>    <Resource name="jdbc/postgres" auth="Container"            type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"            url="jdbc:postgresql://127.0.0.1:5432/mydb"            username="myuser" password="mypasswd" maxActive="20" maxIdle="10"  maxWait="-1"/>  </Context>

2. Web application's web.xml

<resource-ref>   <description>postgreSQL Datasource example</description>   <res-ref-name>jdbc/postgres</res-ref-name>   <res-type>javax.sql.DataSource</res-type>   <res-auth>Container</res-auth>  </resource-ref>

2. Code

    Connection conn = null;
        try {
            InitialContext cxt = new InitialContext();
            DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );
            conn = ds.getConnection();
           
                 ...

                ...   
                while(rs.next()) {
                ...
                ...

                }
                rs.close();
            }
            conn.close();
        } catch (NamingException e1) {
            e1.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        };

Maven Postgresql JDBC

1. Add dependency in pom.xml. e.g.
http://mvnrepository.com/artifact/org.postgresql/postgresql/9.3-1100-jdbc41
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
</dependency>

2. Coding:

Connection conn = null;
try
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://THE_HOST/THE_DATABASE";
conn = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT id, subject, permalink
FROM blogs ORDER BY id");
while ( rs.next() )
{
Blog blog = new Blog();
blog.id = rs.getInt ("id");
blog.subject = rs.getString ("subject");
blog.permalink = rs.getString ("permalink");
listOfBlogs.add(blog);
}
rs.close();
st.close();

}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}

Monday, August 18, 2014

System server requirements

System hardware requirements
  CPU File I/O Database I/O RAM
Management Web App
High Low High Mid
Scoring Web App
Low Low to Mid Mid Mid
Workers
High High  Mid High
PostgreSQL Mid High N/A High
DWH N/A N/A High N/A
ETL High Low to Mid Mid High
CRM Mid Low Mid Mid
Analytics Engine High Low Mid High















System Server Requirements
  File Server Database Server Web Server Processing Server
Functionalities SFTP, NFS DWH, Operation DB Web based application, CRM, … Workers, ETL, Analysis Engine, …
CPU Low (E3-1230v2 or existing) Mid to High (E5-2420 dual / E52620 dual) Mid (E3-1230v2/existing server) High (E3-1230v2/existing server)
RAM 16G or above 32G or above 16G or above 16G or above
RAID RAID 1/5/6 RAID 10 NO RAID / RAID 1 NO RAID
RAID Controller Dell H710p or equivalent Dell H710p or equivalent N/A N/A
HDD TBD 1TB x 4 500GB 500GB
Quantity x1 x1 xN xN
Public IPs x1 N/A x2 N/A
Region All
All
All
All
Scalability Add drive for increase storage capacity.  Can add new server as required. Single server can support up to 3 to 5 years.  Can add new server as required. Scale Horizontally by adding new server as required. Scale Horizontally by adding new server as required.
New Server Price 20K (Dell R220) to 40K (Dell R520) 50K+ HKD (Dell R520/R720) 12K HKD (Dell R220) 12K HKD (Dell R220)





Servers Allocation
Live site

File Server Database Server Web Server Processing Server

New server Dell R220/R520 New server Dell R520/R720 HK  

20K/40K+ HKD - Stage 2+ 50K+ HKD - Stage 2 existing server #1 - Management  

  Support both all regions
existing server #2 - Scoring
 

  Database for Management, Scoring, Worker, DWH, etc. Dell R210 - Workers, ETL, SFTP  

    UK  

    existing #3 - Management  

    existing #4 - Scoring  

=R220, R210 #2 in Stage 1 = existing servers, R210 and R220 servers in Stage 1 Dell R220 #2 (12K HKD - Stage 1) - Worker, SFTP =R210, R220 #2 in Stage 1





Standby site

File Server Database Server Web Server Processing Server

New server Dell R220 RAID 1 New server Dell R220 with RAID 1 HK  

~20K HKD - Stage 3 (* Use low to mid-range standby server) R220 #3 (12K HKD - Stage 1.5) - Management, Scoring, SFTP, …  

  ~20K HKD - Stage 3 1 x VM #1 (2K HKD - Stage 1.5) Worker  

    UK  

    R220 #3 (12K HKD - Stage 1.5) - Management, Scoring, SFTP, …  

=R220 #3, R220 #4, VM #1, VM #2 in Stage 1.5 =R220 #3, R220 #4, VM #1, VM #2 in Stage 1.5 1 x VM #2 (2K HKD - Stage 1.5) Worker =VM #1, VM #2 in Stage 1.5