Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

July 07, 2022

How to use observable pattern to notify stock market breakouts entry stoploss


Created a stock market application by implementing observable pattern.
In observable pattern the subsribers will be notified when ever there is any event occured in publishers object. In our example stock is the publisher ( Observables) and we kept a list of subscribers list in NotificationManager class.



Stock.java


package com.learning.designpattern.observer;

import java.io.File;
/**
 * Stock class
 * Act as Observable or publisher
 * 
 * Where ever a change happens in Stock object (publisher), it will notifies the subscribers
 * 
 * two methods stoploss() & entry() corresponds to file opening and saving events
 * 
 *
 * 
 * 
 * @author smithesh k k
 *
 */
public class Stock {

private Breakout breakout;
public NotificationManager events;

public Stock() {
this.events = new NotificationManager(); 
}

public void stoploss(String nseTicker) {
if (!nseTicker.isEmpty()) {
this.breakout = new Breakout(nseTicker);
events.notify(Alerts.STOPLOSS.toString(), breakout);
}
}

public void entry(String nseTicker) {
if (!nseTicker.isEmpty()) {
this.breakout = new Breakout(nseTicker);
events.notify(Alerts.ENTRY.toString(), breakout);
}
}

}

NotificationManager.java


/**
 * 
 */
package com.learning.designpattern.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  NotificationManager
 *  
 *  keeps the subscriber list ( watchlist), through NotificationManager you can subscribe or unsusbscribe for an event
 *  
 *  notify() helps to notify the subscribers/observer's
 * 
 * 
 * @author bijuvas
 *
 */
public class NotificationManager {

private Map<String, List<EventListener>> watchlist;
public NotificationManager() {
this.watchlist = new HashMap<>();
addEvents();
}
public void notify(String eventType, Breakout file) {
List<EventListener> users = watchlist.get(eventType);
users.forEach(user -> {
user.update(eventType, file);
});
}
public void subscribe(String eventType, EventListener listener) {
List<EventListener> users = watchlist.get(eventType);
users.add(listener);
}
public void unsubscribe(String eventType, EventListener listener) {
List<EventListener> users = watchlist.get(eventType);
users.remove(listener);
}

public void addEvents() {
final Alerts[] alerts = Alerts.values();
for (Alerts event : alerts) {
            this.watchlist.put(event.toString(), new ArrayList<>());
        }
}
}

EventListener.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * EventListener
 * 
 * update()
 * 
 * @author sreekumar
 *
 */
public interface EventListener {
public void update(String eventType, Breakout breakout);
}


EmailNotificationListener.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * EmailNotificationListener
 * 
 * @author perambra kozhikode
 *
 */
public class EmailNotificationListener implements EventListener {
private String email;
public EmailNotificationListener(String email) {
this.email = email;
}

@Override
public void update(String eventType, Breakout breakout) {
System.out.println(" email send to "+email +" for "+eventType);
}

}


MainClass.java


/**
 * 
 */
package com.learning.designpattern.observer;

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

/**
* @param args
*/
public static void main(String[] args) {
Stock editor = new Stock();
NotificationManager event = editor.events;
event.subscribe(Alerts.STOPLOSS.toString(), new EmailNotificationListener("test@gmail.com"));
editor.stoploss("SGX");
}

}


Breakout.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * @author Zamorins Guruvayoorappan college
 *
 */
public class Breakout{  //implements Strategies{

public Breakout(String nseTicker) {
} 

}


Alerts.java


/**
 * 
 */
package com.learning.designpattern.observer;

/**
 * @author lijesh
 *
 */
public enum Alerts {
TARGET1, ENTRY, TARGET2, STOPLOSS;

}


Full source code


Git url
 

June 27, 2022

Sources must not be empty | java.lang.IllegalArgumentException | Spring boot application

Issue reported


2022-06-27 16:13:04.789  INFO 6348 --- [           main] o.s.boot.SpringApplication               : Starting SpringApplication v2.6.0 using Java 11.0.7 on apple-pc with PID 6348 (E:\Aswathi\maven_repo\org\springframework\boot\spring-boot\2.6.0\spring-boot-2.6.0.jar started by aswathi in E:\Aswathi\repo\stockmaster\nyseticker)
2022-06-27 16:13:04.793  INFO 6348 --- [           main] o.s.boot.SpringApplication               : No active profile set, falling back to default profiles: default
2022-06-27 16:13:04.828 ERROR 6348 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalArgumentException: Sources must not be empty
at org.springframework.util.Assert.notEmpty(Assert.java:470) ~[spring-core-5.3.13.jar:5.3.13]
at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:403) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:301) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.main(SpringApplication.java:1317) ~[spring-boot-2.6.0.jar:2.6.0]

Solution

Go to class where you have your @SpringBootApplication and right click -> run as java application.



  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.0)

2022-06-27 16:19:32.454  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : Starting NysetickerApplication using Java 11.0.7 on apple-pc with PID 3160 (E:\Aswathi\repo\stockmaster\nyseticker\target\classes started by apple in E:\Aswathi\repo\stockmaster\nyseticker)
2022-06-27 16:19:32.460  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : No active profile set, falling back to default profiles: default
2022-06-27 16:19:34.141  INFO 3160 --- [           main] c.p.nyseticker.NysetickerApplication     : Started NysetickerApplication in 2.955 seconds (JVM running for 4.258)



December 21, 2021

Find missing number in a sequence Minimum complexity | n Log n

/**
 * Find missing number in a sequence Minimum complexity (n Log n)
 * 
 * input : {1,2,3,5}
 * output : 4
 */
package com.codecreeks.solutions;

import java.util.Arrays;

/**
 * @author Consumerfed Information Technology Section
 *
 */
public class MissingNumberArray {
private static int loopCount = 0;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int[] a = {1,2,3,4,6,7,8,9,10,11,12};
int len = a.length;
MissingNumberArray m = new MissingNumberArray();
int value = 0;
if(a[len-1]!=len) {
value = m.findMissingNumber(a, 0, len);
System.out.println(" The Missing number in the array :"+Arrays.toString(a)+" is "+value);
}else {
loopCount++;
System.out.println(" There is no missing number in the given array "+Arrays.toString(a));
}
System.out.println(" For "+len+" size array it tooks "+loopCount+" search to find the answer ");
System.out.println(" Complexity :"+len*Math.log(len));
System.out.println(" Time Taken : "+(System.currentTimeMillis() - startTime)+" ms");
}
private int findMissingNumber(int[] array, int startPstn, int endPstn) {
loopCount++;
int arraySize = endPstn - startPstn;
int position = startPstn + arraySize / 2;
if(arraySize==0) {
return position +1;
}else if (arraySize == 1) {
return array[position] + 1;
}
else if (array[position] != position + 1) {
return findMissingNumber(array, startPstn, position);
} else {
return findMissingNumber(array, position + 1, endPstn);
}
}
}

December 14, 2021

Squaring and Sorting an input array contains negative and positive number | complexity

/**
 * Squaring and Sorting an input array contains negative and positive number
 * 
 * Complexity O(2n)
 * 
 */
package consumerfed;

import java.util.Arrays;

/**
 * @author konzerntech
 *
 */
public class SquareAndSort {

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

int[] input = { -10, -8, -3, -1, 4, 6, 8 };
int len = input.length;
int[] output = new int[len];

int[] a = new int[len];
int[] b = new int[len];

int aLen = 0;
int bLen = 0;

for (int i = 0; i < len; i++) {
int value = input[i];
int square = value * value;
if (value < 0) {
a[aLen] = square;
aLen++;
} else {
b[bLen] = square;
bLen++;
}
}

int aPtr = aLen-1;
int bPtr = 0;


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

if (bPtr > (bLen - 1)) {
while (aPtr >= 0) {
output[i] = a[aPtr];
i++;
aPtr--;
}
break;
}

if (aPtr < 0) {
while (bPtr < bLen) {
output[i] = b[bPtr];
i++;
bPtr++;
}
break;
}

if (b[bPtr] < a[aPtr]) {
output[i] = b[bPtr];
bPtr++;
} else {
output[i] = a[aPtr];
aPtr--;
}

}
System.out.println("Input : "+Arrays.toString(input));
System.out.println("Output : "+Arrays.toString(output));
}

}

August 07, 2021

Tikdata coding test solution



input txt is a file  with data known as ‘tickData’. This file consists of several columns. For this question we will consider only "STOCK","LTP","TIME" columns. Rest columns and values

can be ignored.
There are two task you need to perform :

TASK 1 : Convert tickData file in OHLC File :

tick data is the price of the particular stock at any given time. you need to group the data for each stock for each minute and find its Open (first price in that minute) ,
High (highest price in that minute), Low (lowest price in that minute), close(last price of that minute) for that minute. This is called OHLC (open/high/low/close) data.

In a minute we can receive the price of the stocks for upto 100 times.(Not fixed)
e.g.

"STOCK" "LTP" "TIME"
"NQ" 6972.75 08.11.51.319 AM
"NQ" 6974.25 08.12.12.761 AM
"NQ" 6975.25 08.12.42.728 AM
"NQ" 6973.75 08.13.12.700 AM
"NQ" 6974.25 08.13.42.768 AM


For given input above, Output will be

STOCK Open High Low Close TIME
NQ 6972.75 6972.75 6972.75 6972.75 01-NOV-18 08.11.00.00 AM
NQ 6974.25 6975.25 6974.25 6975.25 01-NOV-18 08.12.00.00 AM
NQ 6973.75 6974.25 6973.75 6974.25 01-NOV-18 08.13.00.00 AM

Basically take all prices for the stock in a particular minute, Find its open, high, low, close and print it along with a time and stock name (tab separated).

TASK 2 :

Now since you have OHLC data with you from step 1, you need to calculate the zScore for the stocks. please follow the steps given below to find the zScore of the stocks at a given minute.

1. At any given minute, take the last 20 close prices for that stock. e.g. If we're calculating zScore for 08:20:00 AM , we will take all close prices for the stock from 08:00:00 to 08:19:00.
2. Since we have a list of the last 20 close prices, we will calculate average and standard deviation of the close prices.
3. Now we have average and standard deviation of last 20 prices and current minutes data as well. so zScore = (current_close - average)/standard_deviation;

e.g.
Consider from Task 1 you got the following OHLC data. (This is sample Data only for explanation and not actual data)

Stock open high low close time
NQ 100 100.2 99 100.2 01-NOV-18 09.10.00.00 AM
NQ 100 101.2 99 101.2 01-NOV-18 09.11.00.00 AM
NQ 100 100.2 99 99 01-NOV-18 09.12.00.00 AM
NQ 100 100.2 99 100 01-NOV-18 09.13.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.14.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.15.00.00 AM
NQ 100 100.2 99 100 01-NOV-18 09.16.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.17.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.18.00.00 AM
NQ 100 103 99 103 01-NOV-18 09.19.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.20.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.21.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.22.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.23.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.24.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.25.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.26.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.27.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.28.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.29.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.30.00.00 AM

Now if we wish to calculate zScore at 01-NOV-18 09.30.00.00 AM, We will take previous 20 close prices i.e. From 01-NOV-18 09.10.00.00 AM to 01-NOV-18 09.29.00.00 AM.
Calculate average of the prices and standard_deviation for the same.
average = 100.31
standard_deviation = 0.72974
zScore  = (100.2-100.31)/0.72974 = -1.5073


Output should be:

Stock zScore time
NQ -1.5073 01-NOV-18 09.30.00.00 AM
and so on.


Solution



#MygDigital cheating

July 28, 2021

Parking lot - problem and solution

Problem Statement I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is given a number starting at 1 increasing with increasing distance from the entry point in steps of one. I want to create an automated ticketing system that allows my customers to use my parking lot without human intervention. When a car enters my parking lot, I want to have a ticket issued to the driver. The ticket issuing process includes us documenting the registration number (number plate) and the colour of the car and allocating an available parking slot to the car before actually handing over a ticket to the driver (we assume that our customers are nice enough to always park in the slots allocated to them). The customer should be allocated a parking slot which is nearest to the entry. At the exit the customer returns the ticket with the time the car was parked in the lot, which then marks the slot they were using as being available. Total parking charge should be calculated as per the parking time. Charge applicable is $10 for first 2 hours and $10 for every additional hour. We interact with the system via a simple set of commands which produce a specific output.

 Please take a look at the example below, which includes all the commands you need to support - they're self explanatory


The system should accept a filename as a parameter at the command prompt and read the commands from that file. 

Example: File To install all dependencies, compile and run tests: $ bin/setup To run the code so it accepts input from a file: $ bin/parking_lot file_inputs.txt Commands 

• Create parking lot of size n : create_parking_lot {capacity} 
• Park a car : park {car_number} 
• Remove(Unpark) car from : leave {car_number} {hours} 
• Print status of parking slot : status Input (contents of file): create_parking_lot 6 park K
A-01-HH-1234 park 
KA-01-HH-9999 
park KA-01-BB-0001 
park KA-01-HH-7777 
park KA-01-HH-2701 
park KA-01-HH-3141 
leave KA-01-HH-3141 4 
status park KA-01-P-333 
park DL-12-AA-9999 
leave KA-01-HH-1234 4 
leave KA-01-BB-0001 6 
leave DL-12-AA-9999 2 
park KA-09-HH-0987 
park CA-09-IO-1111 
park KA-09-HH-0123 
status 
Output (to STDOUT): Created parking lot with 6 slots Allocated slot number: 1 Allocated slot number: 2 Allocated slot number: 3 Allocated slot number: 4 Allocated slot number: 5 Allocated slot number: 6 Registration number KA-01-HH3141 with Slot Number 6 is free with Charge 30 Slot No. Registration No. 1 KA-01-HH-1234 2 KA-01-HH-9999 3 KA-01-BB-0001 4 KA-01-HH-7777 5 KA-01-HH-2701 Allocated slot number: 6 Sorry, parking lot is full Registration number KA-01-HH1234 with Slot Number 1 is free with Charge 30 Registration number KA-01-BB0001 with Slot Number 3 is free with Charge 50 Registration number DL-12-AA-9999 not found Allocated slot number: 1 Allocated slot number: 3 Sorry, parking lot is full Slot No. Registration No. 1 KA-09-HH-0987 2 KA-01-HH-9999 3 CA-09-IO-1111 4 KA-01-HH-7777 5 KA-01-HH-2701 6 KA-01-P-333

January 07, 2021

Coding test -parking lot problem solved

problem

I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is given a number starting at 1 increasing with increasing distance from the entry point in steps of one. I want to create an automated ticketing system that allows my customers to use my parking lot without human intervention. When a car enters my parking lot, I want to have a ticket issued to the driver. The ticket issuing process includes us documenting the registration number (number plate) and the colour of the car and allocating an available parking slot to the car before actually handing over a ticket to the driver (we assume that our customers are nice enough to always park in the slots allocated to them). The customer should be allocated a parking slot which is nearest to the entry. At the exit the customer returns the ticket with the time the car was parked in the lot, which then marks the slot they were using as being available. Total parking charge should be calculated as per the parking time. Charge applicable is AED 100 for first 2 hours and AED100 for every additional hour. We interact with the system via a simple set of commands which produce a specific output. Please take a look at the example below, which includes all the commands you need to support - they're self explanatory. The system should accept a filename as a parameter at the command prompt and read the commands from that file.

Solution

git hub url

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



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;
}

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));

}

}

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

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

Facebook comments