Java: Using Iterator in Switch Statement - java

I want to cycle through an ArrayList<String> named fileContent, using the Iterator interface, and I want it to be analyzed one string at a time which should result in a specific state by the switch statement, depending on what string it is.
Object token is supposed to be read as 'Table'.
void process() {
Iterator fileIterator = fileContent.iterator();
int state = 0;
Object token = null;
switch (state) {
case 0:
token = fileIterator.next();
if (token.equals("Table")) {
System.out.println(token);
state = 1;
} else {
System.err.println("Corrupt file format at state 0: "+ token);
System.exit(0);
}
break;
}
}
This doesn't switch state to 1, instead it prints out:
'Corrupt file format at state 0: Table'
So it seems as it reads the Object token correctly as 'Table' but not for the statement 'if (token.equals("Table"))'.
I have also tried 'if (token == ("Table"))'
Can somebody help me?

Looks like you want to equate Strings, try this
void process() {
Iterator fileIterator = fileContent.iterator();
int state = 0;
String token = ""; // notice this
switch (state) {
case 0:
token = ((String)fileIterator.next()).trim(); // notice this
if (token.equals("Table")) {
System.out.println(token);
state = 1;
} else {
System.err.println("Corrupt file format at state 0: "+ token);
System.exit(0);
}
break;
}
}

What makes you think "it reads the Object token correctly as 'Table'"? When the if() fails, then token must be something unlike Table. My guess is that the output is misleading. Try this instead:
System.err.println("Corrupt file format at state 0: ["+ token + "]");
The square brackets around the token will help you see unexpected whitespace characters.
Also note that token might not be a string but return Table when toString() is called on it (which will happen if you append it to a string).

Related

How to test method which uses other method - Mockito, java, junit

I would like to test method which use another one? I tried do it using Mockito like below:
EDIT: Full method
public String createUrlAddress(TypeOfInformation typeOfInformation, String icao) {
switch (typeOfInformation) {
case METAR:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_METAR + icao;
break;
case TAF:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_TAF + icao + StaticValues.TAF_4_HOURS_BEFORE_NOW;
break;
case CITY_PAIR_METAR:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS
+ pc.getDepartureAndArrivalTime().get("departureTime") //get departure time from hashmap
+ StaticValues.END_TIME_STRING
+ pc.getDepartureAndArrivalTime().get("arrivalTime")
+ StaticValues.STATION_STRING
+ pc.getOriginIcao()
+ ","
+ pc.getDestinationIcao()
+ StaticValues.MOST_RECENT_FOR_TYPED_STATIONS;
System.out.println(urlAddress);
break;
case CITY_PAIR_TAFS:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS_TAFS
+ pc.getDepartureAndArrivalTime().get("departureTime")
+ StaticValues.END_TIME_STRING
+ pc.getDepartureAndArrivalTime().get("arrivalTime")
+ StaticValues.STATION_STRING
+ pc.getOriginIcao()
+ ",%20"
+ pc.getDestinationIcao()
+ StaticValues.MOST_RECENT_FOR_TYPED_STATIONS_TAFS;
System.out.println(urlAddress);
break;
default:
System.out.println("Wrong Type of informations");
}
return urlAddress;
}
Tests:
#Test
public void forGivenTypeOfInformationAndIcaoReturnUrl() {
HashMap<String,Long> departureAndArrivalTimeTest = new HashMap<>();
departureAndArrivalTimeTest.put("departureTime", 1499264449L);
departureAndArrivalTimeTest.put("arrivalTime", 1499282449L);
PageControllerForNearestCity pcSpy = Mockito.spy(pc);
Mockito.when(pcSpy.getDepartureAndArrivalTime()).thenReturn(departureAndArrivalTimeTest);
Mockito.when(pcSpy.getOriginIcao()).thenReturn("EPWA");
Mockito.when(pcSpy.getDestinationIcao()).thenReturn("EDDF");
assertThat(StaticValuesForTest.URL_ADDRESS_FOR_CITY_PAIR_METAR).isEqualTo(xmlParser.createUrlAddress(TypeOfInformation.CITY_PAIR_METAR, "EPGD")); }
How can I use my mocks in that case? Is it good approach or I have to do it in other way? I would like to add that I won't add these variables as arguments for this method.
PS I thought that the method has only one resposibility, just create a string, am I wrong? Should it be divided into another one like a "Service"?
Thank you for support
Your test enters too much in implementation details.
You mock the own processings/logic of your method. So it makes the test brittle and we can wonder what you assert really.
Besides, the test is complicated to read and to maintain.
At last, the processing associated to each case matters. It is the main logic of your method :
case CITY_PAIR_METAR:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS
+ pc.getDepartureAndArrivalTime().get("departureTime") //get departure time from hashmap
+ StaticValues.END_TIME_STRING
+ pc.getDepartureAndArrivalTime().get("arrivalTime") //get arrival time from hashmap
+ StaticValues.STATION_STRING
+ pc.getOriginIcao()
+ ","
+ pc.getDestinationIcao()
+ StaticValues.MOST_RECENT_FOR_TYPED_STATIONS;
System.out.println(urlAddress);
It should be tested without mocking as you actually doing.
To do it, you should separate responsabilities by introducing a new class.
The actual class should only have a controller/dispatcher role and the new class should perform the logic with a public method by case.
In this way, you class under test could have a dependency on this class and you could mock them in a straight way.
Your actual method could finally look like :
private AddressService addressService;
public String createUrlAddress(TypeOfInformation typeOfInformation, String icao) {
switch (typeOfInformation) {
(...)
case CITY_PAIR_METAR:
urlAddress = addressService.createUrl();
break;
(...)
default:
System.out.println("Wrong Type of informations");
}
return urlAddress;
}
#rafaelim After your response I updated my test class and injected mock to the class like below:
#Before
public void setUp() throws Exception {
departureAndArrivalTimeTest = new HashMap<>();
xmlParser = new XmlParser();
pc = new PageControllerForNearestCity();
departureAndArrivalTimeTest.put("departureTime", 1499264449L); //second arg dep time in sec
departureAndArrivalTimeTest.put("arrivalTime", 1499282449L); //second arg arr time in sec
}
#Test
public void forGivenTypeOfInformationAndIcaoReturnUrl() {
PageControllerForNearestCity pcSpy = Mockito.spy(pc);
xmlParser.setPc(pcSpy);
Mockito.when(pcSpy.getDepartureAndArrivalTime()).thenReturn(departureAndArrivalTimeTest);
Mockito.when(pcSpy.getOriginIcao()).thenReturn("EPWA");
Mockito.when(pcSpy.getDestinationIcao()).thenReturn("EDDF");
assertThat(StaticValuesForTest.URL_ADDRESS_FOR_METAR).isEqualTo(xmlParser.createUrlAddress(TypeOfInformation.METAR, "EPGD"));
assertThat(StaticValuesForTest.URL_ADDRESS_FOR_TAF).isEqualTo(xmlParser.createUrlAddress(TypeOfInformation.TAF, "EPGD"));
assertThat(StaticValuesForTest.URL_ADDRESS_FOR_CITY_PAIR_METAR).isEqualTo(xmlParser.createUrlAddress(TypeOfInformation.CITY_PAIR_METAR, "EPGD"));
assertThat(StaticValuesForTest.URL_ADDRESS_FOR_CITY_PAIR_TAF).isEqualTo(xmlParser.createUrlAddress(TypeOfInformation.CITY_PAIR_TAFS, "EPGD"));
}
Test passed, but its a little bit unreadable, I have to work with "clean code" I think.
EDIT:
#davidxxx please look at this:
public class UrlAddressService {
PageControllerForNearestCity pc = new PageControllerForNearestCity();
public String createUrlForMetar() {
String urlAddressForMetars = new StringBuilder()
.append(StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS)
.append(pc.getDepartureAndArrivalTime().get("departureTime"))
.append(StaticValues.END_TIME_STRING)
.append(pc.getDepartureAndArrivalTime().get("arrivalTime"))
.append(StaticValues.STATION_STRING)
.append(pc.getOriginIcao())
.append(",")
.append(pc.getDestinationIcao())
.append(StaticValues.MOST_RECENT_FOR_TYPED_STATIONS_METARS)
.toString();
return urlAddressForMetars;
}
public String createUrlForTaf() {
String urlAddressForTafs = new StringBuilder()
.append(StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS_TAFS)
.append(pc.getDepartureAndArrivalTime().get("departureTime"))
.append(StaticValues.END_TIME_STRING)
.append(pc.getDepartureAndArrivalTime().get("arrivalTime"))
.append(StaticValues.STATION_STRING)
.append(pc.getOriginIcao())
.append(",%20")
.append(pc.getDestinationIcao())
.append(StaticValues.MOST_RECENT_FOR_TYPED_STATIONS_TAFS)
.toString();
return urlAddressForTafs;
}
}
And createUrlAddress method:
public String createUrlAddress(TypeOfInformation typeOfInformation, String icao) {
switch (typeOfInformation) {
case METAR:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_METAR + icao;
break;
case TAF:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_TAF + icao + StaticValues.TAF_4_HOURS_BEFORE_NOW;
break;
case CITY_PAIR_METAR:
urlAddress = addressService.createUrlForMetar();
break;
case CITY_PAIR_TAFS:
urlAddress = addressService.createUrlForTaf();
break;
default:
System.out.println("Wrong Type of informations");
}
return urlAddress;
}
Do you think that it is better approach? I cannot reduce code during building a URL String, because there are 3 different parts of code for Tafs and Metars. Could you show me the best way how to test it if my test are bad?
I think you are in the right direction! You are mocking the dependencies of your code and that dependency is exactly the PageControllerForNearestCity!
One observation about the mock, you have to inject it on xmlParser, like this:
#Test
public void forGivenTypeOfInformationAndIcaoReturnUrl() {
// here you created the mock
PageControllerForNearestCity pcSpy = Mockito.spy(pc);
// I'll assume that xmlParser is the subject of your test
// and that you're injecting the mock like code below
xmlParser.setPageController(pcSpy);
// Configure the mock and then you do the assertion
assertThat(...)
}
PS I thought that the method has only one resposibility, just create a
string, am I wrong? Should it be divided into another one like a
"Service"?
Your method is good! It really do one thing and well and that is building an url from TypeOfInformation
My suggestion is that you refactor your code, after you write your test codes and make it pass! You can remove code duplication and make it more readable!
Remeber this:
'Any fool can write code that a computer can understand. Good
programmers write code that humans can understand.'
Martin Fowler
Good coding!
Edit
Some examples of your code with some refactoring
public String createUrlAddress(TypeOfInformation typeOfInformation, String icao) {
String urlAddress;
switch (typeOfInformation) {
case METAR:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_METAR + icao;
break;
case TAF:
urlAddress = StaticValues.MAIN_URL_ADDRESS_FOR_TAF + icao + StaticValues.TAF_4_HOURS_BEFORE_NOW;
break;
case CITY_PAIR_METAR:
// We delegate the build logic to pc because
// all the information needed to build the url
// is in the PageControllerForNearestCity class
urlAddress = pc.urlAddressForCityPairMetar();
break;
case CITY_PAIR_TAFS:
// Same
urlAddress = pc.urlAddressForCityPairTafs();
break;
default:
System.out.println("Wrong Type of informations");
}
return urlAddress;
}
class PageControllerForNearestCity {
public String urlAddressForCityPairMetar() {
return urlBasedOn(StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRSS, ",", StaticValues.MOST_RECENT_FOR_TYPED_STATIONS);
}
public String urlAddressForCityPairTafs() {
return urlBasedOn(StaticValues.MAIN_URL_ADDRESS_FOR_CITY_PAIRS_TAFS, ",%20", StaticValues.MOST_RECENT_FOR_TYPED_STATIONS_TAFS);
}
// This method removes the duplication that I mentioned before
private String urlBasedOn(String mainUrl, String separator, String endString) {
return mainUrl
+ this.getDepartureAndArrivalTime().get("departureTime")
+ StaticValues.END_TIME_STRING
+ this.getDepartureAndArrivalTime().get("arrivalTime")
+ StaticValues.STATION_STRING
+ this.getOriginIcao()
+ separator
+ this.getDestinationIcao()
+ endString;
}
}
Note that after this refactoring, your forGivenTypeOfInformationAndIcaoReturnUrl test method will become much simpler. But you will have to create test for urlAddressForCityPairMetar() and urlAddressForCityPairTafs().

Jersey - String not mapped to Json while using ObjectMappers function writeValueAsString succeeds

I have the following function :
protected final ResponseBuilderImpl RESPONSE_BUILDER_IMPL = new ResponseBuilderImpl(); // This is taken from jersey-core-1.11.jar
protected Response buildAcceptedResponse(Object entity) {
return buildResponse(entity, Response.Status.ACCEPTED);
}
protected Response buildResponse(Object entity, Response.Status status) {
return RESPONSE_BUILDER_IMPL.status(status).entity(entity).build();
}
I've tested several cases and noticed that only String is not working, and can't figure out why.
I'm using postman, sending some GET requests
switch (whatToTest){
case 1: //working
log.info("testing case of Interger!! ");
int x = 11;
return buildAcceptedResponse(x);
case 2: // getting as a response Unexpected 'e'
String t = "testing string";
log.info("testing case of String !!");
return buildAcceptedResponse(t);
case 3: //working
log.info("testing case of Boolean !! ");
boolean y = true;
return buildAcceptedResponse(y);
case 4: //not working
log.info("testing case of Object !! ");
Object yy = "test object";
return buildAcceptedResponse(yy);
case 5: //working
log.info("testing case of Object from type int !! ");
Object yyy = 1565746;
return buildAcceptedResponse(yyy);
case 6: //working
log.info("testing case of class with strings and ints!! ");
TestClass e = new TestClass(4,new Integer(7),"test1", false);
return buildAcceptedResponse(e);
/// Adding - when using this case - it works fine
case 7:
log.info("mapping to object");
ObjectMapper om = new ObjectMapper();
Object res = null;
String te = "test test";
try {
res = om.writeValueAsString(te);
} catch (IOException ex) {
ex.printStackTrace();
}
return buildAcceptedResponse(res);
I thought that I might have a problem with primitive types, but int and boolean are returning as they should. Also, a class containing a String inside - is also good.Can someone advise why only Strings are not working ?
Adding -
My function uses :
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("test/test")
public Response getTest(String someParam);
// Response is sr311-api\0.11\jsr311-api-0.11-sources.jar

Rerunning my program in Java

I am trying to make it so that if the username and / or password aren't correct, the program will run it over again, instead of just doing the print command in the else statement. I tried putting another while loop in the else statement and nesting the if statement inside that checks the username and password inside of it, but then I realized I would have to copy all the code from the if statement into the else statement, which obviously seems like it is not the correct solution and is probably very clunky. What is the right way to refer the program back to run from the start or something?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
Think about the below logic
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
If command equals calculator then how can it equal renameUser
You should have it
if (....) {
}
else if (...) {
}
statement or as a switch statement
This snippet here is increasing the cyclomatic complexity of your software making it hard to make a decision, if you want to change that later, you have more chances to break the code than success
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
try to design something more like a witch case logic
Example:
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}

Ormlite Where issue with parenthesis, building meta-layer query library

I've read the other posts and the docs about how to use the "Where" clause to "create" parenthesis statements.
My requirement is simple:
... WHERE companyID=1 AND (director=true OR officer=true) ;
I'm writing a routine that takes an array of Object, which are then parsed into an Ormlite Where call. a typical call looks like this:
.., "companyID", 1, Q.AND, Q.Bracket, "director", true, Q.OR, "officer", true, Q.Bracket)
The intent is to speed up simple queries. There is no desire to replace Ormlite's querying tools. This is a simple meta-layer on top.
Everything works fine for simple queries, since the parameters are processed sequentially and the where clause is built incrementally.
For parenthesis I am postponing the processing until the bracket is closed.
This is where I am having a problem. The example from the docs I am using shows this:
-- From the OrmLite docs...
Where<Account, String> where = queryBuilder.where();
where.or(
where.and(
where.eq(Account.NAME_FIELD_NAME, "foo"),
where.eq(Account.PASSWORD_FIELD_NAME, "_secret")),
where.and(
where.eq(Account.NAME_FIELD_NAME, "bar"),
where.eq(Account.PASSWORD_FIELD_NAME, "qwerty")));
This produces the following approximate SQL:
SELECT * FROM account
WHERE ((name = 'foo' AND password = '_secret')
OR (name = 'bar' AND password = 'qwerty'))
The key thing I understand from the docs example, is that the same where instance is used in the nested and(...) call. This is precisely what I'm doing but I'm still getting a "Did you forget an AND or an OR" message.
The code implementing the "delayed" processing looks like this:
#SuppressWarnings("unchecked")
private void processWhere(Where<?, ?> where, Q q, List<QValue> list)
{
if (null == list || list.size() < 2)
{
System.err.println("Invalid where passed: " + list);
return;
}
if (q.equals(Q.AND))
where.and(getCondition(where, list.get(0)), getCondition(where, list.get(1)));
else
where.or(getCondition(where, list.get(0)), getCondition(where, list.get(1)));
}
The "QValue" item is just a "holder" for column, condition and value data.
The "getCondition" method is as follows:
#SuppressWarnings("rawtypes")
protected Where getCondition(Where<?, ?> where, QValue qv)
{
if (null != where && null != qv)
return getCondition(where, qv.getType(), qv.getColumn(), qv.getValue(), qv.getValue2());
else
return null;
}
#SuppressWarnings("rawtypes")
protected Where getCondition(Where<?, ?> where, Q cond, String key, Object val, Object val2)
{
if (null == where || null == cond || null == key || null == val)
return null;
SelectArg arg = new SelectArg();
arg.setValue(val);
try
{
switch (cond)
{
case NotNull:
where.isNotNull(key);
break;
case IsNull:
where.isNull(key);
break;
case Equals:
where.eq(key, arg);
break;
case NotEqual:
where.ne(key, arg);
break;
case GreaterThan:
where.gt(key, arg);
break;
case LessThan:
where.lt(key, arg);
break;
case Like:
arg.setValue("%" + val + "%");
where.like(key, arg);
break;
case LikeStart:
arg.setValue("" + val + "%");
where.like(key, arg);
break;
case LikeEnd:
arg.setValue("%" + val);
where.like(key, arg);
break;
case Between:
if (null != val && null != val2)
where.between(key, val, val2);
break;
default:
where.eq(key, arg);
break;
}
}
catch (SQLException e)
{
GlobalConfig.log(e, true);
return null;
}
return where;
}
As far as I can tell, I'm using the Where object correctly, but I am still getting a:
"Did you forget an AND or OR?" message.
I've tried creating "new" Where clauses with QueryBuilder:
Where w1 = qb.where() ;
//process w1 conditions...
return where.query() ;
Which also fails or generates incorrect SQL in the various combinations I've tried. Any suggestions on how to get the and(...) and or(...) methods working properly will be greatly appreciated.
BTW once the library is working properly, I'll put it up as Open Source or donate it to Gray, or both.
Thanks in advance.
Anthony
I faced the same issue and solved it like this:
where.eq("companyID", 1);
where.and(where, where.or(where.eq("director", true), where.eq("officer", true)));
or
where.and(where.eq("companyID", 1), where.or(where.eq("director", true), where.eq("officer", true)));
which in SQL gives us:
((`companyID` = 1 AND `director` = 1 ) OR (`companyID` = 1 AND `officer` = 1 ))
It's not identical to your example clause WHERE companyID=1 AND (director=true OR officer=true) but has the same meaning.

EMV TLV Java Function

I'm looking for a way to translate an EMV response with Java like with this online option:
http://www.emvlab.org/tlvutils/
where you put something like this EMV response:
6f3a8407a0000000031010a52f500b56495341204352454449548701015f2d086573656e707466729f12074352454449544f9f1101019f38039f1a02
and it will show you everything perfectly, I started doing something by myself but then I realize that maybe we could have two 9F38(PDOL) Strings not neccesary two same tags cuz I know it's impossible but maybe the value of a tag end in 9F and the start of the next tag would be 38 and that would give me an error... Now that I mention it, is that possible? cuz that was one of the main reasons why I stopped doing my own function..
Does any of you have written a function to do this already?
Thanks!
https://github.com/binaryfoo/emv-bertlv should do the trick.
Using your example, the following code:
List<DecodedData> decoded = new RootDecoder().decode("6f3a8407a0000000031010a52f500b56495341204352454449548701015f2d086573656e707466729f12074352454449544f9f1101019f38039f1a02", "EMV", "constructed");
new DecodedWriter(System.out).write(decoded, "");
Will output:
[6F (FCI template)] 8407A0000000031010A52F500B56495341204352454449548701015F...1A02
[84 (dedicated file name)] A0000000031010
[A5 (FCI proprietary template)] 500B56495341204352454449548701015F2D086573656E707466729F...1A02
[50 (application label)] VISA CREDIT
[87 (application priority indicator)] 01
[5F2D (language preference)] esenptfr
[9F12 (application preferred name)] CREDITO
[9F11 (issuer code table index)] 01
[9F38 (PDOL - Processing data object list)] 9F1A02
9F1A (terminal country code) 2 bytes
This project has code to deal with EMV data http://code.google.com/p/javaemvreader/
You are on the right track. You can easily build your own EMV parser using the technique call TLV (Tag Length Value). Your raw data always comes back with a Tag, then after the tag is the length, using the length can get you the value.
So create three methods
method 1: Contains all the short tags
method 2: Contains all the long tags
method 3: Contains all the proprietary tags
So when you pass in your raw emv tag:
6f3a8407a0000000031010a52f500b56495341204352454449548701015f2d086573656e707466729f12074352454449544f9f1101019f38039f1a02
Loop through all those three methods, it will give you all the nice information that you need.
Use below function which will gives you hashmap of TLV value
public LinkedHashMap parseBERTLVTag(String tlv) throws DecoderException
{
if(tlv==null || "".equalsIgnoreCase(tlv)){
return null;
}
System.out.println("============= START ["+tlv+"]==================");
boolean inTagRead= true;
Map<String,String> tags= new HashMap<>();
StringBuilder _tmp = new StringBuilder();
String lastTag = "";
int old_index = 0;
boolean isFirstTagByte = true;
int len = 0;
boolean more=true;
String data = "";
while (more)
{
len = 0;
String hByte = tlv.substring(old_index,(old_index = old_index+2));
if(inTagRead)
{
if(isLastTagByte(hByte, isFirstTagByte))
{
inTagRead=false;
_tmp.append(hByte);
lastTag = _tmp.toString();
System.out.println("Tag["+lastTag+"]");
tags.put(lastTag, null);
_tmp= new StringBuilder();
}else
{
_tmp.append(hByte);
}
isFirstTagByte = false;
}else//Length
{
isFirstTagByte = true;
if(isLastLengthByte(hByte)) {
inTagRead=true;
_tmp.append(hByte);
len = Integer.parseInt(_tmp.toString(), 16 );
//read len*2
System.out.println(" Length ["+len+"]");
data = tlv.substring(old_index, (old_index = old_index+len*2));
String tmpData= lastTag+":"+_tmp.toString()+":h"+data;
System.out.println(" Data ["+tmpData+"]");
_tmp = new StringBuilder();
tags.put(lastTag, tmpData);
}else
{
_tmp.append(hByte);
}
}
more= tlv.length()<=old_index?false:true;
System.out.println("tag "+lastTag+" value "+data+" length "+len);
if(lastTag.length() > 0 && data.length() > 0 && len > 0){
if(!map.containsKey(lastTag)){
map.put(lastTag,new TLVModel().setTag(lastTag).setLength(len).setValue(data));
}
}
}//END OF WHILE
System.out.println("------------ as MAP ---------------------");
System.out.println("size "+map.size());
for (Map.Entry mp:map.entrySet()){
System.out.println("key "+mp.getKey()+" value "+mp.getValue());
}
return map.size() > 0 ? map : null;
}

Categories

Resources