1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
2) Java final method
If you make any method as final, you cannot override it.
3)Java final class
If you make any class as final, you cannot extend it.
Q)Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
Q)Can we initialize blank final variable?
Yes, but only in constructor. For example:
Q)static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it. int cube(final int n){ n = n+2; }
Q)Can we declare a constructor final?
No, because constructor is never inherited.
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Friday, 2 August 2019
Friday, 12 October 2018
Java + SOAP API
<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>javax.xml.soap-api</artifactId>
<version>1.3.8</version>
</dependency>
package com.google.soap;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Base64;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class Final {
public static void main(String[] args) throws SOAPException {
String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/ </soapenv:Body></soapenv:Envelope>";
SOAPConnection connection = null;
String authorization = Base64.getEncoder()
.encodeToString(("uname" + ":" + "pwd").getBytes(Charset.forName("UTF-8")));
String endPointURLString = "http://googlec.om/abc";
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
connection = soapConnectionFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage request = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(str.getBytes()));
MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Authorization", "Basic " + authorization);
headers.addHeader("SOAPAction", "getSum");
headers.addHeader("Content-Type", "multipart/related; type=\"text/xml\";");
request.saveChanges();
SOAPMessage response = connection.call(request, endPointURLString);
System.out.println(getResspString(response));
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
connection.close();
}
}
public static String getResspString(SOAPMessage response) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(response.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}
<groupId>javax.xml.soap</groupId>
<artifactId>javax.xml.soap-api</artifactId>
<version>1.3.8</version>
</dependency>
package com.google.soap;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Base64;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class Final {
public static void main(String[] args) throws SOAPException {
String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/ </soapenv:Body></soapenv:Envelope>";
SOAPConnection connection = null;
String authorization = Base64.getEncoder()
.encodeToString(("uname" + ":" + "pwd").getBytes(Charset.forName("UTF-8")));
String endPointURLString = "http://googlec.om/abc";
try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
connection = soapConnectionFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage request = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(str.getBytes()));
MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Authorization", "Basic " + authorization);
headers.addHeader("SOAPAction", "getSum");
headers.addHeader("Content-Type", "multipart/related; type=\"text/xml\";");
request.saveChanges();
SOAPMessage response = connection.call(request, endPointURLString);
System.out.println(getResspString(response));
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
connection.close();
}
}
public static String getResspString(SOAPMessage response) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(response.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}
Thursday, 11 October 2018
JAVA + SOAP API CALL
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static void main2(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);
String strXMLFilename = "C:\\Users\\KKasthuri\\Documents\\req.xml";
File input = new File(strXMLFilename);
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
String url = "http://abc.com/xyx/proj";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "getmthods");
((EntityEnclosingMethod) method).setRequestEntity(entity);
client.executeMethod(method);
String response = method.getResponseBodyAsString();
System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}
public static void main4(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);
String url = "http://google.com/test";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "MyMethod");
method.setRequestHeader("Content-Type", "text/xml");
((EntityEnclosingMethod) method).setRequestEntity(new StringRequestEntity(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://yieldstar.com/ws/AppExchange/v1\"><soapenv:Header/><soapenv:Body></soapenv:Body></soapenv:Envelope>"));
client.executeMethod(method);
String response = method.getResponseBodyAsString();
System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static void main2(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);
String strXMLFilename = "C:\\Users\\KKasthuri\\Documents\\req.xml";
File input = new File(strXMLFilename);
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
String url = "http://abc.com/xyx/proj";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "getmthods");
((EntityEnclosingMethod) method).setRequestEntity(entity);
client.executeMethod(method);
String response = method.getResponseBodyAsString();
System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}
public static void main4(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);
String url = "http://google.com/test";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "MyMethod");
method.setRequestHeader("Content-Type", "text/xml");
((EntityEnclosingMethod) method).setRequestEntity(new StringRequestEntity(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://yieldstar.com/ws/AppExchange/v1\"><soapenv:Header/><soapenv:Body></soapenv:Body></soapenv:Envelope>"));
client.executeMethod(method);
String response = method.getResponseBodyAsString();
System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}
Wednesday, 25 April 2018
Java Program : write a method to check if it is well formed expression. Eg: {[()]}
This question was asked in an interview that I found interesting.
Here you go.
I know, There are other ways to do it better.
Map<Character, Character> exprssionMap = new HashMap<>();
exprssionMap.put('{', '}');
exprssionMap.put('[', ']');
exprssionMap.put('(', ')');
String inputExpression = "{[({{)}}]}";
int expressionLengh = inputExpression.length();
if (expressionLengh % 2 == 1) {
System.out.println("malformed Expression; Size of the Expression is not even number");
} else {
for (int i = 0; i < expressionLengh / 2; i++) {
if (!exprssionMap.get(inputExpression.charAt(i))
.equals(inputExpression.charAt(expressionLengh - 1 - i))) {
System.out.println(
"Matching expression not found for: " + inputExpression.charAt(i) + "; index:" + i);
}
}
}
Happy Coding.
Here you go.
I know, There are other ways to do it better.
Map<Character, Character> exprssionMap = new HashMap<>();
exprssionMap.put('{', '}');
exprssionMap.put('[', ']');
exprssionMap.put('(', ')');
String inputExpression = "{[({{)}}]}";
int expressionLengh = inputExpression.length();
if (expressionLengh % 2 == 1) {
System.out.println("malformed Expression; Size of the Expression is not even number");
} else {
for (int i = 0; i < expressionLengh / 2; i++) {
if (!exprssionMap.get(inputExpression.charAt(i))
.equals(inputExpression.charAt(expressionLengh - 1 - i))) {
System.out.println(
"Matching expression not found for: " + inputExpression.charAt(i) + "; index:" + i);
}
}
}
Happy Coding.
Thursday, 16 February 2017
Read soap xml file using xpath
import org.apache.xmlbeans.impl.xb.xsdschema.FieldDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.FileReader;
public class SoapReaderUsingXpath {
public static void main(String[] args){
String result ="";
String soapXmlFile;
DocumentBuilderFactory dbf;
DocumentBuilder db;
Document doc;
XPath xpath;
Node nl;
soapXmlFile="C:\\wssoap.xml";
String myXpath="//Element/Body/Node1/text()";
try{
dbf=DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
db=dbf.newDocumentBuilder();
doc=db.parse(new InputSource(new FileReader(soapXmlFile)));
xpath= XPathFactory.newInstance().newXPath();
nl=(Node)xpath.evaluate(myXpath,doc.getDocumentElement(), XPathConstants.NODE);
result=nl.getNodeValue();
}
catch (Exception ex){}
}
}
Wednesday, 1 February 2017
Api testing : Get
Simple GetApi code:
Maven dependency:
<!--For Http Get/Post/ect we need HTTP client libs :: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
public class TestGet {
public static void main(String[] args) {
String url = "https://httpbin.org/get";
HttpResponse response = null;
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
builder.setConnectionManager(connectionManager);
HttpClient httpclient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
/*
* connectionRequestTimeout happens when you have a pool of
* connections and they are all busy, not allowing the
* connection manager to give you one connection to make the
* request.
*/
.setConnectionRequestTimeout(30000)
/*
* connectTimeout happens when establishing the connection. For
* instance while doing the tcp handshake.
*/
.setConnectTimeout(30000)
/*
* socketTimeout: is the timeout while waiting for data. Usually
* happens when your server is slow
*/
.setSocketTimeout(30000).build();
try {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(responseBody);
System.out.println(jsonObj.get("origin"));
//Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (IOException ex) {
}
}
}
Maven dependency:
<!--For Http Get/Post/ect we need HTTP client libs :: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;
public class TestGet {
public static void main(String[] args) {
String url = "https://httpbin.org/get";
HttpResponse response = null;
HttpClientBuilder builder = HttpClientBuilder.create();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
builder.setConnectionManager(connectionManager);
HttpClient httpclient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
/*
* connectionRequestTimeout happens when you have a pool of
* connections and they are all busy, not allowing the
* connection manager to give you one connection to make the
* request.
*/
.setConnectionRequestTimeout(30000)
/*
* connectTimeout happens when establishing the connection. For
* instance while doing the tcp handshake.
*/
.setConnectTimeout(30000)
/*
* socketTimeout: is the timeout while waiting for data. Usually
* happens when your server is slow
*/
.setSocketTimeout(30000).build();
try {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(responseBody);
System.out.println(jsonObj.get("origin"));
//Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (IOException ex) {
}
}
}
Eclipse - Maven - Archetype
Here is the archetype for a new maven project for automation
maven-archetype-quickstart
maven-archetype-quickstart
Adding multiple modules in one project : eclipse
A project can consist multiple modules, where a
module is a project with some dependency on each other.
Create a Parent project: ( which behaves like parent to further maven
modules)
File – New – Other –
Maven Project
Check “Create a
simple Project (Skip archetype selection)
Next
Group id : com.parent
Artifact id : parent
Packaging : POM ß
Finish
This is how pom.xml looks like
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.parent</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
Create a child / maven module:
File – New – Other –
Maven Module
Check “Create a
simple Project (Skip archetype selection)
Module Name: Child
Parent Project:
Parent
Finish
This is how pom.xml looks like
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.parent</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>child</artifactId>
</project>
Observations:
In child pom.xml: observe
that parent tag, which talks about who is my parent
Note: any dependencies declared in parent pom.xml are available to
child pom.xml by default.
Testing:
GO to parent pom.xml
file folder and say > mvn clean
Now two projects will
be created.
Friday, 5 August 2016
First Gradle project | IntellJ
Gradle is one more tool for build management besides ANT, Maven etc.
Below are the steps to configure for the first time.
Download and Configuration:
Gradle is downloadable as a zip file at http://www.gradle.org/downloads.
Only the binaries are required, so look for the link to
gradle-version-bin.zip.
Unzip the file to your computer, and add the bin folder to
your path.
Testing:
From the command-line:
> gradle
You will get ‘BUILD SUCCESSFUL’
If you are still not able to see ‘Gradle’ option in Intellij
Run below command.
>gardle init
First Gradle project:
Open IntelliJ idea – File – New – Project
Choose Gradle from left panel and select Java Checkbox.
Key in GroupId and ArtifactID.
Select below 3 options for easy configuration:
- -Use Auto Import
- - Create Directories for empty content roots
automatically
- - Use local gradle distribution
Choose appropriate project name and location.
Click on FINISH button.
Takes few minutes to create initial gradle project.
If you see any issues reg importing gradle dependencies,
File - settings - Build,Execution,Deployment - Gradle - Uncheck 'offline work'
Thats all.
Friday, 22 April 2016
Selenium POM ( Page object model) Project
-
Create a Maven project as explained here. http://kranthikasthuri.blogspot.com/2016/04/how-to-create-maven-project-in-eclipse.html
-
Lets add Selenium and TestNg Maven dependencies
in pom.xml
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
</dependencies>
-
The moment you add above code in pom.xml, IDE
starts to download the said jars
-
Now maven dependencies looks like this.
Java
coding part:
-
Now create packages for Page object model as
shown below.
-
Driver object creation
o
I have used singleton design patterns to create.
Here you can find it. http://kranthikasthuri.blogspot.com/2016/04/design-patterns-singleton-single-object.html
o
MyDriver.java contains only Driver object related
stuff
-
Now, Lets work on POM
o
What is POM : Segregating Locators , pages and
Tests related to each page for better maintenance.
- HomePageLocators
- HomePage
- HomePageTests
o
Locators:
§
This this the palace where all your Specific
page level locators exists.
o
Pages:
§
This is the places where all your specific page
level locators exists
o
Tests:
§
This is the places where all your specific page
level Test cases exists
-
For Running the project:
o
Right click on POM.xml and select maven test
-
If you are facing any issues please check below
points
o
Make sure you had an entry in pom.xml which is
related to testing dependency
o
You test class file must end with Test
o
M2_Maven variable must be added
Wednesday, 20 April 2016
How to create Maven project in Eclipse for Java.
Maven is a very nice build and configuration tool that helps us specify the jar as a GAV (group, artifact, version) in a xml file, that helps manage the project dependencies in a succinct manner.
Steps for creating maven project.
a.
Open Eclipse and got to File -> New ->
Other
b.
Search with ‘Maven’ and select Maven Project.
*** If you are not able to locate MavenProject here, please install maven add on in eclipse.
Eclipse - Help - Install new software and link is http://download.eclipse.org/technology/m2e/releases/
*** If you are not able to locate MavenProject here, please install maven add on in eclipse.
Eclipse - Help - Install new software and link is http://download.eclipse.org/technology/m2e/releases/
c.
Un-check the ‘Use default
Workspace location‘ and choose your workspace .
d.
Select the archetype, for now
just select the ‘maven-aechetype-quickstart‘.
e.
Specify the Group Id & Artifact
Id and click on Finish.
f.
Here is the pom.xml
g.
Right click on the pom.xml and go to Run As > Maven test.
h.
Here are the logs.
Monday, 18 April 2016
Design Patterns : singleton / Single Object class
Here is the simple definition.
Single Object class have its constructor as private and have a static instance of itself.
Explanation:
1. Private constructor: This stops us creating object for the class, Not even one object creation is allowed.
But, we want one object.
How can we create it?
2. Static instance of itself: Create a instance of self and mark it as static.
'Static' help us to access the instance with out creating object ( Anyways with the point#1, we can not create instance )
public class Singleton { private static Singleton singleton = new Singleton( ); /* A private Constructor prevents any other * class from instantiating. */ private Singleton(){ } /* Static 'instance' method */ public static Singleton getInstance( ) { return singleton; } }
// File Name: SingletonDemo.java public class SingletonDemo { public static void main(String[] args) { Singleton tmp = Singleton.getInstance( ); tmp.demoMethod( ); } }
Tuesday, 25 November 2014
What is abstract ? in OOP Language
You declare a class to be abstract by saying something like:
abstract class Base
{
}
Why would you do this?
To stop it being instantiated.
You cannot then say
Base b = new Base();
But, you can instantiate concrete sub-classes of Base.
Why would you want to stop it being instantiated?
Usually because it is too general.For example, you might define a class Animal and concrete subclasses of Bird, Cat and Dog.
In the real world you can have Cats and Dogs but not Animals which are not some type of Animal.
Using abstract lets you model this situation.
Subscribe to:
Comments (Atom)