Monday, July 2, 2018

Boost the speed of calculating Large Primes with Golang

Following points are used

1. Check whether the last digit of the integer can be divided by 2 or not
2. Check whether the sum of all digits of the integer can be divided by 3 or not
3. Check whether the last digit of the integer can be divided by 5 or not
4. If all the above checks fails Check whether there is an integer from 7 to square root of number which is divide the number




package main import ( "fmt" "math" "strconv" ) func main() { fmt.Printf("275489 is a prime : %t", isPrime(275489)) } func isPrime(num int) bool { if !canBeDivideBy2(num) && !canBeDivideBy3(num) && !canBeDivideBy5(num) { isPrime := true //If the number can not be divided by 2, 3 or 5 divide from 7 to squre root of the number to check the existence of a factor for i := 7; i <= int(math.Sqrt(float64(num))); i++ { if num%i == 0 { isPrime = false break } } return isPrime } return false } // If the last digit can be divided by 2 whole number can be divided by 2 func canBeDivideBy2(num int) bool { numAsStr := strconv.Itoa(num) lastNum, _ := strconv.Atoi(string(numAsStr[len(numAsStr)-1])) return lastNum%2 == 0 } // If the digit sum can be divided by 3 whole number can be divided by 3 func canBeDivideBy3(num int) bool { numAsStr := strconv.Itoa(num) sum := 0 for i := 0; i < len(numAsStr); i++ { iThNum, _ := strconv.Atoi(string(numAsStr[i])) sum += iThNum } return sum%3 == 0 } //If the last digit can be divided by 5 whole number can be divided by 5 func canBeDivideBy5(num int) bool { numAsStr := strconv.Itoa(num) lastNum, _ := strconv.Atoi(string(numAsStr[len(numAsStr)-1])) return lastNum%5 == 0 }

Check last JRE access time

JRE will create and update a file in a directory called oracle_jre_usage located  in
  • Windows : %ProgramData%\Oracle\Java\.oracle_jre-usage\ 
  • All other operating systems: ${user.home}/.oracle_jre_usage/
ex: I have used ubuntu 18.04. So when I start intellij idea it will create a file like  below

lakshman@lakshman-Latitude-3580:~/.oracle_jre_usage$ vim 9e360713136aba0a.timestamp

File content is as follows

/usr/lib/jvm/java-8-oracle/jre
1530512372457
~       

As you can see the last access time can be found in timestamp format.

From JDK 8u171 and later updates and JDK 10 and later, usage tracking can be disabled by using jdk.disableLastUsageTracking property.

ex: java -Djdk.disableLastUsageTracking=true -jar lastUsageTracking-executable.jar

Wednesday, July 5, 2017

PDF generation with Apache FOP

What is Apache FOP?
Apache FOP is a print formatter driven by XSL formatting objects(XSL-FO). It is a library to read XSL FO objects and generate documents with specified output format. Here I have used pdf as the output format.

What is XSL?

XSL is a language for expressing stylesheets. It describes how to display data in an XML file.

What is XSL FO?

XSL FO is a part of XSL which is a markup language for XML document formatting. Follow W3school tutorial for XSL FO.

How Apache FOP generate PDFs.


I have generated javaFX form to enter the data and when I click the print button after filling data, PDF will be created in a folder called PDFs. source code for this available in https://github.com/laki88/PatientDischargeForm.




Thursday, March 23, 2017

JDBC drivers and connection strings

Recently I was fixing a bug in gadget creation in WSO2 DAS 3.1.0 in which gadget creation throws errors on some database types. So I have to check for major database types for gadget creation and I came up with following database drivers and connection strings and little more information their JDBC drivers.

MySQL
Driver class : com.mysql.jdbc.Driver
Connection string : jdbc:mysql://localhost:3306/databaseName

You can download JDBC driver from their official site.

MSSQL
Driver class : com.microsoft.sqlserver.jdbc.SQLServerDriver
Connection string :jdbc:sqlserver://hostName:1433;database=databaseName

You can download MSSQL driver from microsoft site. According to the JRE it comes from several flavours as below.

• Sqljdbc41.jar requires a JRE of 7 and supports the JDBC 4.1 API
• Sqljdbc42.jar requires a JRE of 8 and supports the JDBC 4.2 API

Apart from official MSSQL driver there are other supported drivers like jtds as well. You can find more information about them by referring this stackoverflow question.

PostgreSQL
Driver class : org.postgresql.Driver
Connection string : jdbc:postgresql://localhost:5432/databaseName

You can download the PostgreSQL driver from their official site and it also comes in different flavours depend on the Java version. It would be very easy to work with PostgresSQL if you are using postgres.app. For mac users, note that to uninstall all previous versions of PostgreSQL versions to work with postgres app.

DB2
Driver class : com.ibm.db2.jcc.DB2Driver
Connection string : jdbc:db2://myhost:5021/mydb

You can download db2 JDBC driver from their official site.

Oracle
Driver class : oracle.jdbc.OracleDriver
Connection string : jdbc:oracle:thin:@hostName:1521/wso2qa11g

You can download Oracle JDBC driver from their official site.

Tuesday, February 28, 2017

Simple wait and notify example in Java

This example demonstrate wait and notify example. Main thread(ThreadA) will create threadB and will start threadB. After threadB started, it just print that it is started and will go to WAITING state by calling wait(). Meanwhile threadA goes to sleep for 3 seconds and will print that it is awaked and will notify threadB by calling notify(). This will cause to threadB goes to RUNNABLE state. Then it will resume the threadB's execution and will print that it is notified.


Note that when we call wait() and notify(), it should call inside synchronised context. Otherwise it will throw java.lang.IllegalMonitorStateException. We have to pass a lock object to the synchronised block. That object will be blocked during the execution of synchronisation block. In this case I pass the threadB itself as the lock object.

Monday, January 23, 2017

Customize the place where tomcat instance creating for wso2 4.4.x servers

WSO2 4.4.x servers run on an OSGIfied tomcat. It creates the tomcat instance on <CARBON_HOME>/lib/tomcat directory. You can customize this path to your own one by changing the property "catalina.base" in wso2server.sh.

Friday, April 29, 2016

Policy add using Rest API in WSO2 EMM

You can add a policy using REST API given in EMM. For the use the dynamic registration client given.
below sample curl command will return client id and secret


curl -k -H "Content-Type: application/json" -X POST -d '{"owner":"admin","clientName":"admin_emm","grantType":"refresh_token password client_credentials","tokenScope":"prod"}' https://localhost:9443/dynamic-client-web/register

This will return a response like below

{"client_secret":"YCnfi_jp9Tso0qyRcbGxaQnYctga","callback_url":null,"client_id":"xJvKvUHNYqfK1MeQ_VybtBfF5MAa","client_name":"admin_admin_emm"}

Use the client id and secret by encoding using base64 to generate access token using below command

curl -k -d "grant_type=password&username=admin&password=admin&scope=default " -H "Authorization: Basic eEp2S3ZVSE5ZcWZLMU1lUV9WeWJ0QmZGNU1BYTpZQ25maV9qcDlUc28wcXlSY2JHeGFRblljdGdh" -H "Content-Type: application/x-www-form-urlencoded" https://localhost:9443/oauth2/token

This will return a response like below

{"scope":"default","token_type":"Bearer","expires_in":3600,"refresh_token":"97c3c78b8c2c4e2ccd5424ffc7259d3e","access_token":"60a810d5baa3361af9aa5e6d8cf76ea9"}

Use the generated access token to call the policy publishing API. 

Below is a sample curl command to create black list policy

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer 60a810d5baa3361af9aa5e6d8cf76ea9" -d @'operation.json' -k -v https://localhost:9443/mdm-admin/policies/active-policy


Resource path  : /active-policy
URL : /mdm-admin/policies/active-policy
HTTP Method : POST
Request/Response format : application/json

Sample payload in operation.json is 

{
  "policyName": "black list",
  "description": "",
  "compliance": "enforce",
  "ownershipType": "ANY",
  "profile": {
    "profileName": "black list",
    "deviceType": {
      "id": 1
    },
    "profileFeaturesList": [
      {
        "featureCode": "APP-RESTRICTION",
        "deviceTypeId": 1,
        "content": {
          "restriction-type": "black-list",
          "restricted-applications": [
            {
              "appName": "app name1",
              "packageName": "package1"
            },
            {
              "appName": "app name2",
              "packageName": "package2"
            },
            {
              "appName": "app name3",
              "packageName": "package3"
            }
          ]
        }
      }
    ]
  },
  "roles": [
    "ANY"
  ]
}


After making above curl command you will get successful response as below

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: localhost
> POST /mdm-admin/policies/active-policy HTTP/1.1
> Host: localhost:9443
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Type: application/json
> Authorization: Bearer 60a810d5baa3361af9aa5e6d8cf76ea9
> Content-Length: 460
* upload completely sent off: 460 out of 460 bytes
< HTTP/1.1 200 OK
< Date: Fri, 29 Apr 2016 11:19:39 GMT
< Content-Type: application/json
< Content-Length: 76
< Server: WSO2 Carbon Server
* Connection #0 to host localhost left intact
{"statusCode":201,"messageFromServer":"Policy has been added successfully."}

Created policy bundle will show in policy management window of EMM UI.

Boost the speed of calculating Large Primes with Golang

Following points are used 1. Check whether the last digit of the integer can be divided by 2 or not 2. Check whether the sum of all digit...