I write vba macros, that create file in random access mode:
Private Type Record
id As Long
name As String * 20
status As String * 10
End Type
Private rec As Record
Private rows_count As Long
Private datfilePath As String
Private Sub writeButton_Click()
datfilePath = ThisWorkbook.Path + "\data\datfile.dat"
datfile = FreeFile()
Open datfilePath For Random As #datfile Len = Len(rec)
rows_count = Int(LOF(datfile) / Len(rec))
rec.id = rows_count + 1
rec.name = "test_name_" + Str(rows_count + 1)
rec.status = "test_sta" + Str(rows_count + 1)
Put #datfile, rows_count + 1, rec
rows_count = Int(LOF(datfile) / Len(rec))
Close #datfile
End Sub
how to read created file in java?
in result:
import java.io.*;
class ReadVBFile {
public static void main(String[] args) throws IOException{
try
{
String file = "datfile.dat";
RandomAccessFile fh = new RandomAccessFile(file,"r");
int file_length =(int)fh.length();
int rec_length = 34;
int rec_count = (int)(file_length/rec_length);
System.out.println("file_length: " + file_length + "\r\n");
System.out.println("rec_count: " + rec_count + "\r\n");
for( int i_row=0; i_row < rec_count; i_row++ )
{
byte[] id_array = new byte[4];
byte[] name_array = new byte[20];
byte[] status_array = new byte[10];
for( int i=0; i < 34; i++ )
{
byte b = fh.readByte();
if( i < 4 )
{
id_array[i] = b;
}
else if( i < 24 )
{
name_array[i-4] = b;
}
else if( i < 34 )
{
status_array[i-24] = b;
}
fh.seek( i_row*34 + i + 1 );
}
// Long as Int
int myInt = ((id_array[1] & 0xff) << 24) | ((id_array[2] & 0xff) << 16) | ((id_array[3] & 0xff) << 8) | (id_array[0] & 0xff);
String name_value = new String(name_array);
String status_value = new String(status_array);
System.out.println( myInt + ", '" + name_value + "', '" + status_value + "'");
}
}
catch(IOException e)
{
System.out.println( "IOException: " + e.getMessage() );
}
catch(Exception e)
{
System.out.println( "Exception: " + e.getMessage() );
}
}
}
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
I have tried many sample codes to parse APDU response to TLV format.
I am able to parse it properly if the response length is less but facing issue if length is more(how calculate length of a tag without any libraries)
NOTE: I am using predefined tags in Constants
code:
private HashMap<String, String> parseTLV(String apduResponse) {
HashMap<String, String> tagValue = new HashMap<>();
String remainingApdu = apduResponse.replaceAll(" ", "");
if (remainingApdu.endsWith(ResponseTags._SUCCESS_STATUSWORDS)) {
remainingApdu = remainingApdu.substring(0, remainingApdu.length() - 4);
}
while (remainingApdu != null && remainingApdu.length() > 2) {
remainingApdu = addTagValue(tagValue, remainingApdu);
}
return tagValue;
}
addTagValue method
private String addTagValue(HashMap<String, String> tagValue, String apduResponse) {
String tag = "";
String length = "";
String value = "";
int tagLen = 0;
if (tagUtils.isValidTag(apduResponse.substring(0, 2))) {
tagLen = readTagLength(apduResponse.substring(3));
// tagLen = 2;
tag = apduResponse.substring(0, 2);
} else if (tagUtils.isValidTag(apduResponse.substring(0, 4))) {
tagLen = 4;
tag = apduResponse.substring(0, 4);
} else {
return "";
}
Log.e("TAG_LEN","tag: "+tag+"taglen: "+tagLen);
if (tagUtils.shouldCheckValueFor(tag)) {
length = apduResponse.substring(tagLen, tagLen + 2);
int len = tagUtils.hexToDecimal(length);
value = apduResponse.substring(tagLen + 2, (len * 2) + tagLen + 2);
tagValue.put(tag, value);
if (ResponseTags.getRespTagsmap().containsKey(tag)) {
//logData = logData + "\nKEY:" + tag + " TAG:" + ResponseTags.getRespTagsmap().get(tag)/* + " VALUE:" + value + "\n "*/;
}
if (tagUtils.isTemplateTag(tag)) {
// logData = logData + "\n\t-->";
return addTagValue(tagValue, value) + apduResponse.substring(tag.length() + value.length() + length.length());
} else {
return apduResponse.substring(tag.length() + value.length() + length.length());
}
} else {
value = apduResponse.substring(2, 4);
tagValue.put(tag, value);
// logData = logData + "\n\t\tKEY:" + tag + " TAG:" + ResponseTags.getRespTagsmap().get(tag) /*+ " VALUE:" + value + "\n "*/;
return apduResponse.substring(tag.length() + value.length() + length.length());
}
}
readTagLength :
private int readTagLength(String apduResponse) {
int len_bytes = 0;
if (apduResponse.length() > 2) {
len_bytes = (apduResponse.length()) / 2;
}
Log.e("tlv length:", "bytes:" + len_bytes);
if (len_bytes < 128) {
return 2;
} else if (len_bytes > 127 && len_bytes < 255) {
return 4;
} else {
return 6;
}
}
I cannot able to get length properly for few cards(if apdu response is long)
Please help
First be sure the input data is proper before you go into the code. Take the full data and try it on https://www.emvlab.org/tlvutils/ .
Once its confirmed the data is proper, go through in EMV 4.3 Book 3,
Annex B Rules for BER-TLV Data Objects sections B1, B2, B3 - with utmost attention.
If you follow this precisely, then you wouldn't need to store a static list of tags; will save time in future.
Below sample has an assumption that TLV array is ending with special 0x00 tag but for sure you can ignore it.
Pojo class :
public class Tlv {
private short tag;
private byte[] value;
public Tlv(short tag) {
this.tag = tag;
}
public short getTag() {
return tag;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] valueBytes) {
this.value = valueBytes;
}
}
Utility method :
public static Map<Byte, Tlv> parse(ByteBuffer bb) throws TlvException {
Map<Byte, Tlv> tlvs = null;
tlvs = new HashMap<Byte, Tlv>();
try {
while (bb.remaining() > 0) {
byte tag = bb.get();
if(tag == 0x00)
continue;
int length = bb.get();
byte[] value = new byte[length];
bb.get(value, 0, length);
Tlv tlv = new Tlv(tag);
tlv.setValue(value);
tlvs.put(tag, tlv);
}
} catch (IndexOutOfBoundsException e) {
throw new TlvException("Malformed TLV part: " + bb.toString() + ".", e);
}
return tlvs;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello I have been working on a program that predicts numbers. I have went through the code several times now and edited it. For some reason teamOneScored is ALWAYS higher than teamTwoScored. This does not make any sense to me.
What is the error that is occurring?
Here is my CompareEngine Class:
package compare;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import data.Main;
public class CompareEngine
{
public static void Comparison(int firstTeamTotal, int secondTeamTotal,
int[] firstPositionAmount, int[] secondPositionAmount, int[]
firstPosition, int[] secondPosition)
{
System.out.println(" Comparisons:");
System.out.println("----------------------------------------");
System.out.println(Main.firstTeam + " vs. " + Main.secondTeam);
System.out.println("----------------------------------------");
System.out.println(firstTeamTotal + " Total " + " " + secondTeamTotal);
System.out.println("");
System.out.println(firstPosition[0]-1+"-"+firstPosition[1]+"-"+firstPosition[2] + " Formation " + (secondPosition[0]-1) +"-"+secondPosition[1]+"-"+secondPosition[2]);
System.out.println("");
System.out.println(firstPosition[0] + " Defenders " + " " + secondPosition[0]);
System.out.println(firstPositionAmount[0] + " Defense Total " + " " + secondPositionAmount[0]);
System.out.println("");
System.out.println(firstPosition[1] + " Midfielders " + " " + secondPosition[1]);
System.out.println(firstPositionAmount[1] + " Midfield Total " + " " + secondPositionAmount[1]);
System.out.println("");
System.out.println(firstPosition[2] + " Attackers " + " " + secondPosition[2]);
System.out.println(firstPositionAmount[2] + " Attack Total " + " " + secondPositionAmount[2]);
}
public static void RunGame(int firstTeamTotal, int secondTeamTotal, int[] firstPositionAmount,
int[] secondPositionAmount, int[] firstPosition, int[] secondPosition) throws IOException
{
int depth;
System.out.println("What depth do you want to run?");
depth = Main.read.nextInt();
int firstShotCount = 0;
int secondShotCount = 0;
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
while(firstAttack*3 > secondDefense)
{
firstShotCount = firstShotCount + 1;
firstAttack = firstAttack - 5;
}
while(secondAttack*3 > firstDefense)
{
secondShotCount = secondShotCount + 1;
secondAttack = secondAttack - 5;
}
System.out.println(firstShotCount);
System.out.println(secondShotCount);
PossessionControl(Main.firstTeam, Main.secondTeam);
int[] teamOneScored = new int[99];
int[] teamTwoScored = new int[99];
int[] oneShotOn = new int[99];
int[] twoShotOn = new int[99];
int[] OnePossession = new int[99];
int[] TwoPossession = new int[99];
Random random = new Random();
for(int i = 0; i < depth; i++)
{
for(int x = 0; firstShotCount >= x; x++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamOneScored[i] = teamOneScored[i] + 1;
}
if (shot > 4)
{
oneShotOn[i] = oneShotOn[i] + 1;
}
}
for(int y = 0; secondShotCount >= y; y++)
{
int shot = random.nextInt(10 - 1 + 1) + 1;
if (shot > 8)
{
teamTwoScored[i] = teamTwoScored[i] + 1;
}
if (shot > 4)
{
twoShotOn[i] = twoShotOn[i] + 1;
}
}
System.out.println(teamOneScored[i] + ":" + teamTwoScored[i]);
}
}
static File firstDataFile = new File("src/playerdata/" + Main.firstTeam);
static File secondDataFile = new File("src/playerdata/" + Main.secondTeam);
static int teamOnePossessionTotal = 0;
static int teamTwoPossessionTotal = 0;
public static void PossessionControl(String firstTeam, String secondTeam) throws IOException
{
BufferedReader br1 = new BufferedReader(new FileReader(firstDataFile));
String line = "";
for(int i = 1; i+1 < 13; i++)
{
line = br1.readLine();
teamOnePossessionTotal = teamOnePossessionTotal + PossessionStatTotal(line);
}
br1.close();
BufferedReader br2 = new BufferedReader(new FileReader(secondDataFile));
for(int i = 1; i+1 < 13; i++)
{
line = br2.readLine();
teamTwoPossessionTotal = teamTwoPossessionTotal + PossessionStatTotal(line);
}
br2.close();
}
public static int PossessionStatTotal(String line)
{
int value = 0;
String[] stats = line.split("-");
String position = stats[1];
if(!(position.equals("GK")))
{
String passing = stats[5];
String positioning = stats[7];
String ballControl = stats[9];
value = (int) ((int) (Integer.valueOf(passing)*.5) + Integer.valueOf(positioning)*.2 + Integer.valueOf(ballControl)*.1);
}
return value;
}
}
Here is my Main Class:
package data;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static String currentTeam;
public static void main(String[] args) throws IOException
{
compareTeams();
//setOveralls();
}
public static void setOveralls() throws IOException
{
Scanner read = new Scanner(System.in);
System.out.println("Which team do you like?");
currentTeam = read.nextLine();
read.close();
PlayerOverall.eraseOverallFile();
PlayerOverall.getPlayerInfo(13, currentTeam);
}
public static String firstTeam;
public static String secondTeam;
public static Scanner read = new Scanner(System.in);
public static void compareTeams() throws IOException
{
System.out.println("What is the first team?");
firstTeam = read.nextLine();
System.out.println("What is the second team?");
secondTeam = read.nextLine();
compare.CompareTeams.compare(firstTeam, secondTeam);
}
}
Here is the PlayerOverall Class, this just determines their Overall.
package data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class PlayerOverall
{
//NOTE TO SELF -- CHANGE OUT OF HARD CODE VVVVVVVVVVV
static File dataFile = new File("src/playerdata/" + Main.currentTeam);
static File overallFile = new File("src/overalls/" + Main.currentTeam);
public static String getPlayerInfo(int numLine, String currentTeam) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(dataFile));
String line = "";
for(int i = 1; i+1 < numLine; i++)
{
line = br.readLine();
evaluatePlayer(line);
}
br.close();
return line;
}
public static void evaluatePlayer(String line) throws IOException
{
String[] stats = line.split("-");
String position = stats[1];
int overall = 0;
if(position.equals("GK"))
{
int height = Integer.parseInt(stats[2]);
int diving = Integer.parseInt(stats[3]);
int catching = Integer.parseInt(stats[4]);
int shooting = Integer.parseInt(stats[5]);
int reflexes = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
overall = (int) ((int) ((int) ((int) ((int) ((int) (height*.05) + diving*.2) + catching*.2) + shooting*.1) + reflexes*.2) + positioning*.25);
setOverall(position, overall);
//OVERALL WORKS CORRECT NOW DO THE ADDITION OF OVERALL TO THE FILE!!
}
else
{
int speed = Integer.parseInt(stats[2]);
int acceleration = Integer.parseInt(stats[3]);
int distance = Integer.parseInt(stats[4]);
int passing = Integer.parseInt(stats[5]);
int shooting = Integer.parseInt(stats[6]);
int positioning = Integer.parseInt(stats[7]);
int defending = Integer.parseInt(stats[8]);
int ballControll = Integer.parseInt(stats[9]);
if(position.equals("LB") || position.equals("RB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.1) + positioning*.15) + defending*.15) + ballControll*.1);
}
else if(position.equals("CB"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.095) + acceleration*.1) + distance*.1) + passing*.1) + shooting*.05) + positioning*.2) + defending*.3) + ballControll*.1);
}
else if(position.equals("CM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.05) + acceleration*.05) + distance*.15) + passing*.2) + shooting*.1) + positioning*.2) + defending*.1) + ballControll*.1) + 10;
}
else if(position.equals("LM") || position.equals("RM"))
{
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.2) + acceleration*.2) + distance*.1) + passing*.1) + shooting*.133) + positioning*.1) + defending*.033) + ballControll*.133) + 5;
}
else if(position.equals("ST"))
{
int stength = Integer.parseInt(stats[10]);
overall = (int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) ((int) (speed*.133) + acceleration*.133) + distance*.033) + passing*.05) + shooting*.225) + positioning*.225) + defending*.0) + ballControll*.1) + stength*.1) + 5;
}
setOverall(position, overall);
}
}
public static void setOverall(String position, int overall) throws IOException
{
try (FileWriter fw = new FileWriter(overallFile, true))
{
fw.append(position + "-" + overall +"\n");
}
}
public static void eraseOverallFile() throws IOException
{
FileWriter fw = new FileWriter(overallFile);
fw.write("");
fw.close();
}
}
The files I am getting for are just regular files. They look like this:
Lukas Hradecky-GK-63-81-81-74-89-82
Jetro Willems-LB-83-86-80-79-76-72-76-81
David Abraham-CB-76-83-68-74-70-76-80-61
Simon Falette-CB-60-71-77-57-50-74-84-56
Timmy Chandler-RB-80-76-83-74-68-71-77-74
Marco Fabian-CM-70-76-75-78-80-77-36-85
Jonathan De Guzman-CM-78-79-70-78-80-78-51-83
Mijat Gacinovic-RM-78-78-74-70-68-69-61-81
Ante Rebic-LM-76-79-71-62-78-72-40-75
Sebastien Haller-ST-75-79-73-64-77-77-35-79-91
Kevin Prince Boateng-ST-74-74-67-79-82-78-70-83-83
You can name this file whatever you like. Make another file in the appropriate location and it will generate everything else needed.
Thank you for your help!
I think you missed the minimal in [mcve].
TL;DR ... but spotted:
int firstDefense = firstPositionAmount[0] + firstPositionAmount[1]/2;
int secondDefense = secondPositionAmount[0] + secondPositionAmount[1]/2;
int firstAttack = firstPositionAmount[2] + firstPositionAmount[1]/2;
int secondAttack = secondPositionAmount[2] + secondPositionAmount[2]/2;
Indices are:
0 1
0 1
2 1
2 2
This seems inconsistent. Perhaps last should be a 1?
I want to take real-time data using modbus tcp/ip simulator for filling of a tank that uses port no 502.
How can I write a code in java to get the holding register value from the simulator and also I want to control the values of it?
If you use a Modbus library like this one most of the work is already done for you.
ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost").build();
ModbusTcpMaster master = new ModbusTcpMaster(config);
CompletableFuture<ReadHoldingRegistersResponse> future =
master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
future.thenAccept(response -> {
System.out.println("Response: " + ByteBufUtil.hexDump(response.getRegisters()));
ReferenceCountUtil.release(response);
});
import java.io.* ;
import java.net.* ;
import java.util.*;
public class Modcli {
public static void main(String argv[]) {
if (argv.length < 4) {
System.out.println("usage: java test3 dns_name unit reg_no num_regs");
System.out.println("eg java test3 aswales8.modicon.com 5 0 10");
return;
}
try {
String ip_adrs = argv[0];
int unit = Integer.parseInt(argv[1]);
int reg_no = Integer.parseInt(argv[2]);
int num_regs = Integer.parseInt(argv[3]);
System.out.println("ip_adrs = "+ip_adrs+" unit = "+unit+" reg_no = "+
reg_no+" num_regs = "+num_regs);
// set up socket
Socket es = new Socket(ip_adrs,502);
OutputStream os= es.getOutputStream();
FilterInputStream is = new BufferedInputStream(es.getInputStream());
byte obuf[] = new byte[261];
byte ibuf[] = new byte[261];
int c = 0;
int i;
// build request of form 0 0 0 0 0 6 ui 3 rr rr nn nn
for (i=0;i<5;i++) obuf[i] = 0;
obuf[5] = 6;
obuf[6] = (byte)unit;
obuf[7] = 3;
obuf[8] = (byte)(reg_no >> 8);
obuf[9] = (byte)(reg_no & 0xff);
obuf[10] = (byte)(num_regs >> 8);
obuf[11] = (byte)(num_regs & 0xff);
// send request
os.write(obuf, 0, 12);
// read response
i = is.read(ibuf, 0, 261);
if (i<9) {
if (i==0) {
System.out.println("unexpected close of connection at remote end");
} else {
System.out.println("response was too short - "+i+" chars");
}
} else if (0 != (ibuf[7] & 0x80)) {
System.out.println("MODBUS exception response - type "+ibuf[8]);
} else if (i != (9+2*num_regs)) {
System.out.println("incorrect response size is "+i+
" expected"+(9+2*num_regs));
} else {
for (i=0;i<=2;i++) {
int w = (ibuf[0+i+i]<<8) + ibuf[1+i+i];
System.out.println("word "+i+" = "+w);
}
for (i=3;i<=5;i++) {
int w = (ibuf[i+3]) ;
System.out.println("word "+i+" = "+w);
}
for (i=0;i<num_regs;i++) {
int w = (ibuf[9+i+i]<<8) + ibuf[10+i+i];
System.out.println("word "+i+" = "+w);
}
}
// close down
es.close();
} catch (Exception e) {
System.out.println("exception :"+e);
}
}
}
I know this has been asked before, but I have tried all the posts on this site and still no fix so I though I might upload my code and see what im doing wrong.
I am using java for my server and javascript websocket for my client. When I send information from my server to my client nothing happens and also when I send data from client to server nothing is received. Please help?!?!?!
Here is my server code:
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import org.apache.commons.codec.binary.Base64;
public class Server extends JFrame
{
private JTextArea textArea = new JTextArea();
private Scanner fromClient;
private BufferedOutputStream toClient;
private Socket socket;
private static final int TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10;
public static void main(String[] args)
{
new Server();
}
public Server()
{
setLayout(new BorderLayout());
add(new JScrollPane(textArea), BorderLayout.CENTER);
setTitle("Server");
setSize(700, 400);
setLocation(0, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try
{
//create server socket
ServerSocket serverSocket = new ServerSocket(8181);
textArea.append( "Starting Server...\n" );
textArea.append("Server started at " + new Date() + '\n');
//Wait for connection
socket = serverSocket.accept();
//create input output
fromClient = new Scanner(socket.getInputStream());
toClient = new BufferedOutputStream(socket.getOutputStream());
this.handle_handshake(fromClient);
textArea.append("\n\nsending text....\n");
//this.brodcast("pop");
this.send_message("test");
int i = 1;
while (true)
{
String s = fromClient.hasNext() ? fromClient.nextLine() : "";
textArea.append("Client: " + s + "\n");
if( i == 0 ) break;
}
socket.close();
serverSocket.close();
}
catch (IOException ex)
{
System.err.println(ex);
}
}
private boolean handle_handshake( Scanner scanner )
{
String line;
String hash_str = "";
String key = "";
int counter = 0;
while ( scanner.hasNextLine() && (line = scanner.nextLine() ) != null )
{
String[] tokens = line.split( ": " );
switch ( tokens[0] )
{
case "Sec-WebSocket-Key":
key = tokens[1].trim();
textArea.append( "SocketKey" );
hash_str = this.get_return_hash( tokens[1] );
break;
case "Sec-WebSocket-Version":
textArea.append( "WebSock-Ver: " + tokens[1] + "\n" );
break;
default:
textArea.append( tokens[0] + ": " + tokens[tokens.length-1] + "\n" );
break;
}
++counter;
if ( counter > 12 )
{
textArea.append( "Handshake" );
String msg = "HTTP/1.1 101 Switching Protocols\r\n";
msg += "Upgrade: websocket\r\n";
msg += "Connection: Upgrade\r\n";
msg += "Sec-WebSocket-Accept: " + hash_str + "\r\n";
msg += "\r\n\r\n";
try
{
toClient.write( msg.getBytes( "UTF-8" ) );
textArea.append( "Server > Client: " + msg );
//toClient.flush();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
textArea.append( "\n\nClosing handshake\n\n" );
return true;
}
}
return false;
}
public void brodcast(String mess) throws IOException
{
byte[] rawData = mess.getBytes();
int frameCount = 0;
byte[] frame = new byte[10];
frame[0] = TEXT;
if(rawData.length <= 125){
frame[1] = (byte) rawData.length;
frameCount = 2;
}else if(rawData.length >= 126 && rawData.length <= 65535){
frame[1] = (byte) 126;
byte len = (byte) rawData.length;
frame[2] = (byte)((len >> 8 ) & (byte)255);
frame[3] = (byte)(len & (byte)255);
frameCount = 4;
}else{
frame[1] = (byte) 127;
byte len = (byte) rawData.length;
frame[2] = (byte)((len >> 56 ) & (byte)255);
frame[3] = (byte)((len >> 48 ) & (byte)255);
frame[4] = (byte)((len >> 40 ) & (byte)255);
frame[5] = (byte)((len >> 32 ) & (byte)255);
frame[6] = (byte)((len >> 24 ) & (byte)255);
frame[7] = (byte)((len >> 16 ) & (byte)255);
frame[8] = (byte)((len >> 8 ) & (byte)255);
frame[9] = (byte)(len & (byte)255);
frameCount = 10;
}
int bLength = frameCount + rawData.length;
byte[] reply = new byte[bLength];
int bLim = 0;
for(int i=0; i<frameCount;i++){
reply[bLim] = frame[i];
bLim++;
}
for(int i=0; i<rawData.length;i++){
reply[bLim] = rawData[i];
bLim++;
}
toClient.write(reply);
toClient.flush();
textArea.append("\n\n\nEnd of brodcasting: " + mess + "\n\n\n");
}
private void send_message( String msg )
{
try
{
textArea.append( "Sending Message: " + msg + "\n" );
byte[] textBytes = msg.getBytes( "UTF-8" );
//ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte code = TEXT;
//opcode
toClient.write( code );
//length
toClient.write( (byte) textBytes.length );
//data
toClient.write( textBytes );
//fin end line
toClient.write( code );
toClient.flush();
}
catch ( IOException e )
{
System.out.printf( "IOE: %s", e.getMessage() );
}
}
private String get_return_hash( String key )
{
textArea.append( "|| " + key + " ||\n" );
String protocol_str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] sha1_bytes = sha1( key + protocol_str );
String final_hash = new String(Base64.encodeBase64( sha1_bytes ));
return final_hash;
}
private byte[] sha1(String input)
{
try
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
return result;
}
catch ( NoSuchAlgorithmException e )
{
return null;
}
}
}
And Here is my client code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="assets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$( document ).ready( function()
{
var ws;
var host = 'ws://localhost:8181';//'ws://echo.websocket.org';
if('WebSocket' in window)
{
console.log( "Connect" );
connect(host);
}
function connect(host)
{
ws = new WebSocket(host);
ws.binaryType = 'blob'; //ws.binaryType = 'arraybuffer';
ws.onopen = function( evt )
{
console.log( "Connection opened" );
console.log( "readyState: " + ws.readyState );
console.log( evt );
console.log('protocol: ' + ws.protocol);
setInterval(test, 5000);
};
ws.onerror = function( evt )
{
console.log( 'Error Code: ' + evt.code );
console.log( evt );
};
ws.onmessage = function (evt)
{
console.log('reveived data:' + evt.data);
};
ws.onclose = function (evt)
{
console.log( "Socket closed" );
console.log( "Reason: " + evt.reason + " Code: " + evt.code );
console.log( "Clean Close: " + evt.wasClean );
};
};
function test()
{
console.log("waiting...");
//var data = str2ab("Ping");
var line = 'waiting...';
// perform some operations on the ArrayBuffer
console.log( ws.readyState );
if (ws.readyState == 1) ws.send(line);
if (ws.bufferedAmount === 0)
{
console.log('SENT!');
}
else
{
console.log('NOT SENT! left over' + ws.bufferedAmount);
}
};
});
</script>
</head>
<body>
</body>
</html>
Thank you for any help!!
The biggest (or at least the first) issue that you can resolve is in the handle handshake.
Change:
msg += "Sec-WebSocket-Accept: " + hash_str + "\r\n";
to:
msg += "Sec-WebSocket-Accept: " + hash_str;
This is causing the handshake to end with three "\r\n". The client ends the handshake after reading the first two, causing the third to get left in the stream. This means your last \r\n will get read in as part of whatever data the client tries to read next. If you try to send the client a message, it will disconnect due to a bad opcode (most likely).