July 28, 2019

Cobol to Java Convertor - A Transformation Utility application

Cobol to Java Converter - A Transformation Utility

 Trying to make an application that can effeciently converts COBOL code to Java.

This project is on going on...


The function identifies the block of codes in COBOL and categories it, based on
CobolConstants.divisionIdentifier


public Map<String,List<String>> createCodeblocks() throws IOException {
codeBlocks = new HashMap<>();
String line = null;
List<String> elements = null;
String key = null;
while (null != (line = bufferedReader.readLine())) {
if (CobolConstants.divisionIdentifier.contains(line)) {
if (null != elements) {
codeBlocks.put(key, elements);
codeConstructor(key,elements);
}
key = line;
elements = new ArrayList<>();
} else {
elements.add(line);
}
}

return codeBlocks;
}


CodeConstructor is trying to constructor java code by finding the proper class based on the identifierdivisions in COBOL

private void codeConstructor(String key, List<String> elements) {
// TODO Auto-generated method stub
switch (key) {
case "IDENTIFICATION DIVISION.":
identificationDivision = new IdentificationDivision(key, elements);
identificationDivision.getConvertedCode();
break;

default:
break;
}
}



This step create the Java code from the COBOL code given

public void getConvertedCode() {

for(String code : codes) {
if(code.contains("PROGRAM-ID")) {
String name = code.replace("PROGRAM-ID.", "").replace(".", "");
System.out.println(" public class "+getNamingUtility().createClassName(name));

}
}

}


Input

PROGRAM-ID. Iteration-If

Output

public class iterationIf



For complete code, please check my github page, feel free to contact us...



July 21, 2019

Shortest path algorithm - Dijkstra Algorithm Java source code

/**
 * Dijkstra's algorithm to find the shortest path between a and b. It picks the unvisited vertex with the lowest distance, calculates the distance through it to each unvisited neighbor, and updates the neighbor's distance if smaller.
The process that underlies Dijkstra’s algorithm is similar to the greedy process used in Prim’s algorithm. Prim’s purpose is to find a minimum spanning tree that connects all vertices in the graph; Dijkstra is concerned with only two vertices. Prim’s does not evaluate the total weight of the path from the starting vertex, only the individual path.
Breadth-first search can be viewed as a special-case of Dijkstra’s algorithm on unweighted graphs (or when all edge lengths are same).
 */
package com.cfed.alogorithm.dijkstra;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

/**
 *
 * @author Konzerntech
 * @version 1.0
 *
 */
public class DijkstraAlgorithm {


public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<>();
vertexQueue.add(source);

while (!vertexQueue.isEmpty()) {
Vertex u = (Vertex) vertexQueue.poll();  // 8281808029
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}

public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}

public static void main(String[] args) {
Vertex v0 = new Vertex("a");
Vertex v1 = new Vertex("b");
Vertex v2 = new Vertex("c");
Vertex v3 = new Vertex("d");
Vertex v4 = new Vertex("e");

Vertex[] vertices = new Vertex[5];
Edge[] ed = new Edge[4];

for (int i = 0; i < 5; i++) {
vertices[i] = new Vertex("a" + i);
for (int j = 0; j < 5; j++) {
ed[j] = new Edge(vertices[j], 10 + j);
}
}

System.out.println(vertices.length + "and " + vertices[3]);

v0.adjacencies = new Edge[] { new Edge(v1, 8), new Edge(v2, 10), new Edge(v3, 8) };
v1.adjacencies = new Edge[] { new Edge(v0, 5), new Edge(v2, 3), new Edge(v4, 7) };
v2.adjacencies = new Edge[] { new Edge(v0, 10), new Edge(v1, 3) };
v3.adjacencies = new Edge[] { new Edge(v0, 8), new Edge(v4, 12) };
v4.adjacencies = new Edge[] { new Edge(v1, 7), new Edge(v3, 2) };
Vertex[] vertices1 = { v0, v1, v2, v3, v4 };



for (Vertex v : vertices1) {
System.out.println("Distance to the vertex ( " + v + ") is : " + v.minDistance);
List<?> path = getShortestPathTo(v);
System.out.println("Shortest path: " + path);
System.out.println(" Dijkstra algorithm to compute shortest distance ");

}

computePaths(vertices[0]);

for (Vertex v : vertices) {
System.out.println("Distance to the vertex ( " + v + ") is : " + v.minDistance);
List<?> path = getShortestPathTo(v);
System.out.println("Shortest path: " + path);
System.out.println(" Dijkstra algorithm to compute shortest distance ");
}
}
}


package com.cfed.alogorithm.dijkstra;
/**
 *
 * @author Cfed
 *
 */
class Edge {


public final Vertex target;
public final double weight;

public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}


package com.cfed.alogorithm.dijkstra;
/**
 *
 * @author Cfed
 *
 */
public class Vertex implements Comparable<Vertex> {

public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;

public Vertex(String name) {
this.name = name;
}

public String toString() {
return name;
}

public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}


How to handle NumberFormatException: For input string: "0.0" : Next on blogpost

July 14, 2019

Moving Robot Html Javascript code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>AI Robot</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var robotHead;
var robotBody;
var robotLegOne;
var robotLegTwo;
var robotHandOne;
var robotHandTwo;

function startGame() {
robotHead = new robotHeadComp(100, 100, "#8ED6FF", 50, 50);
robotBody = new robotBodyComp(100, 200, "blue", 50, 150);
robotLegOne = new robotBodyComp(25, 200, "blue", 50, 250);
robotLegTwo = new robotBodyComp(25, 200, "blue", 125, 250);
robotHandOne = new robotBodyComp(25, 25, "blue", 150, 150);
robotHandTwo = new robotBodyComp(25, 25, "blue", 25, 150);
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 900;
        this.canvas.height = 500;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
    },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function robotHeadComp(width, height, color, x, y) {
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;   
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.strokeStyle = "black";
        ctx.stroke();
    }
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;       
    }   
}

function robotBodyComp(width, height, color, x, y) {
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;   
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;       
    }   
}

function updateGameArea() {
    myGameArea.clear();
    robotHead.newPos();   
    robotHead.update();
    robotBody.newPos();   
    robotBody.update();
    robotLegOne.newPos();   
    robotLegOne.update();
    robotLegTwo.newPos();   
    robotLegTwo.update();
    robotHandOne.newPos();   
    robotHandOne.update();
    robotHandTwo.newPos();   
    robotHandTwo.update();
}

function moveup() {
robotHead.speedY -= 1;
}

function movedown() {
robotHead.speedY += 1;
}

function moveleft() {
robotHead.speedX -= 1;
}

function moveright() {
robotHead.speedX += 1;
robotBody.speedX += 1;
robotLegOne.speedX += 1;
robotLegTwo.speedX += 1;
robotHandOne.speedX += 1;
robotHandTwo.speedX += 1;
}

function chargeBattery(){

}
</script>

<div style="text-align:center;width:480px;">
  <button onclick="chargeBattery()">charge Battery</button><br>
<!--   <button onclick="moveup()">UP</button><br><br> -->
<!--   <button onclick="moveleft()">LEFT</button> -->
  <button onclick="moveright()">Walk</button><br><br>
<!--   <button onclick="movedown()">DOWN</button> -->
</div>


</body>
</html>

July 07, 2019

Artificial intelligence robot in java a prototype

Artificial intelligence robot in java a prototype




/**
 * @author Consumerfed I T Section
 *
 */
public class MainClass {

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

}

}

/**
 *
 */
package com.consumerfed.airobo.model;

import com.consumerfed.airobo.utilities.RoboMessages;

/**
 * @author Conumerfed I T Section
 *
 */
public class AIRobot {

private boolean alert = false;

private RoboMessages message = null;

private float batteryStatus = 0;

private float weightCarried = 0;

private float distanceCovered = 0;

public float getBatteryStatus() {
return batteryStatus;
}

public void setBatteryStatus(float batteryStatus) {
this.batteryStatus = batteryStatus;
}

public RoboMessages getMessage() {
if (null == message) {
message = RoboMessages.NILL;
}
return message;
}

public void setMessage(RoboMessages message) {
this.message = message;
}

public float getWeightCarried() {
return weightCarried;
}

public void setWeightCarried(float weightCarried) {
this.weightCarried = weightCarried;
}

public boolean isAlert() {
return alert;
}

public void setAlert(boolean alert) {
this.alert = alert;
}

public float getDistanceCovered() {
return distanceCovered;
}

public void setDistanceCovered(float distanceCovered) {
this.distanceCovered = distanceCovered;
}

}

package consumerfed.xebia.airobo.model;
/**
 * @author Conumerfed I T Section
 *
 */
public class Barcode {
private String code = null;
private byte[] img = null;
private double price = 0;

public byte[] getImg() {
return img;
}

public void setImg(byte[] img) {
this.img = img;
}

public String getCode() {
return "ISBN 8281808025";
}

public double getPrice() {
return 120.75;
}

}



package com.Consumerfed.airobo.service;

import com.Consumerfed.airobo.model.AIRobot;
import com.Consumerfed.airobo.model.Barcode;
import com.Consumerfed.airobo.utilities.AIRobotUtilities;
import com.Consumerfed.airobo.utilities.RoboMessages;

/**
 * @author Consumerfed
 *
 */
public class AIRobotService implements AIRobotServiceInf, Scanning {

private AIRobot robot = null;

public AIRobotService(AIRobot robot) {
this.robot = robot;
}

@Override
public float walk(float kilometer) {
if (loadWeight(robot.getWeightCarried()) && checkBatteryStatus() && checkMaxDistance(kilometer)) {
if(isChargeExist(kilometer)) {
batteryConsumption(kilometer, robot.getWeightCarried());
float distanceCovered = robot.getDistanceCovered();
robot.setDistanceCovered(kilometer+ distanceCovered);
}
}
checkBatteryStatus();
display();
return robot.getBatteryStatus();
}

private boolean isChargeExist(float kilometer) {
boolean isChargeExistForMove = false;
float weight = robot.getWeightCarried();
float extraChargeConsumed = weight * AIRobotUtilities.EXTRA_REDUCE_PKM_WGT;
float chargeConsume = kilometer * (AIRobotUtilities.BATTERY_CONSUMPTION_PKM + extraChargeConsumed);
float charge = robot.getBatteryStatus();
if((charge)>= chargeConsume) {
isChargeExistForMove = true;
}
return isChargeExistForMove;
}

private void batteryConsumption(float kilometer, float weight) {
float charge = robot.getBatteryStatus();
float extraChargeConsumed = weight * AIRobotUtilities.EXTRA_REDUCE_PKM_WGT;
float chargeConsumed = kilometer * (AIRobotUtilities.BATTERY_CONSUMPTION_PKM + extraChargeConsumed);
float remainingCharge = charge - chargeConsumed;
robot.setBatteryStatus(remainingCharge < 0 ? 0 : remainingCharge);
}

@Override
public float walkWithWeight(float kilometer, float kilogram) {
if (loadWeight(kilogram))
walk(kilometer);
return robot.getBatteryStatus();
}

@Override
public boolean loadWeight(float kilogram) {
float weightCarried = robot.getWeightCarried();
float totalWeight = weightCarried + kilogram;
boolean isNormalWeight = true;
if (totalWeight > 10) {
robot.setMessage(RoboMessages.OVERWEIGHT);
isNormalWeight = false;
}
robot.setWeightCarried(totalWeight);
return isNormalWeight;
}

@Override
public void chargeBattery() {
if (robot.getBatteryStatus() == 100) {
robot.setMessage(RoboMessages.FULL_CHARGE);
robot.setAlert(false);
display();
} else {
System.out.println(" Battery charging..");
try {
Thread.sleep(2512);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Fully charged ");
}
robot.setDistanceCovered(0);
robot.setBatteryStatus(100);
}

@Override
public void removeLoad() {
if (robot.getWeightCarried() == 0) {
robot.setMessage(RoboMessages.EMPTY_LOAD);
robot.setAlert(false);
display();
}
robot.setWeightCarried(0);
}

private boolean checkBatteryStatus() {
float batteryCharge = robot.getBatteryStatus();
if (batteryCharge == 0) {
robot.setMessage(RoboMessages.EMPTY_BATTERY);
robot.setAlert(true);
return false;

} else if (batteryCharge < 15) {
robot.setMessage(RoboMessages.RESEVE_BATTERY);
robot.setAlert(true);
return false;
}
return true;
}

private boolean checkMaxDistance(float kilometer) {
if (calcMaxMilege(kilometer) < kilometer) {
robot.setMessage(RoboMessages.MAX_DISTANCE_EXCEED);
return false;
}
return true;
}

private float calcMaxMilege(float kilometer) {
float weight = robot.getWeightCarried();
float maxMilege = 100
/ (AIRobotUtilities.BATTERY_CONSUMPTION_PKM + (AIRobotUtilities.EXTRA_REDUCE_PKM_WGT * weight));
return maxMilege;
}

private void display() {
System.out.println("Light on Robot head : \t" + (robot.isAlert() ? "Red" : " "));
System.out.println("Led display on Robot chest : \t" + robot.getMessage().getMessage());
System.out.println("Battery Remaining :\t" + robot.getBatteryStatus());
}

@Override
public double scan(Barcode barcode) {
double price = 0;
System.out.println("scanning");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (checkBarcodeImg(barcode)) {
price = barcode.getPrice();
System.out.println("Price display on Robot  : \t" + price);
} else {
robot.setMessage(RoboMessages.SCAN_FAILED);
display();
}
return price;
}

/**

* @param barcode
* @return
*/
private boolean checkBarcodeImg(Barcode barcode) {
// if(barcode.getImg())
return true;
}

}

package com.consumerfed.airobo.service;

public interface AIRobotServiceInf {
public float walk(float kilometer);
public float walkWithWeight(float kilometer, float kilogram);
public boolean loadWeight(float kilogram);
public void chargeBattery();
public void removeLoad();

}

/**
 * 
 */
package com.consumerfed.airobo.service;

import com.consumerfed.airobo.model.Barcode;

/**
 * @author consumerfed Information Technology
 *
 */
public interface Scanning {
public double scan(Barcode barcode);

}


package com.cosumerfed.airobo.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.consumerfed.airobo.model.AIRobot;
import com.consumerfed.airobo.model.Barcode;
import com.consumerfed.airobo.service.AIRobotService;
import com.consumerfed.airobo.service.AIRobotServiceInf;
import com.consumerfed.airobo.service.Scanning;

public class AIRobotTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
// System.setOut("");
}

// Robot carries 12 KG
@Test
public void OverweightTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
assertEquals(false, tester.loadWeight(12));
}

@Test
public void NormalTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
assertTrue(tester.loadWeight(9.5f));
}

// Robot walks 3.5 kilometers
@Test
public void WalkBatteryValidTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
tester.chargeBattery();
assertEquals(30.0, tester.walk(3.5f), 0.0001);
}

@Test
public void WalkWithoutCharingTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
assertEquals(00.0, tester.walk(3.5f), 0.0001);
}

// Robot walks for 2Km carrying 3 kg
@Test
public void WalkWithWeighValidTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
tester.chargeBattery();
assertEquals(36.0, tester.walkWithWeight(2, 3), 0.0001);
}
@Test
public void robotScanTest() {
Barcode barcode = new Barcode();
AIRobot robot = new AIRobot();
Scanning tester = new AIRobotService(robot);
assertEquals(120.75, tester.scan(barcode), 0.0001);
}
@Test
public void successiveWalkTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
tester.chargeBattery();
tester.walk(3);
assertEquals(0.0, tester.walk(2), 0.0001);
}
@Test
public void walkAboveMaxDistanceTest() {
AIRobot robot = new AIRobot();
AIRobotServiceInf tester = new AIRobotService(robot);
tester.chargeBattery();
assertEquals(100.0, tester.walk(6), 0.0001);
}

}

package com.consumerfed.airobo.utilities;

public class AIRobotUtilities {
public static final float MAX_MILEAGE = 5;

// BATTERY RESERVICE IN PERCENAGE
public static final float BATTERY_RESERVE = 15;

// EXTRA PERCENTAGE REDUCTION PER KILO METER
public static final float EXTRA_REDUCE_PKM_WGT = 2;

// private battery consumption per kilo meter
public static final float BATTERY_CONSUMPTION_PKM = 20;

// WEIGHT IN KILO GRAM
public static final float MAX_WEIGHT = 10;

}

/**
 * 
 */
package com.consumerfed.airobo.utilities;

/**
 * @author Consumerfed
 *
 */
public enum RoboMessages {
OVERWEIGHT("OVERWEIGHT"),
FULL_CHARGE("BATTERY FULL CHARGED"),
EMPTY_LOAD("LOAD IS EMPTY"),
EMPTY_BATTERY("BATTERY IS EMPTY"),
MAX_DISTANCE_EXCEED("MAXIMUM DISTANCE EXCEEDED"), 
RESEVE_BATTERY("BATTERY IN RESERVE"),
NILL(""), SCAN_FAILED("SCAN FAILURE");

private String message;

public String getMessage() {
return this.message;
}

private RoboMessages(String message) {
this.message = message;
}

}


Facebook comments