Showing posts with label Annotation. Show all posts
Showing posts with label Annotation. Show all posts

May 21, 2019

Custom annotation in Java with examples

Custom annotation in Java using Tax annotation


Here we demonstrate how you can create a custom annotation. Creating a custom annotation is very easy. You can use custom annotation in places where you are developing your own services.


The complete code will be available in the following link

Our git hub repository : Konzernites

Custom annotation interface example

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
public @interface Tax {
public String name();
public double amount();
public TaxMode mode() default TaxMode.PERCENTAGE;
public TaxTypes type() default TaxTypes.INCLUSIVE;
}



 What we did here?

we declared a public custom annotation named Tax using @inteface keyword

public @interface Tax

Next we added the scope and visibility using meta annotation

@Retention &  @Target is used



ElementType.TYPE implies the annotation can be applied on a class
ElementType.FIELD implies the annotation can be applied on a field
ElementType.METHOD implies the annotation can be applied on a method

We then wrote a price Modification class which works on reflection in java ( Java Reflection API)
where in run time we check the whether the annotation is added on the fields or method of a class and corresponding computation is calculated.

Below is an Insurance class where we applied the custom annotation we created.

@author steffi thomas
public class Insurance {
private String name;
private double supplierPrice;
private double maketPrice;
private double basePrice;
private double profit;
private double commision;

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name
*            the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the supplierPrice
*/
public double getSupplierPrice() {
return supplierPrice;
}

/**
* @param supplierPrice
*            the supplierPrice to set
*/

public void setSupplierPrice(double supplierPrice) {
this.supplierPrice = supplierPrice;
}

/**
* @return the maketPrice
*/
@Tax(name = "VAT", amount = 5, mode = TaxMode.PERCENTAGE, type = TaxTypes.INCLUSIVE)
public double getMaketPrice() {
return maketPrice;
}

/**
* @param maketPrice
*            the maketPrice to set
*/
public void setMaketPrice(double maketPrice) {
this.maketPrice = maketPrice;
}

/**
* @return the basePrice
*/
@Tax(name = "VAT", amount = 5, mode = TaxMode.PERCENTAGE, type = TaxTypes.INCLUSIVE)
public double getBasePrice() {
return basePrice;
}

/**
* @param basePrice
*            the basePrice to set
*/
public void setBasePrice(double basePrice) {
this.basePrice = basePrice;
}

/**
* @return the profit
*/
@Tax(name = "VAT", amount = 100, mode = TaxMode.AMOUNT, type = TaxTypes.EXCLUSIVE)
public double getProfit() {
return profit;
}

/**
* @param profit
*            the profit to set
*/
public void setProfit(double profit) {
this.profit = profit;
}

/**
* @return the commision
*/
@Tax(name = "VAT", amount = 1, mode = TaxMode.PERCENTAGE, type = TaxTypes.EXCLUSIVE)
public double getCommision() {
return commision;
}

/**
* @param commision
*            the commision to set
*/
public void setCommision(double commision) {
this.commision = commision;
}

}


While processing the annotation we used the reflection API as we mentioned above, please refer the PriceModification.Java class to know how it works


Thanks

January 17, 2019

Spring Boot Application for Rest API - micro service api example

Consumerfed application - An Expense Rest API

Diagram



A sample spring boot application

Main class

package com.etrade.expenses;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.etrade.expenses.services.ExpensesService;
/**
 *
 * @author Consumerfed IT Section Kozhikode
 * consfedkozhikode@gmail.com
 */
@SpringBootApplication
@RestController
public class EtradeExpensesApplication {

@Autowired
ExpensesService expenseService;

public static void main(String[] args) {
SpringApplication.run(EtradeExpensesApplication.class, args);
}

@RequestMapping(value= "/getAllExpenseHead", method=RequestMethod.GET, headers="Accept=application/json")
public List getExpensesDetails() {
return expenseService.getExpensesHead() ;
}

}


SpringBootServletInitializer class


package com.etrade.expenses;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
 *
 * @author Consumerfed I T Section kozhikode
 *
 * Since we are developing a web application
 * we need to extends SpringBootServletInitializer
 *
 * we can also do the following
 *
 * EtradeExpensesApplication extends SpringBootServletInitializer
 *
 * For our convenience we did like this
 *
 */
public class ServletInitializer extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(EtradeExpensesApplication.class);
}

}

Service class


/**
 *  Expense service class is an implementation of ExpenseService Interface
 */
package com.etrade.expenses.servicesImpl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrade.expenses.dao.ExpensesDao;
import com.etrade.expenses.services.ExpensesService;

/**
 * @author Consumerfed IT Section kozhikode
 *
 */
@Service("expensesService")
public class ExpensesServiceImpl implements ExpensesService {

@Autowired
ExpensesDao expenseDao;


@Override
@Transactional
public List getExpensesHead() {
return expenseDao.getExpensesHead();
}
}

Data Access Object class

/**
 *Phone : +918281808029
 */
package com.etrade.expenses.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.etrade.expenses.dao.ExpensesDao;
/**
 * Expense Data Access Object class is an implementation of DAO interface
 */
import com.etrade.expenses.entities.ExpenseHead;

/**
 * @author Consumerfed I T Section kozhikode
 *
 */
@Repository
public class ExpensesDaoImpl implements ExpensesDao {

@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}

@Override
public List getExpensesHead() {
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ExpenseHead.class);
List<ExpenseHead> expenseList = criteria.list();
return expenseList;
}

}

Entity class


package com.etrade.expenses.entities;

import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonProperty;

//import org.springframework.boot.autoconfigure.domain.EntityScan;


/**
 * The persistent class for the tbl_expense_head database table.
 * Phone : +918281808029
 */
@Entity
@Table(name="expense_head")
@XmlRootElement(name="expense")
//@NamedQuery(name="TblExpenseHead.findAll", query="SELECT t FROM TblExpenseHead t")
public class ExpenseHead implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(name="expense_head_id_pk")
@GeneratedValue(strategy=GenerationType.AUTO)
@JsonProperty("id")
private int expenseHeadIdPk;

@JsonProperty("description")
@Column(name="expense_head_description")
private String expenseHeadDescription;

@JsonProperty("name")
@Column(name="expense_head_name")
private String expenseHeadName;

@JsonProperty("status")
@Column(name="expense_head_status")
private String expenseHeadStatus;

public ExpenseHead() {
}

public int getExpenseHeadIdPk() {
return this.expenseHeadIdPk;
}

public void setExpenseHeadIdPk(int expenseHeadIdPk) {
this.expenseHeadIdPk = expenseHeadIdPk;
}

public String getExpenseHeadDescription() {
return this.expenseHeadDescription;
}

public void setExpenseHeadDescription(String expenseHeadDescription) {
this.expenseHeadDescription = expenseHeadDescription;
}

public String getExpenseHeadName() {
return this.expenseHeadName;
}

public void setExpenseHeadName(String expenseHeadName) {
this.expenseHeadName = expenseHeadName;
}

public String getExpenseHeadStatus() {
return this.expenseHeadStatus;
}

public void setExpenseHeadStatus(String expenseHeadStatus) {
this.expenseHeadStatus = expenseHeadStatus;
}

}

Hibernate configuration class


/**
 *  Hibernate Configuration class
 *
 *  datasource, sessionfactory, transaction manager
 */
package com.etrade.expenses;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
//import org.springframework.orm.hibernate4.HibernateTransactionManager;
//import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Consumerfed I T section kozhikode

 * Phone : 8281808029
 */
@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

@Value("${db.driver}")
private String DRIVER;

@Value("${db.username}")
private String USERNAME;

@Value("${db.password}")
private String PASSWORD;

@Value("${db.url}")
private String URL;

@Value("${hibernate.dialect}")
private String DIALECT;

@Value("${hibernate.show_sql}")
private String SHOW_SQL;

@Value("${hibernate.hbm2ddl.auto}")
private String HBM2DDL_AUTO;

@Value("${entitymanager.packagesToScan}")
private String PACKAGE_TO_SCAN;

@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DRIVER);
dataSource.setUrl(URL);
dataSource.setPassword(PASSWORD);
dataSource.setUsername(USERNAME);
return dataSource;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {

LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(PACKAGE_TO_SCAN);

Properties properties = new Properties();
properties.put("hibernate.dialect", DIALECT);
properties.put("hibernate.show_sql", SHOW_SQL);
properties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
sessionFactory.setHibernateProperties(properties);

return sessionFactory;
}

@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}

}

application property file


# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/consumerfedBithesh
db.username: bithesh
db.password: bithesh@gmail.com

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Output


[{"id":1,"description":"The expense for taking photostats and xerox","name":"PHOTOCOPIER","status":"A"},{"id":2,"description":"Expenses like auto, taxi, bus fares below 100 rupees","name":"LOCAL CONVEYANCE","status":"A"},{"id":3,"description":"Amount paid for packing goods in units","name":"PACKING CHARGES","status":"A"},{"id":4,"description":"Expenses for tea","name":"TEA EXPENSES","status":"I"}]

Notes

@RequestMapping(value= "/createExpense", method=RequestMethod.POST, headers="Accept=application/json")

can be replaced by

@PostMapping(value= "/createExpense",headers="Accept=application/json")

Description

Working as an assistant of kozhikode regional office Information Manager, we developed this project. This project is working on producer consumer model. We don't follow any specific methodology ,uml diagrams and all as our organization is not a software development company, we have a efficient team who develop software for the organization. This project was developed for kozhikode Regional office , Regional Manager who is a good support for all Information Technology related works.

This Rest API what it does is, will give the consumer , who ever it is the details of all expense head, as the data is in the format of json, it can be consumed even by mobile application very fast. The application is a stand alone application. We build the whole application as a combination of many standalone which has their own functionality. We are not sure is it a good practice or not, as there is not top layer above us to clear our doubts.

The project was developed in the year 2015

Reader can contact us at any time if they any queries

Hire us!!! Or for projects contact us !!! 

July 09, 2018

@Gzip compression annotation in java

package com.belazy.gzip;

import java.io.IOException;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String data = "hello world ";
try {
byte[] s = GzipAlgo.compress(data);
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

SamplePojo p =new SamplePojo();
GzipCompressor compressor = new GzipCompressor();
p=compressor.getCompressor(p);

}

}


/**
 *
 */
package com.belazy.gzip;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author belazy
 *
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD })
public @interface Gzip {
public String type();
}


package com.belazy.gzip;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipAlgo {

public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
}


/**
 * 
 */
package com.belazy.gzip;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author consumerfed itsection
 * phone : 8281808029
 * 
 */
public class GzipCompressor {

public SamplePojo getCompressor(SamplePojo axa) {
// TODO Auto-generated method stub
Class refClass = axa.getClass();
Annotation taxAnno;
Method[] methods = refClass.getMethods();

for (Method thisMethod : methods) {
String methodName = thisMethod.getName();
if (thisMethod.getAnnotations().length > 0) {
for (Annotation annotation : thisMethod.getAnnotations()) {
if (annotation instanceof Gzip) {
taxAnno = thisMethod.getAnnotation(Gzip.class);
Gzip zip = (Gzip) taxAnno;
try {
System.out.println(" *** "
+ thisMethod.invoke(axa, new String()));
String data  = (String)thisMethod.invoke(axa, new String());
byte[] b = GzipAlgo.compress(data);
System.out.println(b);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

}
}
return axa;
}

}
/**
 * 
 */
package com.belazy.gzip;

/**
 * @author consumerfed itsection
 * Phone : 0091 8281808029
 *
 */
public class SamplePojo {
private String data;

/**
* @return the data
*/
@Gzip(type="compression")
public String getData() {
return data;
}

/**
* @param data the data to set
*/
public void setData(String data) {
this.data = data;
}

}



Facebook comments