December 28, 2020

Could not determine type for: com.google.model.user.adminuser, at table: amazon, for columns: [org.hibernate.mapping.Column(business_seller)]

Could not determine type for: com.fp.ordermanagementservice.model.user.FP_Business_User, at table: fp_order, for columns: [org.hibernate.mapping.Column(business_seller)]


solution

You need to provide mapping annotations like @onetoone

December 21, 2020

No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.Long'. Check configuration for 'WorldEnd'



 No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.Long'. Check configuration for 'Bean validation in spirng boot'


Solutions

As clearly mentioned in the  problem, to solve this error you MUST use correct annotations.

In above case, 

@NotBlank or @NotEmpty annotation are used in String datatype.

you need to use @NotNull for Long datatypes.


December 14, 2020

No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate

No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate

2020-07-04 09:39:16.837 ERROR 1680 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@1fdf1c5] to prepare test instance [com.fp.ordermanagementservice.OrderManagementServiceApplicationTests@3f6bfcbe]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.fp.ordermanagementservice.OrderManagementServiceApplicationTests': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

December 07, 2020

To developed a pricing engine for a cycle in java - coding test

CODING TEST ( Problem)

The module to be developed is a pricing engine for a cycle. A cycle can be thought of as high level components - 

1. frame 

2. handle bar with brakes 

3. seating, 

4. wheels, 

5. chain assembly 

Each of the above high level components will have parts, for instance, a wheel has spokes, rim, tube, tyre. 

The pricing module should be able to calculate the price of the cycle given its configuration. For example, price a cycle with tubeless tyres, steel frame, 4 gears. The pricing of the parts is time sensitive, means the cost of a tyre will change with time and the module should support this. A tyre can cost 200Rs from Jan 2016 - Nov 2016, and its price can change to Rs 230 from Dec 2016 onwards. 

The pricing module should be a command line executable, no graphical ui needed. It can take its input as command line parameters or as a json text file, whatever is convenient to specify in. The inputs to the module will be the list of constituent parts, date of pricing and it will output the price of the entire cycle and also price for each high level component - frame, wheels etc. 

Modular code and well thought out class/object model is expected as well as Junit tests for main classes. 

Calculate Pricing for 1000 cycles using multithread and blocking queue using a maximum of 10 threads. 



Solution



November 28, 2020

Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.amazon.datascience.model.admin.GoogleInterview on entity object

Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.amazon.datascience.model.admin.GoogleInterview

This exception is mainly due to missing things in model class

November 21, 2020

org.springframework.security.authentication.InternalAuthenticationServiceException | UserDetailsService returned null

org.springframework.security.authentication.InternalAuthenticationServiceE

xception: UserDetailsService returned null, which is an interface contract 

violation\r\n\tat 

org.springframework.security.authentication.dao.DaoAuthenticationProvider

.retrieveUser(DaoAuthenticationProvider.java:110)\r\n\tat 

org.springframework.security.authentication.dao.AbstractUserDetailsAuthen

ticationProvider.authenticate

(AbstractUserDetailsAuthenticationProvider.java:144)\r\n\tat 

org.springframework.security.authentication.ProviderManager.authenticate

(ProviderManager.java:175)\r\n\tat 

org.springframework.security.authentication.ProviderManager.authenticate

(ProviderManager.java:195)


Solution

if your service class is implementing org.springframework.security.core.userdetails.UserDetailsService
you should implement loadUserByUsername()
and returns a new User(username,pass,rolesList)



public class yourServiceClass implements UserDetailsService {

//unimplemented method
loadUserByUsername(){
return new User(x,y,z);
}}

November 14, 2020

Auto Configuration in spring boot

Auto Configuration...


All auto configuration logic is executed in spring-boot-autoconfigure.jar. All auto configuration logic for MVC, JMS, data, and other frameworks is available in a JAR.

Auto-configuration @Conditional

If specific classes are offered in the classpath, then the configuration for that feature is enabled via auto configuration. Annotations such as @ConditionalOnMissingBean, @ConditionalOnClass, help in providing these functions.

Example 1
@Configuration
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })
public class DataSourceAutoConfiguration {
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

This configuration is enabled only when the classes are present in the classpath.

November 07, 2020

The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Errors and solution
=============

Description:

Field customAuthProvider in com.proximotech.zhw.WebServiceAuthProviderSecurityConfig required a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' in your configuration.

Solution:
Annotation @component missing in the class
com.proximotech.zhw.WebServiceAuthenticationProvider

October 21, 2020

java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter [ Solution ]

java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
at io.jsonwebtoken.impl.Base64Codec.decode(Base64Codec.java:26) ~[jjwt-0.9.1.jar:0.9.1]
at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:99) ~[jjwt-0.9.1.jar:0.9.1]
at com.cfed.config.JwtTokenUtil.doGenerateToken(JwtTokenUtil.java:71) ~[classes/:na]
at com.cfed.config.JwtTokenUtil.generateToken(JwtTokenUtil.java:59) ~[classes/:na]
at com.cfed.controller.JWTAuthenticationController.createAuthenticationToken(JWTAuthenticationController.java:43) ~[classes/:na]

Solution


Change your execution environment version to lower than java 9

Java Removed JAXB API from higher version than java 9.

October 14, 2020

Creating a custom validation for bean validation in spring boot

Creating a custom validation for bean validation in spring boot


Why we create a custom bean validation?

To test whether the input are valid one before the inputs reach our application.


How to create a custom annotation java code?

/**
 * Custom annotation
 */
package com.javabelazy.validators;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author Java code
 *
 */

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = { OrderStatusValidator.class })
public @interface Status {

String message() default "Invalid order status";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}


@Target  denotes the context where the annotation type is applicable, here we mentioned on a method or a field.
@Retention  denotes the annotation is available at the run time.
@Constraint denotes the class where the validation  logic is implemented


How to create a custom validator?

/**
 *  Custom annotation validator class
 */
package com.javabelazy.validators;

import java.util.stream.Stream;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;



/**
 * @author Java source code
 *
 */
public class OrderStatusValidator implements ConstraintValidator<Status, String> {

@Override
public void initialize(Status constraintAnnotation) {
}

@Override
public boolean isValid(String orderStatus, ConstraintValidatorContext context) {
System.out.println(" ****** "+orderStatus);

if (orderStatus.isBlank()) {
return true;
}

boolean isValid = Stream.of(OrderStatus.values()).anyMatch(v -> v.name().equals(orderStatus));

return isValid;
}

}

How to use this annotation?


@Status
private String orderStatus;


Thanks





October 07, 2020

Validation failed for query for method public abstract java.util.List net.javabelazy.service.SpringQueryExample.findByAuthor(java.lang.String)!


Error :

java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List net.javabelazy.service.SpringQueryExample.findByAuthor(java.lang.String)!

Solution : 

@Query(value = "your sql query ", nativeQuery = true)


 

September 28, 2020

Java Sample Code to convert a calendar to string object





//2020-06-05T00:00:00.000Z
public static String calendarToStr(Calendar calendar) {
try {
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);

Instant instant = calendar.getTime().toInstant();

LocalDateTime localDateTime = instant.atZone(ZoneId.of(DEFAULT_ZONE_ID, ZoneId.SHORT_IDS)).toLocalDateTime();

String formattedDate = inputFormatter.format(localDateTime);

return formattedDate;


                catch (Exception e) {
e.printStackTrace();
}


return null;
}

September 21, 2020

Hibernate Interview questions

SessionFactory

SessionFactory is a factory class developed on factory design pattern, to get a session object.
its responsibility is to read hibernate configuration class, 
connect to database and 
create sesson object.


Session

Core interface use to perform database operation, 
life cycle of a session is bound by begining and end transaction.


Difference between currentSession() and openSession() 

currentSession is to get the current session object.
we dont need to close it.
it belongs to hibernate context. once sessionfactory gets closed the session object close.

opensession is to open a new session.
we need to manually close after the operation.


Difference between get() and load()

get method loads data as soon as it is called. 
load method returns a proxy object when ever it called. a lazy loading process


What are the patterns used in hibernate ?

1. Domain model pattern
2. Factory pattern - example SessionFactory class
3. Proxy pattern -
4. Data Mapper -



Second level cache ( EH Cache)

dependency : hibernate-ehcache
class : EhCacheRegionFactory

Separate ehcache.xml file where we give details like diskstore path, time to live etc

@cache annotation has to be used in entity class



Immutable class in java



“Hope is important because it can make the present moment less difficult to bear. If we believe that tomorrow will be better, we can bear a hardship today.”

September 14, 2020

Pain is inevitable, but suffering is a choice


A senior monk & a junior monk were traveling. 

They reached a river with a strong current. They were preparing to cross, & they saw an attractive woman also attempting to cross.

She asked if they could help her cross to the other side.

They both glanced at one another because they had taken vows not to touch a woman.

Then, without a word, the older monk picked up the woman, carried her across the river, placed her gently on the other side, & started walking.

The younger monk was shocked to see. After rejoining his companion, he was speechless, & an hour passed without a word between them.

Two more hours, then three, finally the younger monk asked “As monks, we are not permitted a woman, how could you then carry that woman on your shoulders?”

The older monk replied calmly, “Dear, I set her down on the other side of the river hours ago, WHY ARE YOU STILL CARRYING HER?”
______

In life, sometimes we keep carrying the past hurts, worries, sadness, guilt, resentments so tight, that we forget to live the present, unaware that the person we are hurting is our own self.

Pain is inevitable, but suffering is a choice.

We can choose to let go of what doesn’t serve us anymore, & live in the NOW, because now is all that exists.

September 07, 2020

Chef's in paris cooking with ingredients: How to solve below complex problem using java

below is the problem :-

Chef's ingredients:-


1.The chef receives exactly 1 ingredient per day from the market.The
ingredients never repeat.

2. Every ingredient belongs to 1 of the 3 categories namely FIBER,FAT & CARB.

3.Every ingredient has a unique ingredient id.

4.The ingredient id always starts with the category name (ex:FIBERBroccoli,FATCheese,CARBRice)

Chef's Dishes

1. All of the chef's dishes have a constant number of ingredients.(this will be your program's input)

2. All the ingredients used will be fully used in a Dish. The chef doesn' use some part/quntity of an ingredient.

3.All of the chef's dishes mush have at least 60% of the ingredients from a single category.(i.e. if the chef cooks using
4 ingredients,then at leaast 3 FAT ingredients OR at least 3 FIBER ingredients OR at least 3 CARB ingredients are needed)


Chef's Cooking style:-

1. If the chef has multiple options of ingredients for the dish,then he takes the oldest possible ones to cook
in the order of their arrival.

2.After the chef prepares a dish,the ingredients used can Not be reused as theyhave been already used.

3.The chef prepares a maximum of 1 dish per day.

4.if the Chef does not have enough ingredients to cook the dish with above mentioned rules,then he does not
cook on that day.

Given the input array of ingredient id that the chef receives every day (i.e. array index is the day number)
write a program to print when does the chef cook a dish and when he does not.


Input:-

Line 1: The total number of days for the scope of the problem(1<=input<=20)

Line 2: The exact number of ingredients that chef uses to cook(1<=input<=20)

Line 3: The space separated ingredient ids.(6<=length(ingredientid)<=20)

Output:- Print the ":" separated used ingredient ids in order of their arrival if the chef cooks on that day
and print "-" if the chef doesn't cook anything on that day.Print the output as  single string.

Example input 1:

5
3
FATOil FATCheese FATEgg FIBERSpinach CARBRice FIBERBeans

Example INPUT 2:

6
3
FATOil:FATCheese FATEgg FIBERSpinach CARBRice FIBERBeans

EXAMPLE OUTPUT 2:

--FATOil:FATCheese:FATEgg--FIBERSpinach:CARBRice:FIBERBeans

EXAMPLE INPUT 3:

12
4
FATOil FIBERSpinach CARBRice FATCheese FIBERBeans FATEgg
FIBERBroccoil CARBPotato CARBCorn FATOlive FIBERCarrot




package com.cfed;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Solution {

public static void main(String args[]) {

String[] ingre = { "FATOil", "FIBERSpinach", "CARBRice", " FATCheese", "FIBERBeans" };
Map<Integer, String> ingred = new HashMap<Integer, String>();
ingred.put(1, "FATOil");
ingred.put(2, "FIBERSpinach");
ingred.put(3, "CARBRice");
ingred.put(4, "FATCheese");
ingred.put(5, "FIBERBeans");
ingred.put(6, "FATEgg");
ingred.put(7, "FIBERBrocoli");
ingred.put(8, "CARBPotato");
ingred.put(9, "CARBCorn");
ingred.put(10, "FATOlive");
ingred.put(11, "FIBERCarrot");
ingred.put(12, "CARBBeetroot");

int days = 6;
findChefCookingDays(days, ingred);

}

List<String> categories = List.of("FAT", "FIBER", "CARB");
static int fatCount = 0;
static int fiberCount = 0;
static int CarbCount = 0;

static List<String> fatList = new ArrayList<>();
static List<String> fiberList = new ArrayList<>();
static List<String> CarbList = new ArrayList<>();

private static void findChefCookingDays(int days, Map<Integer, String> ingred) {

for (Entry<Integer, String> entry : ingred.entrySet()) {

if (entry.getValue().contains("FAT")) {
fatList.add(entry.getValue());
fatCount++;
} else if (entry.getValue().contains("FIBER")) {
fiberList.add(entry.getValue());
fiberCount++;
} else if (entry.getValue().contains("CARB")) {
CarbList.add(entry.getValue());
CarbCount++;
}

int isCook = tryToCook(ingred);
System.out.print(isCook);

}

/*
* for (String ing : ingred) { tryToCook(); if (ing.contains("FAT")) {
* fatCount++; } else if (ing.contains("FIBER")) { fiberCount++; } else if
* (ing.contains("CARB")) { CarbCount++; }
* }
*/

}

private static int tryToCook(Map<Integer, String> ingred) {

if (fatList.size() > 2 || (fatList.size() >= 2 && (fiberList.size() > 0 || CarbList.size() > 0))) {
if (CarbList.size() > 0) {
CarbList.remove(0);
}else if (fiberList.size() > 0) {
fiberList.remove(0);
} else if (fatList.size() > 2) {
fatList.remove(0);
}
fatList.remove(0);
fatList.remove(0);

return 1;

} else if (fiberList.size() >2 ||( fiberList.size() >= 2 && (fatList.size() > 0 || CarbList.size() > 0))) {

if (fatList.size() > 0) {
fatList.remove(0);
} else if (CarbList.size() > 0) {
CarbList.remove(0);
} else if (fiberList.size() > 2) {
fiberList.remove(0);
}
fiberList.remove(0);
fiberList.remove(0);

return 1;

} else if (CarbList.size() > 2 || (CarbList.size() >= 2 && (fatList.size() > 0 || fiberList.size() > 0))) {

if (fatList.size() > 0) {
fatList.remove(0);
} else if (fiberList.size() > 0) {
fiberList.remove(0);
} else if (CarbList.size() > 2) {
CarbList.remove(0);
}
CarbList.remove(0);
CarbList.remove(0);
return 1;
} else {

return 0;
}

}

}

August 28, 2020

Swagger- api in spring boot


@ApiModel(value = "UserDTO", description = "User Data Transfer Object description")
public class UserDTO {



@ApiModelProperty(value="user ID",position = 0 , hidden = true)
private String userId; 

August 21, 2020

Web hooks - the Reverse APIs

Web hooks provide a mechanism where by a server-side application can notify a client-side application when a new event (that the client-side application might be interested in) has occurred on the server.

Reverse APIs

August 14, 2020

Java8: Stream merge two lists

/**
 * id 53481363
 */
package com.konzern.eight;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Chippu
 *
 */
public class MergingList {

public static<T> List<T> merge(List<T> one, List<T> two){
List<T> list = one.stream().collect(Collectors.toList());
list.addAll(two);
return list;
}

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

List one = new ArrayList<>();
one.add(1);
one.add(2);
one.add(3);
List two = new ArrayList<>();
two.add(4);
two.add(5);
two.add(6);
System.out.println(MergingList.merge(one, two));

}

}

August 07, 2020

Spring boot failed Field customAuthProvider in SecurityConfig required a bean of type 'AuthProvider' that could not be found.

Description:

Field customAuthProvider in com.proximotech.zhw.WebServiceAuthProviderSecurityConfig required a bean of type 

'com.proximotech.zhw.WebServiceAuthenticationProvider' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.proximotech.zhw.WebServiceAuthenticationProvider' in your configuration.

Solution:
Annotation @component missing in the class
com.proximotech.zhw.WebServiceAuthenticationProvider

July 28, 2020

Tic Tac Toe game in java with source code | explained | Java implementation

A Simple tic tac toe game : github url

git clone : https://github.com/consumerfed/game.git

July 21, 2020

Debugging Auto Configuration in spring boot application


Debugging Auto Configuration


There are two approaches you can debug and discover more information about auto 
configuration.

1. Using Spring Boot Actuator

2. Turning on debug logging

You can switch on debug logging by including a simple property value to 
application.properties.

In this example, we are switching on Debug level for all logging from org.springframework 

package (and sub packages).

logging.level.org.springframework: DEBUG

When the application is restarted, you will view an auto configuration report printed in the log.

July 14, 2020

Algorithm to find maximum profit on buying and selling from an array




Class MaximumProfit{

private int maxProfit(int[] prices) {
int profit = 0;
int minimum = 0;
for (int current = 1; current < prices.length; current++) {
int previous = current - 1;
int next = current + 1;
if (prices[previous] > prices[current]) {
minimum = current;
}
if (prices[previous] <= prices[current] && (next == prices.length ||prices[current] > prices[next]  )) {
profit += (prices[current] - prices[minimum]);
}
}
return profit;
}

public static void main(String[] args) {
// int[] a = { 7, 1, 5, 3, 6, 4 };
int[] a = { 1, 2, 3, 4, 5 };
// int []a = {7,6,4,3,1};
// int[] a = { 1, 2, 3, 4, 1 };
System.out.println(new MaximumProfit().maxProfit(a));
}

}

July 07, 2020

Maven : Changing the Version of Java in pom.xml file

Changing the Version of Java


If you wish to change the Java version, you can include a java.version property to pom.xml.

<properties>
    <java.version>1.8</java.version>
</properties>



June 28, 2020

A Complete article on String class in Java

A Complete article on String class in Java




String var = new String("Google interview questions");

There is a high chance you came across the questions about String in most of the interviews.

What is a String?

We can say a string as a sequence of characters.

How a string implemented?

The string is implemented as an array of bytes that stores the character using a certain specific character encoding ( Say for example CP1144)

How this Character Encoding works?

Java uses UTF-16 character encoding internally to store a string.

Java supports a wide range of encoding.

Sample Java code :-

String crackInterview = new String("Facebook interview questions");

byte[]  elonmask=  crackInterview.getBytes();

byte[]  uber=  crackInterview.getBytes("CP1044");

will return different results.

How to create a String in Java?

There are two ways to create a string in java. One by String literal and other by new keyword.

String var = "Amazon interview questions"; ( using literals )

String var = new String("Microsoft interview questions"); ( using new operator)

There will be some differences in creating in these ways, right?
yes, while using new operator a string will be created in the string pool as well as in heap memory. 
on the other hand while using literals string will be created on spring pool

Then what is a string pool? why java using a String pool?

Simply a pool of string in heap memory.

String pool is an implementation of String interning concept, developed on flyweight design pattern. 

we can use the intern() method to put back the string created using a new operator to string pool.

Since the value of the string object does not change, we called String is immutable.

Why we kept the string in a pool?

Security and Immutable

What is the flyweight design pattern?

A creational software design pattern.

Minimizing memory usage by share similar data.

How String becomes mutable?

To become string a mutale one we need to implement either StringBuilder or StringBuffer class


@author : Konzernites

June 21, 2020

Budget Preparation monthly estimation of budget java source code cfed

import java.io.IOException;

import javax.swing.JOptionPane;

/**
 * 
 */

/**
 * @author vipin
 *
 */
public class MainClass {

/**
* @param args
*/
public static void main(String[] args) {
    ReadExcel test = new ReadExcel();
   test.setInputFile("BUDGET.xls");
  // test.setInputFile("BUDGET.xls");
    try {
test.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Err"+e.getMessage());
}

}

}





import java.io.File;
import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.swing.JOptionPane;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
/**
 * 
 * @author cfed
 *
 */
public class ReadExcel {

  private String inputFile = null;
  private BudgetCreator budgetCreator = null;
  
  //private Vector<Vector> array =null;
  
  private Map<Integer,Double> lastFinYrRetail = null;
  private Map<Integer,Double> lastFinYrSbdy = null;
  private Map<Integer,Double> newFinYrRetail = null;
  private Map<Integer,Double> newFinYrSbdy = null;
  private Map<Integer,Double> budgetData = null;
  
  private int lstYrsRFirmCode = 0;
  private double lstYrsRValue = 0;
 
  private int lstYrsSFirmCode = 0;
  private double lstYrsSValue = 0;

  
  private int newYrsRFirmCode = 0;
  private double newYrsRValue = 0;

  private int newYrsSFirmCode = 0;
  private double newYrsSValue = 0;

  
  private int budgetFirmCode = 0;
  private double budgetValue = 0;


  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
  budgetCreator = new BudgetCreator();
// array = new Vector<Vector>();
  lastFinYrRetail = new HashMap<Integer, Double>();
  lastFinYrSbdy= new HashMap<Integer, Double>();
  newFinYrRetail = new HashMap<Integer, Double>();
  newFinYrSbdy= new HashMap<Integer, Double>();
  budgetData= new HashMap<Integer, Double>();
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
      w = Workbook.getWorkbook(inputWorkbook);

      Sheet sheet = w.getSheet("Sheet1");

      
     int rowCount = sheet.getRows();
     int colCount = 10;
      
      for(int row=0; row<rowCount; row++){
      
      for(int col=0;col<colCount;col++){
      
      Cell cell = sheet.getCell(col, row);
      CellType type = cell.getType();
      String value = cell.getContents();
      switch (col) {
case 0:
lstYrsRFirmCode = budgetCreator.getNameFirmCode(value);
break;
case 1:
if(lstYrsRFirmCode>0&&(type==CellType.NUMBER)){
lstYrsRValue = Double.parseDouble(value);
    lastFinYrRetail.put(lstYrsRFirmCode, lstYrsRValue/100000);  // first retails input
}
break;
case 2:
lstYrsSFirmCode = budgetCreator.getNameFirmCode(value);
break;
case 3:
if(lstYrsSFirmCode>0&&(type==CellType.NUMBER)){
lstYrsSValue = Double.parseDouble(value);
    lastFinYrSbdy.put(lstYrsSFirmCode, lstYrsSValue/100000); // first sbdy input
}
break;
case 4:
newYrsRFirmCode = budgetCreator.getNameFirmCode(value);
break;
case 5:
if(newYrsRFirmCode>0&&(type==CellType.NUMBER)){
newYrsRValue = Double.parseDouble(value);
    newFinYrRetail.put(newYrsRFirmCode, newYrsRValue/100000); // new retail input
}
break;
case 6:
newYrsSFirmCode = budgetCreator.getNameFirmCode(value);
break;
case 7:
if(newYrsSFirmCode>0&&(type==CellType.NUMBER)){
newYrsSValue = Double.parseDouble(value);
    newFinYrSbdy.put(newYrsSFirmCode, newYrsSValue/100000); // new sbdy input
}
break;
case 8:
budgetFirmCode = budgetCreator.getNameFirmCode(value);
break;
case 9:
if((budgetFirmCode>0)&&(type==CellType.NUMBER)){  //add recently
budgetValue = Double.parseDouble(value);
    budgetData.put(budgetFirmCode, budgetValue); // budget value
}
break;

default:
break;
}
      
    }
   
      
      }

      
      Vector<Vector> array =budgetCreator.calculateBudget(lastFinYrRetail,lastFinYrSbdy,newFinYrRetail,newFinYrSbdy,budgetData);
      WriteExcel test = new WriteExcel();
         test.setOutputFile("BUDGET_REPORT.xls",array);
    //test.setOutputFile("BUDGET_REPORT.xls",array);
          test.write();
          JOptionPane.showMessageDialog(null, "Excel file : BUDGET_REPORT created !!! ");
          
    } catch (BiffException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(null, "Err"+e.getMessage());
    } catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Err"+e.getMessage());
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Err"+e.getMessage());
}
  }



import java.util.HashMap;
import java.util.Map;


public class UnitsMap {
private Map<Integer,String> unitMap = null;
public UnitsMap(){
unitMap = new HashMap<Integer, String>();
//unitMap.put(287, "GROCERY SECTION MUTHALAKULM( 0287)");
}

public Map<Integer, String> getUnitMap() {
unitMap.put(287,"GROCERY SECTION MUTHALAKULM( 0287)");
unitMap.put(2002,"LITTLE TRIVENI  STORE  KOODARANJI( 2002)");
unitMap.put(2003,"LITTLE TRIVENI STORE KODANCHERY( 2003)");
unitMap.put(2750,"LITTLE TRIVENI STORE KOODATHAI( 2750)");
unitMap.put(2001,"LITTLE TRIVENI STORE KOOLIMADU( 2001)");
unitMap.put(2649,"LITTLE TRIVENI STORE PANAMARAM( 2649)");
unitMap.put(2650,"LITTLE TRIVENI STORE VAALAD( 2650)");
unitMap.put(304,"LITTLE TRIVENI SUPER STORE  K P K( 0304)");
unitMap.put(327,"LITTLE TRIVENI SUPER STORE CHERUVAD( 0327)");
unitMap.put(2538,"LITTLE TRIVENI SUPER STORE KARASSERY( 2538)");
unitMap.put(410,"LITTLE TRIVENI SUPER STORE KODUVALL( 0410)");
unitMap.put(2514,"LITTLE TRIVENI SUPER STORE MANASSERY( 2514)");
unitMap.put(619,"MINI TRIVENI STORE KULAGARA( 0619)");
unitMap.put(2648,"MINI TRIVENI STORE PANNIMUKKU( 2648)");
unitMap.put(2540,"MOBILE TRIVENI BALUSSERY( 2540)");
unitMap.put(2541,"MOBILE TRIVENI BEYPORE( 2541)");
unitMap.put(2507,"MOBILE TRIVENI CALICUT NORTH( 2507)");
unitMap.put(1893,"MOBILE TRIVENI CALICUT SOUTH( 1893)");
unitMap.put(2505,"MOBILE TRIVENI KALPETTA( 2505)");
unitMap.put(2544,"MOBILE TRIVENI KODUVALLI( 2544)");
unitMap.put(2635,"MOBILE TRIVENI KOYILANDY( 2635)");
unitMap.put(2543,"MOBILE TRIVENI KUNNAMANGALAM( 2543)");
unitMap.put(2633,"MOBILE TRIVENI KUTTIADY( 2633)");
unitMap.put(1895,"MOBILE TRIVENI MANANTHAVADY( 1895)");
unitMap.put(2542,"MOBILE TRIVENI NADAPURAM( 2542)");
unitMap.put(2632,"MOBILE TRIVENI PERAMBRA( 2632)");
unitMap.put(1892,"MOBILE TRIVENI STORE ELATHOOR( 1892)");
unitMap.put(1894,"MOBILE TRIVENI SULTHANBATHERI( 1894)");
unitMap.put(2508,"MOBILE TRIVENI THIRUVAMPADI( 2508)");
unitMap.put(2634,"MOBILE TRIVENI VATAKARA( 2634)");
unitMap.put(257,"TRIVENI DEPARTMENT COSMETICS MUTHAL( 0257)");
unitMap.put(259,"TRIVENI GIFT LAND MUTHALAKULAM( 0259)");
unitMap.put(340,"TRIVENI GODOWN  VATAKARA( 0340)");
unitMap.put(33,"TRIVENI GODOWN GROCERY( 0033)");
unitMap.put(261,"TRIVENI SUPER MARKET  VATAKARA( 0261)");
unitMap.put(430,"TRIVENI SUPER MARKET BALUSSERY( 0430)");
unitMap.put(2977,"TRIVENI SUPER MARKET EASTHILL( 2977)");
unitMap.put(325,"TRIVENI SUPER MARKET FEROKE( 0325)");
unitMap.put(2804,"TRIVENI SUPER MARKET KADIYANGAD( 2804)");
unitMap.put(422,"TRIVENI SUPER MARKET KAKKATTIL( 0422)");
unitMap.put(431,"TRIVENI SUPER MARKET KALPATTA( 0431)");
unitMap.put(260,"TRIVENI SUPER MARKET KOYILAN( 0260)");
unitMap.put(450,"TRIVENI SUPER MARKET KUNNAMANGALAM( 0450)");
unitMap.put(266,"TRIVENI SUPER MARKET MANANTHAVADY( 0266)");
unitMap.put(414,"TRIVENI SUPER MARKET MEENANGADY( 0414)");
unitMap.put(258,"TRIVENI SUPER MARKET NADAKKAVU( 0258)");
unitMap.put(432,"TRIVENI SUPER MARKET NADAPURAM( 0432)");
unitMap.put(379,"TRIVENI SUPER MARKET PAROPADI( 0379)");
unitMap.put(328,"TRIVENI SUPER MARKET PERAMBRA( 0328)");
unitMap.put(263,"TRIVENI SUPER MARKET THAMARASSERY( 0263)");
unitMap.put(3001,"TRIVENI GODOWN KARASSERY(3001)");
return unitMap;
}

public void setUnitMap(Map<Integer, String> unitMap) {
this.unitMap = unitMap;
}
}




import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Vector;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class WriteExcel {

  private WritableCellFormat timesBoldUnderline;
  private WritableCellFormat times;
  private String inputFile;
  private Vector<Vector> array = null;


  public void setOutputFile(String inputFile) {
  this.inputFile = inputFile;
  }

  public void setOutputFile(String inputFile, Vector<Vector> array) {
  this.inputFile = inputFile;
  this.array = array;
}
  
  public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet("Report");
    createLabel(excelSheet);
    createContent(excelSheet);

    workbook.write();
    workbook.close();
  }

  private void createLabel(WritableSheet sheet)
      throws WriteException {
    // Lets create a times font
    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    // Define the cell format
    times = new WritableCellFormat(times10pt);
    // Lets automatically wrap the cells
    times.setWrap(true);

    // Create create a bold font with unterlines
    WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,
        UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    // Lets automatically wrap the cells
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    cv.setFormat(timesBoldUnderline);
    cv.setAutosize(false);

    // Write a few headers
    addCaption(sheet, 0, 0, "SL No");
    addCaption(sheet, 1, 0, "Branch Name");
    addCaption(sheet, 2, 0, "Retail");
    addCaption(sheet, 3, 0, "Sbdy");
    addCaption(sheet, 4, 0, "Retail");
    addCaption(sheet, 5, 0, "Sbdy");
    addCaption(sheet, 6, 0, "Variation");
    addCaption(sheet, 7, 0, "Budget");
    addCaption(sheet, 8, 0, "Comparison");
    

  }

  private void createContent(WritableSheet sheet) throws WriteException,
      RowsExceededException {
  
  int size = array.size();
  sheet.setColumnView(1, 50);
      for(int row = 0; row < size; row ++){
  sheet.setRowView(row, 400);
  Vector val = array.get(row);
  for(int col =0; col<9;col++){
  addValues(sheet,col, row, val.get(col));
  }
}
  
  

  }

  private void addCaption(WritableSheet sheet, int column, int row, String s)
      throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
  }

  private void addNumber(WritableSheet sheet, int column, int row,
      Integer integer ) throws WriteException, RowsExceededException {
 
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
    
  }
  
  private void addValues(WritableSheet sheet, int column, int row, Object obj)
      throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, obj.toString(), times);
    sheet.addCell(label);
  }

  private void addLabel(WritableSheet sheet, int column, int row, String s)
      throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, s, times);
    sheet.addCell(label);
  }






/**
 * Budget Creator
 */
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Vector;

/**
 * Consumerfed kozhikode region
 */

/**
 * @author shimjith
 *
 */
public class BudgetCreator {
private UnitsMap unitMap = null;
private Vector<Vector> array = null; //output array
DecimalFormat decimalFormat = null;
public BudgetCreator(){
}

public int getNameFirmCode(String value) {
int firmCode = 0;
String str = value;
if(str.contains("(")&& str.contains(")")){
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
//System.out.println(true);
//System.out.println(startIndex + "--" +endIndex);
String sub = str.substring(startIndex+1, endIndex).trim();
sub = sub.trim();
//System.out.println(sub);
firmCode = Integer.parseInt(sub);
//System.out.println(" firmcode :"+firmCode);
}
return firmCode;
}


public void viewData(Map<Integer, Double> budgetData) {
// TODO Auto-generated method stub
System.out.println(" ------- Report -----------");
System.out.println(budgetData.size());
System.out.println(budgetData);
}

public Vector<Vector> calculateBudget(Map<Integer, Double> lastFinYrRetail,
Map<Integer, Double> lastFinYrSbdy,
Map<Integer, Double> newFinYrRetail,
Map<Integer, Double> newFinYrSbdy, Map<Integer, Double> budgetData) {
// TODO Auto-generated method stub
unitMap = new UnitsMap();
array = new Vector<Vector>();
Vector heading = new Vector();
heading.add("SLNO");
heading.add("BRANCH NAME");
heading.add("RETAIL");
heading.add("SBDY");
heading.add("RETAIL");
heading.add("SBDY");
heading.add("VARIATION");
heading.add("BUDGET");
heading.add("COMPARISON");
array.add(heading);
decimalFormat = new DecimalFormat("0.00");
Map map = unitMap.getUnitMap();
Vector data = null;
int serialNo = 1;
Double oldRetailTotal = 0.00;
Double oldSbdyTotal = 0.00;
Double newRetailTotal = 0.00;
Double newSbdyTotal = 0.00;
Double variationTotal = 0.00;
Double budgetTotal = 0.00;
Double comparisonTotal = 0.00;
for (Object key :map.keySet()){
data = new Vector();
int firmCode = Integer.parseInt(key.toString());
Double newRetail = newFinYrRetail.containsKey(firmCode) ? newFinYrRetail.get(firmCode) : 0.00;
Double newSbdy = newFinYrSbdy.containsKey(firmCode) ? newFinYrSbdy.get(firmCode) : 0.00;
Double oldRetail = lastFinYrRetail.containsKey(firmCode) ? lastFinYrRetail.get(firmCode) : 0.00;
Double oldSbdy = lastFinYrSbdy.containsKey(firmCode) ? lastFinYrSbdy.get(firmCode) : 0.00;
Double budgetValue = budgetData.containsKey(firmCode) ? budgetData.get(firmCode) : 0.00;
//System.out.println(firmCode +"--->"+budgetValue);
Double variation = (newRetail + newSbdy) - (oldRetail + oldSbdy);
Double comparison = budgetValue!=0 ? (newRetail + newSbdy)*100/budgetValue : 0.00;
//inserting all values to array
data.add(serialNo); //1
data.add(map.get(firmCode)); //2
data.add(Double.parseDouble(decimalFormat.format(oldRetail))); //3
data.add(Double.parseDouble(decimalFormat.format(oldSbdy))); //4
data.add(Double.parseDouble(decimalFormat.format(newRetail))); //5
data.add(Double.parseDouble(decimalFormat.format(newSbdy))); //6
data.add(Double.parseDouble(decimalFormat.format(variation))); //7
data.add(budgetValue); //8
data.add(decimalFormat.format(comparison)); //9
//Grand Total calculation
oldRetailTotal =  oldRetailTotal + Double.parseDouble(decimalFormat.format(oldRetail));
oldSbdyTotal =  oldSbdyTotal + Double.parseDouble(decimalFormat.format(oldSbdy));
newRetailTotal = newRetailTotal + Double.parseDouble(decimalFormat.format(newRetail));
newSbdyTotal =  newSbdyTotal + Double.parseDouble(decimalFormat.format(newSbdy));
variationTotal = variationTotal + Double.parseDouble(decimalFormat.format(variation));
budgetTotal = budgetTotal + budgetValue;
//System.out.println(" String : "+comparison);
comparisonTotal = comparisonTotal + Double.parseDouble(decimalFormat.format(comparison));
//System.out.println(map.get(key));
//System.out.println(" firmcode :"+ firmCode +" variation : "+Variation + "comparison : "+comparison);
serialNo = serialNo +1;
array.add(data);
}
Vector footer = new Vector();
footer.add(" ");
footer.add(" GRAND TOTAL ");
footer.add(oldRetailTotal);
footer.add(oldSbdyTotal);
footer.add(newRetailTotal);
footer.add(newSbdyTotal);
footer.add(variationTotal);
footer.add(budgetTotal);
footer.add(comparisonTotal);
array.add(footer);
return array;
}


}


dependency jar : jxl.jar


git clone : https://github.com/consumerfed/BudgetPreparation.git

June 14, 2020

June 07, 2020

Find the odd one from a non empty integer array in java

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

class Cfed{

public int singleNumber(int[] nums) {
int length = nums.length;
for (int i = 0; i < length - 1; i++) {
if (nums[i] > nums[i + 1]) {
int temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
i = -1;
}
}
int i = 0;
int ans = nums[length-1];
while (i+1 < length) {
if(nums[i]!=nums[i+1]) {
ans =  nums[i];
break;
}
i+=2;
}
return ans;
}

public static void main(String[] args) {
Cfed s = new Cfed();
int[] nums = { 4,1,2,1,2 }; 
System.out.println(s.singleNumber(nums));
}
}

May 28, 2020

Java interview questions amazon google microsoft


How to crack java interview ? 

  1. Abstraction in java

           Abstraction means we are exposing only essential parts to user, by hiding non -essential parts. For example car, rather than view individual components of car the user is viewing car as a car itself.
Abstraction is achieved in java through interface & abstract class



      2. What is system in System.out.println(); ?

         System is a class in java inside the package java.lang.package
         out is a static variable of type PrintStream
         println is a method to print message



3. What is system in JDK, JRE, JVM ?

4. Explain public static void main?

        To make java class as a main class
         Its is the entry point of java application
         public ( access specifier )  : method can be acess from anywhere from the application
        static ( keyword ) : static block / method/ keyword can be accessed before object creation
        static variable are class variables (  accessed ClassName.variableName)
        void ( empty) :  method doesnt return anything
        main : method name used to identfy the java as the entry method

5. Explain singleton?

 Only one instance of the class through out the application
 making constructor as private
public access for creation of object through a set method by checking the reference is null or not

6. Static in java?

 Static method : example connection class
Static class : Nested class ( grouping of similar class)
Static variable : can be shared among mutliple class ( example counter variable)
Static block : block of code

class Test {
    static int counter;
   
    // start of static block 
    static {
        counter = 10;
        System.out.println("static block called ");
    }
   
}









Facebook comments