Saturday, October 28, 2017

Algorithm

BinaryGap

binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of .N. 

public int solution(int N) {
String binaryNo = Integer.toBinaryString(N);
int firstIndex = binaryNo.lastIndexOf("1");
int currentGap = 0;
int biggestGap = 0;
for (int i = firstIndex; i >= 0; i--) {
if (getNthDegit(binaryNo, i) == 0) {
currentGap++;
} else {
if (biggestGap < currentGap) {
biggestGap = currentGap;
}
currentGap = 0;
}
}
return biggestGap;
}

public static int getNthDegit(String number, int position) {
String numberString = "" + number;
char c = numberString.charAt(position);
return Character.getNumericValue(c);
}


OddOccurrencesInArray

Find value that occurs in odd number of elements.

public int solution(int[] A) { int num = 0; int max = 0; for (int i = 0; i < A.length; i++) { if (max <= A[i]) { max = A[i]; } } int[] B = new int[max]; for (int i = 0; i < A.length; i++) { if (B[A[i] - 1] == 0) { B[A[i] - 1] = A[i]; } else { B[A[i] - 1] = 0; } } for (int i = 0; i < B.length; i++) { if (B[i] != 0) { num = B[i]; break; } } return num; }


CyclicRotation

Each element is shifted right by one index, and the last element of the array is also moved to the first place.


public int[] solution(int[] A, int K) { if (K > 0 && A.length > 0) { K = K % A.length; int[] B = new int[A.length]; for (int i = 0; i < A.length; i++) { if ((i + K) > (A.length - 1)) { B[i + K - A.length] = A[i]; } else { B[i + K] = A[i]; } } return B; } else { return A; } }

FrogJmp

Count minimal number of jumps from position X to Y.

public int solution(int X, int Y, int D) { if (X == Y) return 0; else if ((Y - X) % D == 0) return ((Y - X) / D); else return ((Y - X) / D) + 1; }

Distinct

Compute number of distinct values in an array.

public int solution(int[] A) { Set<Integer> s = new HashSet<>(); for (int i = 0; i < A.length; i++) { s.add(A[i]); } return s.size(); }


CountDiv

Compute number of integers divisible by k in range [a..b].

public int solution(int A, int B, int K) {
return (B / K) - (A / K) + ((A % K) == 0 ? 1 : 0); }


TapeEquilibrium

Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|.

public int solution(int[] A) {
int N = A.length; int leftsum = 0; int difference; int rightSum; int min = Integer.MAX_VALUE; int sum = 0; for (int i = 0; i < N; i++) { sum = sum + A[i]; } for (int i = 0; i < N - 1; i++) { leftsum = leftsum + A[i]; rightSum = sum - leftsum; difference = Math.abs(rightSum - leftsum); min = Math.min(min, difference); } return min; }


Friday, July 14, 2017

Simple JSP Ajax Tutorial

In this blog post, a simple JSP Ajax sample for adding two numbers.  Ajax is a method for returning a result without reloading the HTML page using JavaScript, DOM, XMLHttpRequest and CSS technologies.

ajaxsample.html

<html>
<head>
<script type="text/javascript">
var request;
function addnum() {
var num1 = document.addform.num1.value;
var num2 = document.addform.num2.value;
var url = "sum.jsp?num1=" + num1 + "&num2=" + num2;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}

try {
request.onreadystatechange = getsum;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to process");
}
}

function getsum() {
if (request.readyState == 4) {
var sum = request.responseText;
document.getElementById("sumvalue").innerHTML = sum;
}
}
</script>
</head>
<body>
<h1>JSP Ajax Simple Example</h1>
<form name="addform">
<input type="text" name="num1"> + <input type="text"
name="num2"> <input type="button" value="Add"
onclick="addnum()">
</form>
<span id="sumvalue"></span>
</body>
</html>


sum.jsp

<%
int num1 = Integer
.parseInt(request.getParameter("num1").toString());
int num2 = Integer
.parseInt(request.getParameter("num2").toString());
int sum = num1 + num2;
out.print("Sum is " + sum);
%>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <session-config>
        <session-timeout>
            30
   </session-timeout>
 </session-config>
 <welcome-file-list>
        <welcome-file>ajaxsample.html</welcome-file>
        </welcome-file-list>
 </web-app>

Wednesday, September 14, 2016

Email OTP Two Factor Authentication through Identity Server

In this post, I will explain how to use Email OTP two authenticator through WSO2 Identity server. In this demonstration, I am using SMTP mail transport which was used to send the OTP code via email at the time authentication happens.






















Add the authenticator configuration  <IS_HOME>/repository/conf/identity/application-authentication.xml file under the <AuthenticatorConfigs> section.

<AuthenticatorConfig name="EmailOTP" enabled="true">
     <Parameter name="GmailClientId">gmailClientIdValue</Parameter>
     <Parameter name="GmailClientSecret">gmailClientSecretValue</Parameter>
     <Parameter name="SendgridAPIKey">sendgridAPIKeyValue</Parameter>
     <Parameter name="EMAILOTPAuthenticationEndpointURL">https://localhost:9443/emailotpauthenticationendpoint/emailotp.jsp</Parameter>
     <Parameter name="EmailOTPAuthenticationEndpointErrorPage">https://localhost:9443/emailotpauthenticationendpoint/emailotpError.jsp</Parameter>
     <Parameter name="EmailAddressRequestPage">https://localhost:9443/emailotpauthenticationendpoint/emailAddress.jsp</Parameter>
     <Parameter name="GmailRefreshToken">gmailRefreshTokenValue</Parameter>
     <Parameter name="GmailEmailEndpoint">https://www.googleapis.com/gmail/v1/users/[userId]/messages/send</Parameter>
     <Parameter name="SendgridEmailEndpoint">https://api.sendgrid.com/api/mail.send.json</Parameter>
     <Parameter name="accessTokenRequiredAPIs">Gmail</Parameter>
     <Parameter name="apiKeyHeaderRequiredAPIs">Sendgrid</Parameter>
     <Parameter name="SendgridFormData">sendgridFormDataValue</Parameter>
     <Parameter name="SendgridURLParams">sendgridURLParamsValue</Parameter>
     <Parameter name="GmailAuthTokenType">Bearer</Parameter>
     <Parameter name="GmailTokenEndpoint">https://www.googleapis.com/oauth2/v3/token</Parameter>
     <Parameter name="SendgridAuthTokenType">Bearer</Parameter>
     <Parameter name="usecase">association</Parameter>
     <Parameter name="secondaryUserstore">primary</Parameter>
     <Parameter name="EMAILOTPMandatory">true</Parameter>
     <Parameter name="sendOTPToFederatedEmailAttribute">false</Parameter>
     <Parameter name="federatedEmailAttributeKey">email</Parameter>
     <Parameter name="EmailOTPEnableByUserClaim">true</Parameter>
     <Parameter name="CaptureAndUpdateEmailAddress">true</Parameter>
     <Parameter name="showEmailAddressInUI">true</Parameter>
</AuthenticatorConfig>

Configure the Service Provider and Identity Provider Configuration as we normally configure for Two factor authentication. Now we will configure EmailOTP Identity provider for SMTP transport.






 
 
 
 
 
 
 
SMTP transport sender configuration.
   Add the SMTP transport sender configuration in the <IS_HOME>/repository/conf/axis2/axis2.xml file.
  Here you need to replace {USERNAME}, {PASSWORD} and {SENDER'S_EMAIL_ID} with real values.

<transportSender name="mailto" class="org.apache.axis2.transport.mail.MailTransportSender">
       <parameter name="mail.smtp.host">smtp.gmail.com</parameter>
       <parameter name="mail.smtp.port">587</parameter>
       <parameter name="mail.smtp.starttls.enable">true</parameter>
       <parameter name="mail.smtp.auth">true</parameter>
       <parameter name="mail.smtp.user">{USERNAME}</parameter>
       <parameter name="mail.smtp.password">{PASSWORD}</parameter>
       <parameter name="mail.smtp.from">{SENDER'S_EMAIL_ID}</parameter>
</transportSender>

Comment <module ref="addressing"/> module from axis2.xml in <IS_HOME>/repository/conf/axis2.
Email Template configuration.
Add the email template in the <IS_HOME>/repository/conf/email/email-admin-config.xml file.

    <configuration type="EmailOTP">
           <targetEpr></targetEpr>
           <subject>WSO2 IS EmailOTP Authenticator One Time    Password</subject>
           <body>
       Hi,
       Please use this OTP {OTPCode} to go with EmailOTP authenticator.
           </body>
           <footer>
       Best Regards,
       WSO2 Identity Server Team
       http://www.wso2.com
           </footer>
           <redirectPath></redirectPath>
    </configuration>


When authentication is happening in second step, the code will be sent to email  which is saved in email claim of  user's user profile.
If the user apply the code, WSO2 IS will validate the code and let the user sign in accordingly.

SMS OTP Two Factor Authentication through Identity Server

In this post, I will explain how to use SMS OTP multifactor authenticator through WSO2 Identity server. In this demonstration, I am using Twilio SMS Provider which was used to send the OTP code via SMS at the time authentication happens.


SMS OTP Authentication Flow



















The SMS OTP authenticator of WSO2 Identity Server allows to authenticate the system using multifactor authentication. This authenticator authenticates with user name and password as a first step, then sending the one time password to the mobile via SMS as a second step. WSO2 IS will validate the code and let the user sign in accordingly

Add the authenticator configuration <IS_HOME>/repository/conf/identity/application-authentication.xml file under the <AuthenticatorConfigs> section.

<AuthenticatorConfig name="SMSOTP" enabled="true">
    <Parameter name="SMSOTPAuthenticationEndpointURL">https://localhost:9443/smsotpauthenticationendpoint/smsotp.jsp</Parameter>
    <Parameter name="SMSOTPAuthenticationEndpointErrorPage">https://localhost:9443/smsotpauthenticationendpoint/smsotpError.jsp</Parameter>
    <Parameter name="MobileNumberRegPage">https://localhost:9443/smsotpauthenticationendpoint/mobile.jsp</Parameter>
    <Parameter name="RetryEnable">true</Parameter>
    <Parameter name="ResendEnable">true</Parameter>
    <Parameter name="BackupCode">true</Parameter>
    <Parameter name="SMSOTPEnableByUserClaim">false</Parameter>
    <Parameter name="SMSOTPMandatory">false</Parameter>
    <Parameter name="usecase">association</Parameter>
    <Parameter name="secondaryUserstore">primary</Parameter>
    <Parameter name="CaptureAndUpdateMobileNumber">true</Parameter>
    <Parameter name="SendOTPDirectlyToMobile">false</Parameter>
</AuthenticatorConfig>

Configure the Service Provider and Identity Provider Configuration as we normally configure for Two factor authentication. Now we will configure SMS OTP Identity provider for Twilio specific SMS Provider.

Go to ​ https://www.twilio.com/try­twilio​  and create a twilio account.

While registering the account, verify your mobile number and click on console home
https://www.twilio.com/console​  to get free credits (Account SID and Auth Token).




Twilio uses a POST method with headers and the text message and phone number are sent asthe payload. So the fields would be as follows.

SMS URL             https://api.twilio.com/2010­04­01/Accounts/{AccountSID}/SMS/Messages.json
HTTP Method     POST
HTTP Headers    Authorization: Basic base64{AccountSID:AuthToken}
HTTP Payload    Body=$ctx.msg&To=$ctx.num&From={FROM_NUM}

You can go to SMS OTP Identity Provider and configure to send the SMS using Twilio SMS Provider.

Twilio SMS Provider Config





















When authentication is happening in second step, the code will be sent to mobile no which is saved in mobile claim of  user's user profile.
If the user apply the code, WSO2 IS will validate the code and let the user sign in accordingly.

Monday, April 4, 2016

WSO2 ESB Kafka Inbound and Kafka Connector Performance tuning

In this post, I am going to explain about Kafka connector and Kafka inbound endpoint performance with WSO2 ESB 4.9 and how to tune the performance for producer and consumer use cases. The performance test of Kafka inbound endpoint and Kafka connector was carried out on below machine configuration:

Performance Test Environment :
OS: Ubuntu 64-bit
Memory: 16GiB
Processor: Intel Core i7-4800MQ CPU 2.70GHzx8

ESB Kafka Connector

WSO2 ESB Kafka connector allows you to send the data to Kafka message broker.  


ThreadsMessages per a ThreadNo of MessagesA Message Size(byte)Throughput (/s)
101001,000106831
105005,0001061590
2050010,0001062251
10025025,0001062940
1,00015001,500,0001062780

Average Throughput(/s) - 2767

You can get highest throughput with default ESB configuration.

ESB Kafka Inbound Endpoint


WSO2 ESB Kafka Inbound endpoint allows you to consume the data from Kafka message broker. 


https://docs.wso2.com/display/ESB490/Working+with+Inbound+Endpoints



Above document includes inbound endpoint common parameters and how to change them for best performance. Even though I provide some recommended values with the performance tuning stats.

You can tune the Kafka inbound endpoint performance by changing the inbound thread pool values. The values can be changed in the location.


<ESB_HOME>/repository/conf/synapse.properties file


On  Sequential Mode

The following performance stat is measured with default inbound thread pool values and sequential mode.

ThreadsMessages per a ThreadNo of MessagesA Message Size(byte)Throughput (/s)
101001,00010616
105005,00010616
2050010,00010615

Average Throughput(/s) - 15

On Non Sequential Mode


The following performance stat is measured with default inbound thread pool values and non sequential mode.

inbound.threads.core = 20

inbound.threads.max = 100  

ThreadsMessages per a ThreadNo of MessagesA Message Size(byte)Throughput (/s)
101001,000106150
105005,000106151
2050010,000106126
10025025,000106136

We have gone through the performance test with default inbound thread pool.
Average Throughput(/s) - 135

Now we have increased the thread pool values and gone through the performance test.

inbound.threads.core = 200

inbound.threads.max = 1000

ThreadsMessages per a ThreadNo of MessagesA Message Size(byte)Throughput (/s)
10010010,000106769
100010001,000,000106800

We can get the throughput around 800 with above thread pool values. 
Average Throughput(/s) - 799

Now we have increased the inbound thread pool values further. The performance is measured with below inbound thread pool values and non sequential mode. The throughput is 711. There is no significant improvement compared with previous throughput.


inbound.threads.core = 500

inbound.threads.max = 2000

ThreadsMessages per a ThreadNo of MessagesA Message Size(byte)Throughput (/s)
10010010,000106757
1,00010001,000,000106710

Average Throughput(/s) - 711


You can configure the inbound common parameters according to this performance stats and see massive performance improvements with the inbound thread pool. To get highest performance, I recommend you to use the following inbound thread pool values with non sequential mode.

inbound.threads.core = 200
inbound.threads.max = 1000

Algorithm

BinaryGap A  binary gap  within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both end...