Thursday, 20 December 2018

Java Regular Expression to fetch last three characters of String

import java.util.regex.Matcher;

import java.util.regex.Pattern;



public class RegExp {

 
public static void main(String[] args) {

 
String instanceName = "pod3cgs02";

Pattern digitPattern = Pattern.compile("\\d{2}$");

Matcher matcher = digitPattern.matcher(instanceName);
System.out.println(digitPattern.matcher(instanceName).matches());

 
if (matcher.find()) {

System.out.println("find() found substring \"" + matcher.group()

+ "\" starting at index " + matcher.start()

+ " and ending at index " + matcher.end());

}

 
}

}

Sunday, 2 December 2018

XML Parsing Using XPath

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;



import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathExpressionException;

import javax.xml.xpath.XPathFactory;



import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;


public class ParseXml {

public static void main(String[] args) {




try {

FileInputStream file = new FileInputStream(new File("c:/Android_Samples/sample.xml"));




DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();




DocumentBuilder builder = builderFactory.newDocumentBuilder();




Document xmlDocument = builder.parse(file);




XPath xPath = XPathFactory.newInstance().newXPath();




System.out.println("*************************");

String expression = "/Employees/Employee[@emplid='3333']/email";

System.out.println(expression);

String email = xPath.compile(expression).evaluate(xmlDocument);

System.out.println(email);




System.out.println("*************************");

expression = "/Employees/Employee/firstname";

System.out.println(expression);

NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}



System.out.println("*************************");

expression = "/Employees/Employee[@type='admin']/firstname";

System.out.println(expression);

nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}



System.out.println("*************************");

expression = "/Employees/Employee[@emplid='2222']";

System.out.println(expression);

Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

if (null != node) {

nodeList = node.getChildNodes();

for (int i = 0; null != nodeList && i < nodeList.getLength(); i++) {

Node nod = nodeList.item(i);

if (nod.getNodeType() == Node.ELEMENT_NODE)

System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue());


}

}



System.out.println("*************************");




expression = "/Employees/Employee[age>40]/firstname";

nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

System.out.println(expression);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}



System.out.println("*************************");

expression = "/Employees/Employee[1]/firstname";

System.out.println(expression);

nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}

System.out.println("*************************");

expression = "/Employees/Employee[position() <= 2]/firstname";

System.out.println(expression);

nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}



System.out.println("*************************");

expression = "/Employees/Employee[last()]/firstname";

System.out.println(expression);

nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {

System.out.println(nodeList.item(i).getFirstChild().getNodeValue());


}



System.out.println("*************************");




} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (XPathExpressionException e) {

e.printStackTrace();


}

}



}


Following is the sample.xml

<?xml version="1.0"?>
<Employees>
 <Employee emplid="1111" type="admin">
  <firstname>John</firstname>
  <lastname>Watson</lastname>
  <age>30</age>
  <email>johnwatson@sh.com</email>
 </Employee>
 <Employee emplid="2222" type="admin">
  <firstname>Sherlock</firstname>
  <lastname>Homes</lastname>
  <age>32</age>
  <email>sherlock@sh.com</email>
 </Employee>
 <Employee emplid="3333" type="user">
  <firstname>Jim</firstname>
  <lastname>Moriarty</lastname>
  <age>52</age>
  <email>jim@sh.com</email>
 </Employee>
 <Employee emplid="4444" type="user">
  <firstname>Mycroft</firstname>
  <lastname>Holmes</lastname>
  <age>41</age>
  <email>mycroft@sh.com</email>
 </Employee>
</Employees>

Java extract numbers from a Strimg and add Preceeding zeros to it

public class ExtractnumberFromString {




public static void main(String[] args) {
   
String s = "TEST002";

s = s.replaceAll("\\D+","");

String res = s.replaceAll("\\D+","");

System.out.println("Numeric is "+res);

String formatted = String.format("%6s", Integer.toBinaryString(Integer.parseInt(res))).replace(" ", "0");

System.out.println("binary is "+formatted);

 

}

}



Wednesday, 4 April 2018

Swift Basics

var for variables
let for constants
example
var a = 2
var a :Int = 2


if condition
{
code

}


Switch statement
Switch valuetoconsider
{
case value1:
case value2,value3:
default:
}


Loops
for counter in lower...upper
{

}

for(index in 1...5)
{
print(index)

}
o/p 12345


while loop
while condition{
some code
}


repeat while loop
repeat{
code
}while condition

functions
func name()
{
code
}


func name() -> Datatype
{

return ;
}

arguments
func name(argumentLabel parametername:datatype)
{
}




How to create a object for Class


class name{
func test()
{

}

}
create a class object
let objectOne = name()




Inheritance

class subclass : name{

 override func test()
 {


 }
}

Optionals
--------
var title:string?
It means it could be nil or could contain a string
var author:person?
where person is a class
if let actualTitle : post.title{
print("hellso string is not empty");
print(post.tilte! +"zzzz") //This is force wrapping
}

How to resize a view
Click and hold command and then click =

comand + enter to remove the split screen

How to print name and age
print("\(name) , \(age)")

power operators in swift
pow(height , 2) which is height * height
Convert double to string
String(value)
for number in arrauOfNumbers
for number in 1..<10 where number %2==0
{
print(number)
}
we get all even numbers till 9




Hold on command and click on method to read doc of method
Hold on option key and hover on method to read doc of method
By default all the components have tag 0
label.text = "\(intvalue)"
How to use lib project written in objctectve c in our swift project
copy .h , .m ,.bundle in to supporting files
then in bridging file write import .h
Then directly use where ever needed
option +ctrl+i to reindent code (select all and do)
creating enums
enum CarType
{
case Sedan
case Coupe
case Hatchback
}
var typeOfCar : CarType = .Coupe
convinience init(color : String)
{
self.init()
colorProp = color
}
designated initializers needs all the properties
inheritance
class selfDrivingCar : Car
{
}
Cocoapods.org

Tuesday, 3 April 2018

Onclick Listener for a button in IOS

Step 1

Create a new Project in X Code by selecting File --> New Project and then required options

Step 2

Create a new File by selecting File --> new File --> CoCoa Touch Class.Select option of create Xib in the same window
Here three files will be generated sample.h , sample.m and sample.xib

Step 3

Sample.xib is like xml file in android.Open it and drag and drop the required component Button

Step 4

Open the AppDelegate.m file then load the required Xib file (Sample.xib) in the didfinishlaunchingwithoptions method
If you run should be able to see the designed interface

Step 5

Create outlets by selecting a component in xib file and dragging it to the interface .h file

Step 6

Create a method like buttonPressed in sample.controller
like
-(IBAction)buttonPressed:(id)sender
{


//do the necessary things
}


Step 7

Go to xib file right click on the button and then select action like TouchDown and drag it to the fileowner where you can see the method which you have defined

Step 8

Build and Run

Monday, 2 April 2018

UITextField Objective C

Step 1

Create a new Project in X Code by selecting File --> New Project and then required options

Step 2

Create a new File by selecting File --> new File --> CoCoa Touch Class.Select option of create Xib in the same window
Here three files will be generated sample.h , sample.m and sample.xib

Step 3

Sample.xib is like xml file in android.Open it and drag and drop the required component TextField

Step 4

Open the AppDelegate.m file then load the required Xib file (Sample.xib) in the didfinishlaunchingwithoptions method
If you run should be able to see the designed interface

Step 5

Create outlets by selecting a component in xib file and dragging it to the interface .h file

Step 6

We have to use TextField delegate UITextFieldDelegate to use the necessary methods of textfield like editing ,keyboard up down etc

Step 7

Implement the protocol UITextFieldDelegate in the .h file
like
@interface SampleController:UIViewController<UITextFieldDelegate>


Step 8

In SampleController.m you can use delegate methods
example
-(BOOL)
textFieldShouldReturn:(UITextField *)textfield
{

NSLog(@"entered text %@",self.nameTextView.text);
[self.nameTextView resignFirstResponder];
return YES;
}

Step 9

Create delegate and referencing delegate by selecting component in xib file and dragging it to the Files owner .Later right click it and create a referencing outlet

Monday, 26 March 2018

Basic Info On Objective C


Object Creation in objective c

MyClass *objectName = [[MyClass alloc]init] ;

Methods declaration in objective c

-(returnType)methodName:(typeName) variable1 :(typeName)variable2;
-(int) max:(int)num1 andNum2:(int)num2;

How to call

-(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth;



To call this method in the same class, we use the following statement −

[self calculateAreaForRectangleWithLength:30 andBreadth:20];
As said above, the use of andBreadth helps us understand that breadth is 20. Self is used to specify that it's a class method.

Important points



  • By default, Objective-C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function.
  • Blocks
    Blocks are a language-level feature added to C, Objective-C and C++ which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages
  • Simple Block declaration syntax
    returntype (^blockName)(argumentType);
  • Simple block implementation
    returntype (^blockName)(argumentType)= ^{
    };
  • structure
  • structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds.
    Example
  • struct Books
    {
       NSString *title;
       NSString *author;
       NSString *subject;
       int   book_id;
    };
  • struct Books Book1;        /* Declare Book1 of type Book */
     

       /* book 1 specification */
       Book1.title = @"Objective-C Programming";
       Book1.author = @"Nuha Ali";
       Book1.subject = @"Objective-C Programming Tutorial";
       Book1.book_id = 6495407;

     //Printing

     /* print Book1 info */
       NSLog(@"Book 1 title : %@\n", Book1.title);
       NSLog(@"Book 1 author : %@\n", Book1.author);
       NSLog(@"Book 1 subject : %@\n", Book1.subject);
       NSLog(@"Book 1 book_id : %d\n", Book1.book_id);
      
  • Structures can be passed as Function Arguments
  • struct Books Book1;  
  • /* book 1 specification */
       Book1.title = @"Objective-C Programming";
       Book1.author = @"Nuha Ali";
       Book1.subject = @"Objective-C Programming Tutorial";
       Book1.book_id = 6495407;
  •    Method
       - (void) printBook:( struct Books) book
    {
       NSLog(@"Book title : %@\n", book.title);
       NSLog(@"Book author : %@\n", book.author);
       NSLog(@"Book subject : %@\n", book.subject);
       NSLog(@"Book book_id : %d\n", book.book_id);
    }

  •  SampleClass *sampleClass = [[SampleClass alloc]init];
       /* print Book1 info */
       [sampleClass printBook: Book1];
  •    Pointers to Structures
    You can define pointers to structures in very similar way as you define pointer to any other variable as follows:
  • More info in the following link
  • Objective-C Categories
  • Sometimes, you may find that you wish to extend an existing class by adding behavior that is useful only in certain situations. In order add such extension to existing classes, Objective-C provides categories and extensions.
  • Syntax Example
    @interface ClassName (CategoryName)
  • id can be used to represent any kind of data type. It’s the most generic form of specifying data; it simply stands for an “identifier” that is used to reference data. This type of dynamic typing allows for increased flexibility in how we code certain things. In iOS, we often see id used for methods that are tied to controls on the screen, like:
    - (IBAction)save:(id)sender;
  • But notice that the sender parameter is of type id. This allows some flexibility in that our app doesn’t care if the sender is a button or an image or whatever else we might want to use to trigger this action.
  • To set up external libraries into Android projects I used Gradle build system and dependency definitions which were quite clever and easy to handle. The equivalent tool in iOS development is CocoaPods
  • Activity = ViewController
  • Transitions between Screens
  • startActivity(Intent) = Segue
    Segues serve the same functionality as starting an activity through an intent. One really cool feature that XCode has is the ability to create a transition to another screen without writing any code. It saves some time and you’ll quickly wish Google would do the same.
    Lists
  • ListView/RecyclerView = TableView
  • Simply create a TableView or TableViewController to get the same list functionality that you’re used to. This also has methods for populating each item in the list similar to Adapters in Android.
  • APK = Archive
  • Interfaces = Archive
  • Emulator = Simulator
  • How to display float in textfield in IOS
    [NSString stringwithformat:@"%f",floafvalue]
  • int i = [self.textfield.text intValue]

Class Methods

Class methods can be accessed directly without creating objects for the class. They don't have any variables and objects associated with it. An example is shown below.

+(void)simpleClassMethod;
It can be accessed by using the class name (let's assume the class name as MyClass) as follows −

[MyClass simpleClassMethod];

Instance Methods

Instance methods can be accessed only after creating an object for the class. Memory is allocated to the instance variables. An example instance method is shown below.
-(void)simpleInstanceMethod; 
It can be accessed after creating an object for the class as follows −
MyClass  *objectName = [[MyClass alloc]init] ;
[objectName simpleInstanceMethod];

Short Cuts in Xcode
ctrl+cmd+up arrow to jump b/w headre and implementation
cmd+i to launch instruments
cmd+r to run
ARC to memory management
Go to Edit section in the toolbar menu select refactor the select ARC
cmd+b to build


------------------------------------------------
In mac for xcode
options+cmd+enter to open assistant editor
ctrl+mouse click for right click
ctrl+i to reindent code
cmd+/ for comments
cmd+shift+k to clean projects










Tuesday, 27 February 2018

Activity LifeCycle

➤onCreate() — Called when the activity is first created
 ➤onStart() — Called when the activity becomes visible to the user
 ➤onResume() — Called when the activity starts interacting with the user
➤onPause() — Called when the current activity is being paused and the previous activity is being resumed
➤onStop() — Called when the activity is no longer visible to the user
➤onDestroy() — Called before the activity is destroyed by the system (either manually or by the system to conserve memory)
➤onRestart() — Called when the activity has been stopped and is restarting again

onclick of home btn which method called?
onpause onSaveInstanceState and onstop and then onresume
Restart the app after pressing home
onRestart
onStart
onResume


on backpressed?
onPause
onStop
onDestroy
onSaveInstanceState was not called, because there is no current state to resume – when you re-enter you will be back at the beginning
Restart the app after pressing back
onCreate
onStart
onResume

Turn off with the power button
onSaveInstanceState
onPause
 
When the phone was suspended, onSaveInstanceState and onPause were called in different orders, and onStop was called in some cases.
Turn on with the power button
onResume

from one activity to other-
when onrestart is called?
go from act1 to act 2 and when you come back from act2 to act1 on restart-- onstart--on resume is called

 

Friday, 16 February 2018

Android how to Clear App Data Programatically

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//clearApplicationData();  ---Method 1
/* ((ActivityManager)MainActivity.this.getSystemService(ACTIVITY_SERVICE)) .clearApplicationUserData();*/ --- Method 2 // deleteAppData(); ---- Method 3
}

private void deleteAppData() {
try {
// clearing app data String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);

} catch (Exception e) {
e.printStackTrace();
} }


public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}


public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}

return deletedAll;
}

}

Wednesday, 14 February 2018

Espresso Check for the Youtube URL



//Using Espresso Intent to check whether the appropriate URL is openedIntents.init();
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData("req_url"));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(startsWith("Video"))).perform(click());
intended(expectedIntent);
Intents.release();

Add this dependency in build.gradle
androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'

Start and Send data to Activity from ADB

1)Navigate to platform-tools which is inside sdk android
2)Then type adb shell am start -n yourpackagename/.activityname
3)Starts the Activity
4)To send the data
adb shell am start -n yourpackagename/.activityname -e myKey test
5)You can retrieve from App Side
getIntent().getStringExtra("myKey")
6)Done

Friday, 2 February 2018

Nexus not detecting in android studio

1.Update Android SDK (Google USB Driver)

2.From PC Control Panel, System -> Device manager -> Right click Nexus 4 -> Update driver.

3.Set android-sdk-folder\extras\google\usb_driver as path to search, include subfolders checked.

If windows tells you that the driver is up to date, just uninstall the driver (right click on nexu4 -> uninstall driver) and start from step 2 again.
After that, open a cmd and type adb kill-server and then a adb devices, now it will include your device.


More details
https://stackoverflow.com/questions/20343014/adb-doesnt-show-nexus-5-device

Git in Android Studio

How to get all changes of release branch to developer branch?


1)Navigate to VCS-->Git--->Merge Changes
There make sure you are on your current branch
2)Branvhes to merge:select the appropriate branch which you want to incorporate
3)Commit
4)Push

Sunday, 28 January 2018

SSL Pinning OverView


Certificate Pinning:

To summarize, pinning a certificate means that your app is verifying that the site the app is communicating with is the actual site by comparing the certificate presented by the site to one bundled in the app. This prevents a man-in-the-middle attack on your app.

SSL pinning isn’t something you want to implement in all your applications, but it makes sense when developing high-risk apps that need strong protection

HOW DOES THIS WORK ON ANDROID ?

  • obtain a certificate for the desired host (preferably the whole certificate chain)
  • make sure the certificate is in .bks format - this step is crucial in order for pinning to work properly across all devices
  • use Apache HTTP client shipped with Android - initialize it to use the obtained .bks keystore for SSL connections

Risks Involved

There is a downside to pinning a certificate. If the site rotates its certificate on a regular basis, then your application would need to be updated regularly. For example, Google rotates its certificates, so you will need to update your application about once a month (if it depended on Google services).

Example of a Failure Scenario
1. App has pinned certificate(s) to some domain name.
2. Certificates get updated on the server side.
3. Version of the app that pinned to old certificate(s) and doesn't know about new certificate(s) won't allow connection
.


Links





Challenges






https://dev.to/drankolq/certificate-pinning-your-android-and-ios-apps

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...