January 30, 2019

A small introduction on Node Js

Node js is a runtime environment for javascript

Node js is c++ program that uses chrome v8 engine

Node js continously monitors EventQueue in the background,
EventQueue helps single thread to perform multiple request async

Node are mainly used on data intensive application not on cpu intensive application
as single thread is used.

How do I resolve “Cannot find module” error using Node.js?

Instead of window object we use global object in node, through which we can access all global objects

In node js every file is a module and the variable inside that scope to that module

If you want to export a function outside the module, you have to use module.export function
to consume it we use require() function
use const instead var for require()

In a module either you can export an object or a single function

User node js we can retrieve the information about operating system and file, which was not possible while using Java script

Always prefer async methods while working with node js

Use jshint tool to know the error

In ECMAScript25 we can concatenate two string with out using + operator you can use ` instead

January 27, 2019

Check if sum of number exist in the array

/**
 *
 */
package com.cfed.tutorials;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Apple
 *
 */
public class CheckingIfSumExist {

private boolean sumExistOrNotSorted(int[] array, int sum) {
int len = 0;
if ((len = array.length) <= 0)
return false;

int low = 0;
int high = len;

while (low < high) {

}

return false;

}

private boolean sumExistOrNot(int[] array, int sum) {
int len;
if ((len = array.length) <= 0)
return false;

Set<Integer> complimentList = new HashSet<>();

for (int i = 0; i < len; i++) {

int value = array[i];

if (complimentList.contains(value))
return true;
else {
int complimentValue = sum - value;
complimentList.add(complimentValue);
}
}

return false;

}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

CheckingIfSumExist c = new CheckingIfSumExist();

int[] array = { 1, 3, 9, 4 };
System.out.println(c.sumExistOrNot(array, 8));

}

}

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 !!! 

How to get the process id associated with process running on a specific port number

How to get the process id associated with process running on a specific port number

To get the process id use

netstat -ao | find "8080"



you will get a out put like this

  TCP    0.0.0.0:8080           Regional Manager-PC:0             LISTENING       2316


If you want to write the following out put to file 

append   >> c:\consumerfed.text to the above command



January 10, 2019

How to create an immutable class in java a simple example - biju vas

package com.cfed.tutorials;
/**
 *  creating an immutable class - class which state does not change
 * 
 *  helps for caching, thread safe etc
 * 
 *  class is final
 * 
 *  all mutable fields are changed to final
 * 
 *  no setters
 * 
 */
import java.util.HashMap;
import java.util.Iterator;

public final class MedicalRepresentives {

private final int tin;

private final String companyName;

private final HashMap<String,String> employees;

public int getId() {
return tin;
}


public String getName() {
return companyName;
}

/**
* Accessor function for mutable objects
*/
public HashMap<String, String> getTestMap() {
//return testMap;
return (HashMap<String, String>) employees.clone();
}


public MedicalRepresentives(int i, String n, HashMap<String,String> hm){

this.tin=i;
this.companyName=n;
HashMap<String,String> tempMap=new HashMap<String,String>();
String key;
Iterator<String> it = hm.keySet().iterator();
while(it.hasNext()){
key=it.next();
tempMap.put(key, hm.get(key));
}
this.employees=tempMap;
}


/**
* Constructor performing Shallow Copy
* @param i
* @param n
* @param hm
*/
/**
public FinalClassExample(int i, String n, HashMap<String,String> hm){
System.out.println("Performing Shallow Copy for Object initialization");
this.id=i;
this.name=n;
this.testMap=hm;
}
*/

/**
* To test the consequences of Shallow Copy and how to avoid it with Deep Copy for creating immutable classes
* @param args
*/
public static void main(String[] args) {
HashMap<String, String> h1 = new HashMap<String,String>();
h1.put("1", "Biju Vas");
h1.put("2", "Smithesh");
h1.put("3", "Sreekumar");

String s = "Guru Medicals , Vadakara";

int i=19999999;

MedicalRepresentives ce = new MedicalRepresentives(i,s,h1);

//Lets see whether its copy by field or reference
System.out.println(s==ce.getName());
System.out.println(h1 == ce.getTestMap());
//print the ce values
System.out.println(" Tin number:"+ce.getId());
System.out.println("organisation name :"+ce.getName());
System.out.println("employees :"+ce.getTestMap());
//change the local variable values
i=20;
s="New organisation";
h1.put("4", "Manohar");
//print the values again
System.out.println("tin after local variable change:"+ce.getId());
System.out.println("organistion name after local variable change:"+ce.getName());
System.out.println("employess after local variable change:"+ce.getTestMap());

HashMap<String, String> hmTest = ce.getTestMap();
hmTest.put("4", "new");

System.out.println("ce testMap after changing variable from accessor methods:"+ce.getTestMap());

}

}


output


true
false
 Tin number:19999999
organisation name :Guru Medicals , Vadakara
employees :{1=Biju Vas, 2=Smithesh, 3=Sreekumar}
tin after local variable change:19999999
organistion name after local variable change:Guru Medicals , Vadakara
employess after local variable change:{1=Biju Vas, 2=Smithesh, 3=Sreekumar}
ce testMap after changing variable from accessor methods:{1=Biju Vas, 2=Smithesh, 3=Sreekumar}

January 09, 2019

Bit wise operator in java

/**
 *
 */
package com.hackerearth.basicprograming;

/**
 * @author I T Section Regional Office Kozhikode
 *
 */
public class LeftShiftOperator {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int i = 2;
int j= i>>1;
int k =i<<1;
System.out.println(j);
System.out.println(k);

}

}

January 03, 2019

Solving optimalUtilization having deviceCapacity foregroundAppList backgroundAppList

package com.cfed.amazon
import java.util.ArrayList;
import java.util.List;
// IMPORT LIBRARY PACKAGES NEEDED BY YOUR PROGRAM
// SOME CLASSES WITHIN A PACKAGE MAY BE RESTRICTED
// DEFINE ANY CLASS AND METHOD NEEDED
// CLASS BEGINS, THIS CLASS IS REQUIRED
public class Solution
{
    // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
    List<List<Integer>> optimalUtilization(
                        int deviceCapacity,
                            List<List<Integer>> foregroundAppList,
                            List<List<Integer>> backgroundAppList)
{

        // WRITE YOUR CODE HERE
   
    List<List<Integer>> optimalUtilization = new ArrayList<>(2);
   
        for(List<Integer> fgList : foregroundAppList){
            for(List<Integer> bgList : backgroundAppList){
           
            int value = fgList.get(1)+bgList.get(1);
           
           
           
            if(value==deviceCapacity ) {
           
            List optList = new ArrayList<>();
            optList.add(fgList.get(0));
            optList.add(bgList.get(0));
            optimalUtilization.add(optList);
            }
           
            }
        }
   
    return optimalUtilization;
    }
    // METHOD SIGNATURE ENDS
   
   
    public static void main(String[] args) {

   
    Solution s = new Solution();
   
    List<List<Integer>> fb = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(8);
fb.add(list1);
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(15);
fb.add(list2);
List<Integer> list3 = new ArrayList<>();
list3.add(3);
list3.add(9);
fb.add(list3);


List<List<Integer>> bg = new ArrayList<>();

List<Integer> list4 = new ArrayList<>();
list4.add(1);
list4.add(8);
bg.add(list4);

List<Integer> list5 = new ArrayList<>();
list5.add(2);
list5.add(11);
bg.add(list5);

List<Integer> list6 = new ArrayList<>();
list6.add(3);
list6.add(12);
bg.add(list6);


//s.nearestVegetarianRestaurant(3, allLocations, 2);
System.out.println(s.optimalUtilization(20, fb, bg));
   
}
}


Output

[[1, 3], [3, 2]]

January 01, 2019

How to handle NumberFormatException: For input string: "0.0"

How to handle NumberFormatException: For input string: "0.0"


Here is the solution for that problem ( Use BigDecimal instead of Long.parseLong())

/**
 * Exception in thread "main" java.lang.NumberFormatException: For input string: "0.0"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.konzern.solution.StringToNumber.main(StringToNumber.java:18)
 */
package com.konzern.solution;

import java.math.BigDecimal;

/**
 * @author cfed
 *
 */
public class StringToNumber {

/**
* @param
*/
public static void main(String[] args) {

/* String valueInString = "0.0";
long valueInLong = Long.parseLong(valueInString);
System.out.println(valueInLong);*/

String valueInString = "0.0";
BigDecimal valueInDecimal = new BigDecimal(valueInString);
long valueInLong = valueInDecimal.longValue();
System.out.println(valueInLong);

}

}


Exception in thread "main" java.lang.NumberFormatException: For input string: "0.0"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.konzern.solution.StringToNumber.main(StringToNumber.java:18)





To find nearestVegetarianRestaurant from totalRestaurants, allLocations, numRestaurants

package com.cfed.amazon;
import java.util.ArrayList;
// IMPORT LIBRARY PACKAGES NEEDED BY YOUR PROGRAM
// SOME CLASSES WITHIN A PACKAGE MAY BE RESTRICTED
// DEFINE ANY CLASS AND METHOD NEEDED
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
// CLASS BEGINS, THIS CLASS IS REQUIRED
public class ConsumerfedITSection
{
    // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
    List<List<Integer>> nearestVegetarianRestaurant(int totalRestaurants,
                                         List<List<Integer>> allLocations,
                                         int numRestaurants)
{
        // WRITE YOUR CODE HERE
     
        Map<Double,List> locationMap = new TreeMap<>();
     
        for(List<Integer> location : allLocations){
            double value = location.get(0)*location.get(0)+location.get(1)*location.get(1);
            locationMap.put(value, location);
        }
     
        int i =0;
     
        List<List<Integer>> nearbyLocationList = new ArrayList<>();
     
        for(Entry<Double, List> entry : locationMap.entrySet()) {
       
        if(i<numRestaurants) {
       
        nearbyLocationList.add(entry.getValue());
        i++;
        }
        }
     
return nearbyLocationList;
     
    }
    // METHOD SIGNATURE ENDS
 
 
    public static void main(String[] args) {

    int totalRest = 3;
   
    fisrtQuiest s = new fisrtQuiest();
   
    /* List<List<Integer>> allLocations = new ArrayList<>();
    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(-3);
allLocations.add(list1);
List<Integer> list2 = new ArrayList<>();
    list2.add(1);
    list2.add(2);
allLocations.add(list2);
List<Integer> list3 = new ArrayList<>();
    list3.add(3);
    list3.add(4);
allLocations.add(list3);*/
   
   
   
        List<List<Integer>> allLocations = new ArrayList<>();
    List<Integer> list1 = new ArrayList<>();
    list1.add(3);
    list1.add(6);
allLocations.add(list1);
List<Integer> list2 = new ArrayList<>();
    list2.add(2);
    list2.add(4);
allLocations.add(list2);
List<Integer> list3 = new ArrayList<>();
    list3.add(5);
    list3.add(3);
allLocations.add(list3);

List<Integer> list4 = new ArrayList<>();
    list4.add(2);
    list4.add(7);
allLocations.add(list4);
   
List<Integer> list5 = new ArrayList<>();
    list5.add(1);
    list5.add(8);
allLocations.add(list5);

List<Integer> list6 = new ArrayList<>();
    list6.add(7);
    list6.add(9);
allLocations.add(list6);
   
   
//s.nearestVegetarianRestaurant(3, allLocations, 2);
System.out.println(s.nearestVegetarianRestaurant(6, allLocations, 3));
   
}
 
 
}


Output



[[2, 4], [5, 3], [3, 6]]




Facebook comments