8 Oct 2017

HTTP content type headers for different purpose in Rest API

Rest API  to return a zip file as download

@RequestMapping(value="/v1/collection_service/response/{appReferenceId}", method=RequestMethod.GET, produces=MediaType.MULTIPART_FORM_DATA_VALUE)

 public ResponseEntity<?> collectionServiceProfile(@PathVariable(value="appReferenceId") String appReferenceId){
  ByteBuffer byteBuffer = collectionService.getCollectionProfileZip(appReferenceId);
  MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
  headers.add(HttpHeaders.CONTENT_TYPE, "application/zip");
  return new ResponseEntity<>(byteBuffer.array(), headers, HttpStatus.OK);
 }

The line in the block is the one that determines that the content should be downloaded as zip.

6 Oct 2017

Store Zip file as blob in Cassandra using Spring data

In this blog we are going to see how we will save a zip file into Cassandra database table column. 

 For this, let's consider an example of Employee table where we want to save employee resume as a zip file into the table. The table looks like below

employee_id(int)
employee_name(text)
employee_type(text)
employee_resume(blob)











The Employee entity class would look like below

@Table(value = "employee")
public class EmployeeBean {

@Column(value = "employee_id")
private Integer employeeId;

@Column(value = "employee_name")
private String employeeName;

@Column(value = "employee_type")
private String employeeType;

@Column(value = "employee_resume")
private ByteBuffer employeeResume;

public Integer getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public String getEmployeeType() {
return employeeType;
}

public void setEmployeeType(String employeeType) {
this.employeeType = employeeType;
}

public ByteBuffer getEmployeeResume() {
return employeeResume;
}

public void setEmployeeResume(ByteBuffer employeeResume) {
this.employeeResume = employeeResume;
}

}


The EmployeeService would look like the below for saving an entry in to the table "employee"

public class EmployeeService {

private CassandraOperations cassandraTemplate;
public void saveEmployee(Integer id, String name, String type, String strResume) {
EmployeeBean emp = new EmployeeBean();
emp.setEmployeeId(id);
emp.setEmployeeName(name);
emp.setEmployeeType(type);
ByteBuffer resumeByteBuffer = ByteBuffer.wrap(strResume.getBytes());
emp.setEmployeeResume(resumeByteBuffer);
cassandraTemplate.insert(emp);
}

}

Please note the Java type for blob in Cassandra is ByteBuffer(for column resume in employee table). 
Convert the String resume to byte array and wrap into ByteBuffer and save into the table. 

13 Jun 2016

UML - Unified Modeling Language

UML has two types of diagrams - 

  1. Structure diagrams - defines the static structures of the design - Class diagram 
  2. Behavior diagrams - defines the activities of the design - Sequence diagram, activity diagram, use case diagram.

1. UML Class diagram structures - A structure diagram

Conceptual model - Helps to understand the entities and the interaction between them.

You must know the following structures before you claim that you know UML class diagrams!!!


  1. UML building blocks
  2. Rules to connect the building blocks
  3. Common mechanism of UML

+ - Public access specified in class diagram.
# - Protected access specified in class diagram.
- - Private access specified in class diagram.

In class diagram the abstract class is defined by writing the class name in italic.

Implementing an Interface is called as Realization in UML class diagram. i.e Car realizes a Vehicle behavior. 


Default value to an attribute in a class


Represent Static method or attribute in a class


      To represent static method or attribute in a class diagram underline the specific method or attribute in the class diagram.





References:



2. UML Sequence diagram structures - a kind of Interaction Diagram

Message can be of two types

  • Synchronous - Represented by solid arrow mark 

  • Asynchronous - Represented by stick arrow head









References:

http://www.ibm.com/developerworks/rational/library/3101.html

3 Jun 2016

Composition vs Aggregation in Association.

Association is a term used to define two related classes in Object oriented Environment.

Aggregation and Composition defines how the two classes are related.

Aggregation - Aggregation says that two classes are related but each individual class has its own existence. For Example : School and Student, these two classes are interrelated, School has Students and Student belongs to a School. But if the School is closed that does not implies that a Student does not exist. The Student can join other School.

Aggregation is mentioned as a hollow diamond ending arrow in UML - class diagram.

Composition - Composition defines a "Has a" relationship between two classes. Common example of composition is Human and Human heart. If Human dies then the heart will die certainly.

Composition is mentioned as a filled diamond ending arrow in UML - class diagram.



Note: In the above diagrams the diamond should be towards Contained class. i.e Car as engine so the diamond should be close to Car.

3 Aug 2015

Configuring Virtual Hosts as Proxy Server on Linux Mint with Apache2.4

Configuring Virtual Hosts as Proxy Server on Linux Mint with Apache2.4

To configure a virtual host as proxy server we use Apache as a virtual host and as a proxy server to redirect requests to JBOSS application server. In this regard we separate the  whole process into multiple steps as below

  1. Installing Apache
  2. Configuring Virtual Hosts in Apache
  3. Enabling and configuring Proxy server in Apache

1. Installing Apache

              As specified in the header we are doing the configuration in Mint, so we user apt-get to install Apache2 as below

#apt-get install apache2

2. Configuring Virtual Hosts in Apache

        Copy the following block in to the file "/etc/apache2/sites-enabled/000-default.conf"

         <VirtualHost *:80>
                  ServerName www.example.com
                  ServerAdmin webmaster@localhost
                  DocumentRoot /var/www/html
         </VirtualHost>

      "*" in the above configuration implies all the requests to this host i.e all the requests to this server with 80 port number will be served by this virtual host.
      "ServerName" directive specifies the name server identifies itself with.

3. Enabling and configuring Proxy server in Apache

                To enable Proxy in Apache use the command a2enmod as shown below

#a2enmod
        The above line will show you modules that are supported by Apache and lets you select the modules to be enabled. So enter the following options to enable 
proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

              To configure the above Virtual host as proxy change the Virtual Host block to the following


<VirtualHost *:80>
    ServerName www.example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
   
    ProxyPreserveHost On
    ProxyPass /examples http://localhost:8080/examples
    ProxyPassReverse /examples http://localhost:8080/examples 
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
         "ProxyPreserveHost" directive uses the incoming request's header for proxy redirections.
         "ProxyPass" directive maps /examples to our local server URL "http://localhost:8080/examples"
          "ProxyPassReverse" adjusts the response header URL sent from the reverse proxied server.


Reference docs:

https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension

https://httpd.apache.org/docs/2.2/vhosts/examples.html

7 May 2015

JSON library Usage

JSON Library usage for replacing the value of particular key in JSON object.


JSONObject: JSONObject is an unordered collection of key value pairs.

Ex:{
         "Employee1": {"Name":"John", "EmpId":"1002", "Address":"California" }
         "Employee2": {"Name":"Alex", "EmpId":"1001", "Address":"Mexico" }
         "Employee3": {"Name":"Luci", "EmpId":"1003", "Address":"New york" }
     }

With the above JSONString create a JSONObject.

String strEmployees ="{
         \"Employee1\": {\"Name\":\"John\", \"EmpId\":\"1002\", \"Address\":\"California\" },
         \"Employee2\": {\"Name\":\"Alex\", \"EmpId\":\"1001\", \"Address\":\"Mexico\" },
         \"Employee3\": {\"Name\":\"Luci\", \"EmpId\":\"1003\",\"Address\":\"New york\" }
     }";

JSONObject employess = new JSONObject(strEmployees);

To replace the details of "Employee1" in the above JSONString, use the JSONObject employees and method put with key value pair, which replaces if the key is already present in the JSON, otherwise it puts the new entry into the JSONObject.

System.out.println(employees.getJSONObject("Employee1"));

Output:

{"Name":"John", "EmpId":"1002", "Address":"California" }

Now to change Employee1 to {"Name":"Stacy", "EmpId":"1005", "Address":"Texos" }

Create a new JSONObject with the above details.

JSONObject employee1 = new JSONObject("{\"Name\":\"Stacy\", \"EmpId\":\"1005\", \"Address\":\"Texos\" }");

employees.put("Employee1", employee1);

Now print the output of employee1

System.out.println(employees.getJSONObject("Employee1"));

The output will be as below.

 {"Name":"Stacy", "EmpId":"1005", "Address":"Texos" }




7 Jan 2015

JAVA Management package

Management package in java consists of classes that has managed beans for environment of JAVA in the system. The following is a small example of what this Management package can do:


import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Toworld {
        public static void main(String args[]){
            OperatingSystemMXBean os =  ManagementFactory.getOperatingSystemMXBean();
            Method[] methods = OperatingSystemMXBean.class.getDeclaredMethods();
            for( int nMethodCntr = 0; nMethodCntr < methods.length ; nMethodCntr++ )
            {
                Method method = methods[nMethodCntr];
                try
                {
                    System.out.println(method.getName()+": "+method.invoke(os));                 
                }
                catch( IllegalArgumentException e )
                {
                    e.printStackTrace();
                }
                catch( IllegalAccessException e )
                {
                    e.printStackTrace();
                }
                catch( InvocationTargetException e )
                {
                    e.printStackTrace();
                }
            }
           
    }
}


The following will be the output:

getName: Linux
getAvailableProcessors: 4
getArch: amd64
getVersion: 3.6.11-4.fc16.x86_64
getSystemLoadAverage: 0.25