Wednesday, 29 May 2019

BCD Length From Long


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public static byte[] intToBCDBytes(long num) {

  return intToBCDBytes(num, 0);
 }

 public static byte[] intToBCDBytes(long num, int minBytes) {
  int digits = 0;

  long temp = num;
  while (temp != 0) {
   digits++;
   temp /= 10;
  }

  int byteLen = digits % 2 == 0 ? digits / 2 : (digits + 1) / 2;
  boolean isOdd = digits % 2 != 0;

  if (byteLen < minBytes)
   byteLen = minBytes;

  byte bcd[] = new byte[byteLen];

  for (int i = 0; i < digits; i++) {
   byte tmp = (byte) (num % 10);

   if (i == digits - 1 && isOdd)
    bcd[i / 2] = tmp;
   else if (i % 2 == 0)
    bcd[i / 2] = tmp;
   else {
    byte foo = (byte) (tmp << 4);

    bcd[i / 2] |= foo;
   }

   num /= 10;
  }

  for (int i = 0; i < byteLen / 2; i++) {
   byte tmp = bcd[i];
   bcd[i] = bcd[byteLen - i - 1];
   bcd[byteLen - i - 1] = tmp;
  }

  return bcd;
 }

 public static String bcdToString(byte bcd) {
  StringBuffer sb = new StringBuffer();

  byte high = (byte) (bcd & 0xf0);
  high >>>= (byte) 4;
  high = (byte) (high & 0x0f);
  byte low = (byte) (bcd & 0x0f);

  sb.append(high);
  sb.append(low);

  return sb.toString();
 }

 public static Integer bcdToInt(byte[] bcd) {

  StringBuffer sb = new StringBuffer();

  for (int i = 0; i < bcd.length; i++) {
   sb.append(bcdToString(bcd[i]));
  }

  return new Integer(sb.toString());
 }

Friday, 26 April 2019

Java ClassPath Issues

When you specify -jar then the -cp parameter will be ignored.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)
You have two options:
  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

How to add S3 based maven repo into gradle repositories


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
buildscript {
 repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
    jcenter()
    mavenCentral()
  }
  dependencies {
    classpath 'com.amazonaws:aws-java-sdk:1.11.214' 
    classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.6-rc1'
  }
}



def awsProfile = "prfilename" //default/saml/east1/anything your configured in aws credentials file
def mavenRepo   = "s3://repo.your.com"

ext {
    samlCredentials = new com.amazonaws.auth.profile.ProfileCredentialsProvider(awsProfile).credentials
}




repositories {
    maven {
        //url "s3://myCompanyBucket/maven2"
        url "${mavenRepo}/releases"
        credentials(AwsCredentials) {
          //  accessKey "someKey"
          //  secretKey "someSecret"
            // optional
           // sessionToken "someSTSToken"
            accessKey samlCredentials.getAWSAccessKeyId()
         secretKey samlCredentials.getAWSSecretKey()
         if (System.env.BUILD_NUMBER==null) {
            if (samlCredentials.getSessionToken()!=null) {
              sessionToken samlCredentials.getSessionToken()
            }
         }
        }
    }
  
  mavenCentral()
  jcenter()
    
 }

Tuesday, 12 June 2018

git error pathspec did not match Remote branch not showing up in “git branch -r”

Problem::

Remote branch not showing up in “git branch -r”
git error pathspec did not match

Solution:

git config -e
it will open an file
For me it was like  " fetch = +refs/heads/master:refs/remotes/origin/master " before solved.

The remote section specifies also fetch rules. You could make sure  something like this exists:
fetch = +refs/heads/*:refs/remotes/origin/*


Thursday, 19 April 2018

Opensource DB UI Tool for Cassandra DB- DBweaver


DBweaver ::

Best opensource tool for CASSANDRA .

I spent lot of time to find open source tool for cassandra , atlast this is the right solution.


#dbeaver-cassandra cassandra db gui

1. Download dbeaver (Community Edition): dbweaver-Download
2. Download cassandra jdbc jar files: http://www.dbschema.com/cassandra-jdbc-driver.html or direct link CassandraJdbcDriver.zip
3. extract cassandra jdbc zip
4. run dbeaver.exe
5. go to Database > Driver Manager
6. click New
7. Fill in details as follow:
   - Driver Name: Cassandra (or whatever you want it to say)
   - Driver Type: Generic
   - Class Name: com.dbschema.CassandraJdbcDriver
   - URL Template: jdbc:cassandra://{host}[:{port}][/{database}]
   - Default Port: 9042
   - Embedded: no
   - Category: <leave blank>
   - Description: Cassandra (or whatever you want it to say)
8. click Add File and add all of the jars in the cassandra jdbc zip
9. click Find Class to make sure the Class Name is found okay
10. click OK
11. Create New Connection, selecting the database driver you just added
dbschema.com
Cassandra JDBC Driver | DbSchema Cassandra Designer
Cassandra free JDBC driver provided by DbSchema Cassandra Admin GUI Tool - best interface for complex Cassandra databases.

Thursday, 25 January 2018

Cassandra java driver With SSL

I want to present you an java code for cassandra client with SSL and Cluster. I am not sharing keystores but i pressume you can get that info from google. I also want to provide you and reference sites i have gone through:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import java.io.File;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Cluster.Builder;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.JdkSSLOptions;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;

/**
 *  "dbinfo": {
      "port": 9042,
      "truststorepath":"/path/to/truststore.jks",
      "truststoresecret":"password of truststore",
      "nodes": [
         "127.0.0.2",
         "127.0.0.1"
      ],
      "ssl": false
   },
 * 
 * 
 * 
 * This is an implementation of a simple Java Cassandra client.
 *
 */
public class CassandraClient {
 private static final Logger logme = LoggerFactory.getLogger(CassandraClient.class);

 private Cluster cluster;

 private Session session;

 /**
  * For single node instance setup
  * 
  * @param node
  * @param port
  */
 public void connectToServer(final String node, final Integer port) {

  Builder b = Cluster.builder().addContactPoint(node);

  if (port != null) {
   b.withPort(port);
  }
  cluster = b.build();

  Metadata metadata = cluster.getMetadata();
  logme.info("Cassandra: Cluster name: " + metadata.getClusterName());

  for (Host host : metadata.getAllHosts()) {
   logme.info("Cassandra:Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: "
     + host.getRack());
  }

  session = cluster.connect();
 }

 /**
  * 
  * For multi node instance setup
  * 
  * @param cfg
  */
 public void connectToServer(JSONObject cfg) {

  Builder b = Cluster.builder();

  JSONObject cassandra = cfg.getJSONObject("dbinfo");
  JSONArray nodes = cassandra.getJSONArray("nodes");

  for (Object node : nodes) {
   b.addContactPoint(node.toString());

  }
  boolean ssl = cassandra.optBoolean("ssl", false);
  int port = cassandra.optInt("port", 9042);
  b.withPort(port);

  if (ssl) {

   String trustPath = cassandra.getString("truststorepath");
   String trustSecret = cassandra.getString("truststoresecret");
   if (trustPath == null || trustSecret == null) {
    logme.error(" *********   Please provide truststore details for cassandra ****************");
   }
   JdkSSLOptions sslOptions = getSSLOptionsFromTrustStore(trustPath, trustSecret);
   b.withSSL(sslOptions);
  }

  cluster = b.build();

  Metadata metadata = cluster.getMetadata();
  logme.info("Cassandra: Cluster name: " + metadata.getClusterName());

  for (Host host : metadata.getAllHosts()) {
   logme.info("Cassandra:Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: "
     + host.getRack());
  }

  session = cluster.connect();
 }

 public Session getSession() {
  return this.session;
 }

 public void close() {
  session.close();
  cluster.close();
 }

 private JdkSSLOptions getSSLOptionsFromTrustStore(String trustStoreLocation, String trustStorePassword) {
  Cluster cluster;
  SSLContext sslcontext = null;

  try {

   InputStream is = FileUtils.openInputStream(new File(trustStoreLocation));
   KeyStore keystore = KeyStore.getInstance("jks");
   char[] pwd = trustStorePassword.toCharArray();
   keystore.load(is, pwd);
   TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmf.init(keystore);
   TrustManager[] tm = tmf.getTrustManagers();

   sslcontext = SSLContext.getInstance("TLSv1");
   sslcontext.init(null, tm, null);

  } catch (Exception e) {
   logme.error(e.getMessage(), e);
  }

  JdkSSLOptions sslOptions = JdkSSLOptions.builder().withSSLContext(sslcontext).build();

  return sslOptions;
 }

}

Monday, 27 November 2017

Best Serializer till now for me in java KRYO


These days we are looking for best serializer for java objects . I came across KRYO . This is one of the best one as of now  for network/file persistance/db.

I thought of making this KRYO known to everyone . Thats why I posted here as reference.

Good Work by Esoteric Software . 👍👍👍


Refer:
Kryo-Github
http://www.baeldung.com/kryo
https://blog.hazelcast.com/kryo-serializer/

Tuesday, 26 September 2017

BER TLV Tag Parsing in Java



Q: Java code for BER TLV tag identification and Length Identification of EMV Fields from Device or HOST ??

Solution:

I tried writing stuff for myself and I thought it helps to you on reading  dynamic TLV tag name and Length in java





  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package com.ohms.rnd.emv;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;


/**
 * 
 * Ref: page :173:Coding of the Tag Field of BER-TLV Data Objects 
 * http://mech.vub.ac.be/teaching/info/mechatronica/finished_projects_2007/Groep%201/Smartcard_files/EMV%20v4.1%20Book%203.pdf
 * 
 * @author 
 *
 */
public class BERTLV {


 private static Set<String> specialtags= Arrays.stream(new String[]{/*"91","71","72"*/}).collect(Collectors.toSet());;
 public static void main(String[] args) {
  
  
  List<String> tlvs= new ArrayList<>();
  //Request Tags
  tlvs.add("77299f2701009f360200419f2608c74d18b08248fefc9f10120110201009248400000000000000000029ff");
  tlvs.add("9f2701009f360200419f2608c74d18b08248fefc9f10120110201009248400000000000000000029ff");
  tlvs.add("9F4005FF80F0F001");
  tlvs.add("9F0206000000012345");
  tlvs.add("9F0306000000004000");
  tlvs.add("9F26088E19ED4BCA5C670A");
  tlvs.add("82025C00");
  tlvs.add("5F340102");
  tlvs.add("9F3602000A");
  tlvs.add("9F0702FF00");
  tlvs.add("9F080208C1");
  tlvs.add("9F09021001");
  tlvs.add("8A025931");
  tlvs.add("9F3403A40002");
  tlvs.add("9F270180");
  tlvs.add("9F1E0853455249414C3132");
  tlvs.add("9F0D05F040008800");
  tlvs.add("9F0E05FCF8FCF8F0");
  tlvs.add("9F0F05FCF8FCF8F0");
  tlvs.add("5F28020840");
  tlvs.add("9F390100");
  tlvs.add("9F3303010101");
  tlvs.add("9F1A020840");
  tlvs.add("9F350122");
  tlvs.add("95050000048000");
  tlvs.add("5F2A020840");
  tlvs.add("9A03140131");
  tlvs.add("9B024800");
  tlvs.add("9F2103123456");//////////////////////
  tlvs.add("9C0100");
  tlvs.add("9F370400BC614E");
  tlvs.add("4F07A0000000031010");
  tlvs.add("9F0607A0000000031010");
  tlvs.add("9F7C0412345678");
  tlvs.add("8407A0000000031010");
  tlvs.add("9F6E05123456789A");
  tlvs.add("9F6E0401020304");
  tlvs.add("9F6E0401020304");
  tlvs.add("9F1006010A03600000");
  tlvs.add("9F5B052000000000");
  tlvs.add("9F4104000001B3");
  tlvs.add("8C209F02069F03069F1A0295055F2A029A039C019F37049F35019F45029F34039B028D08910A8A0295059B028E1000000000000000005F0341035E030203");
  tlvs.add("DFEE250202034F07A0000000031010500B5669736120437265646974560057134072640000000008D22122011143878089629F5A08407264000000000882021C008407A000000003101087008A025A33950580000000009A031709149B0268009C01005F24032212315F2A0208405F300202015F3401019F02060000000001009F03060000000000009F0607A00000000310109F0702FF009F080200969F090200969F1101019F0D05B078FC88009F0E0500000000009F0F05B078FC98009F120E56495341204175737472616C69619F1A0208409F1E085465726D696E616C9F21030842249F33036028C89F34035E03009F3501219F360200B79F370441946B209F38009F3901059F3C009F4005F000F0A0019F4104000000099F5301529F6E009F7C005F201A434152442030332F2D20415544202020202020202020202020205F280200365F2D02656E5F5600DFEE2300DFEE2600FFEE01009F2608D2A4BD91753ADEFF9F2701809F100706010A03A0A000DFEF4C06002700100000DFEF4D373B343037323634303030303030303030383D32323132323031313134333837383038393632393F34303732363430303030303030303038");
  
  //response
  tlvs.add("910A2263BCC1C2D9C4420013");
  tlvs.add("710A0102030405060708090A");
  tlvs.add("720A0102030405060708090A");
  tlvs.add("8C209F02069F03069F1A0295055F2A029A039C019F37049F35019F45029F34039B028D08910A8A0295059B028E1000000000000000005F0341035E030203");
  

  
  tlvs.forEach(x-> {
   try {
    parseBERTLVTag(x);
   } catch (DecoderException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  });
  
  
  
  
  
 }
 
 //B1 Coding of the Tag Field of BER-TLV Data  Objects 
 public static void parseBERTLVTag(String tlv) throws DecoderException 
 {
  if(tlv==null || "".equalsIgnoreCase(tlv)) return;
  
  System.out.println("============= START ["+tlv+"]==================");

  
  boolean inTagRead= true;
  Map<String,String> tags= new HashMap<>();
  
  StringBuilder _tmp = new StringBuilder();
  String lastTag = null;
  int old_index = 0;
  boolean isFirstTagByte = true;
  
  boolean more=true;
  while (more) 
  {
   
   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(!isSpecialTag(lastTag)) {
    
     if(isLastLengthByte(hByte)) {
      inTagRead=true;
      _tmp.append(hByte);
      int len =  Integer.parseInt(_tmp.toString(), 16 );
      //read len*2
      System.out.println(" Length ["+len+"]");
      String 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);
     }

    }else { //Special tag not TLV format
     
     
     
     int len=10;
     String data =  "";//tlv.substring(old_index, (old_index = old_index+len*2));
     String tmpData= lastTag+":0A:h"+data;
     System.out.println(" Data ["+tmpData+"]");
     _tmp = new StringBuilder();

     tags.put(lastTag, tmpData);
     
    }
        
    
    
   }
   
   more= tlv.length()<=old_index?false:true;
//   if(tlv.length()<=old_index) more=false;
   
    
   
   
  }//END OF WHILE
  
  
  System.out.println("------------  as MAP  ---------------------");
  tags.forEach((x,y)->{System.out.println("Tag["+x+"] Value["+y+"]");});
  System.out.println("===============================");
  
 }
 
 
 public static boolean isLastTagByte(String onehexByte, boolean firstByte) throws DecoderException
 {
  
   byte tagByte = Hex.decodeHex(onehexByte.toCharArray())[0];
   
   if(firstByte && (tagByte & 0x1f) == 0x1f) {
    return false;
   } else if (!firstByte && (tagByte & 0x80) == 0x80) {
    return false;
   } else {
    return true;
   }
 }
 
 public static boolean isLastLengthByte(String onehexByte) {
  
  String binVal = new BigInteger(onehexByte, 16).toString(2);
  binVal= fillChars(false, binVal, 8, "0"); 
  if(binVal.startsWith("0")) return true;
   
   return true;

 }
 public static String fillChars(String fillChar,int times)
 {
  StringBuffer builder=new StringBuffer();
  if(fillChar==null)
   return "";
  for (int i = 0; i < times; i++) 
  {
   builder.append(fillChar);
  }
  return builder.toString();
 }
 public static String fillChars(boolean isLeftJustified,String data,int length,String fillChar)
 {
  StringBuffer ret=new StringBuffer(); 
  String fill=null;
  if(data!=null && !data.equalsIgnoreCase(""))
  {
   
   int datLength=data.length();
   int diff=-1;
   if(datLength<length)
   {
    diff=length-datLength; 
    
    fill=fillChars(fillChar, diff);
    
    if(isLeftJustified)
    {
     ret.append(data);
     ret.append(fill);
    }else
    {
     ret.append(fill);
     ret.append(data);
    }
   }else if(datLength==length)
   {
    ret.append(data);
   }
   
  }else
  {
   
   ret.append(fillChars(fillChar, length));
   
  }
 return ret.toString(); 
 }
 
 private static boolean isSpecialTag(String tagName) 
 {
  return specialtags.contains(tagName);
 }
 
 
}

Friday, 15 September 2017

Error - trustAnchors parameter must be non-empty

Question: Error - trustAnchors parameter must be non-empty

Answer:
It means either you have not provided your trust store or your policy jars not supported.
Replace JCE Policy Jars in order to support bigger encryption algorithm key lengths and trustAnchors issue.