Tuesday, November 21, 2017

REST API Testing by using Rest assured

 import io.restassured.RestAssured;  
 import io.restassured.http.Method;  
 import io.restassured.response.Response;  
 import io.restassured.specification.RequestSpecification;  
 public class Test {  
  public static void main(String[] args) {  
  // Specify the base URL to the RESTful web service  
  // RestAssured.baseURI =  
  // "http://restapi.demoqa.com/utilities/weather/city";  
  RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city/Mangalore";  
  // Get the RequestSpecification of the request that you want to sent  
  // to the server. The server is specified by the BaseURI that we have  
  // specified in the above step.  
  RequestSpecification httpRequest = RestAssured.given();  
  // Make a request to the server by specifying the method Type and the  
  // method URL.  
  // This will return the Response from the server. Store the response in  
  // a variable.  
  Response response = httpRequest.request(Method.GET);  
  // Now let us print the body of the message to see what response  
  // we have recieved from the server  
  String statusLine = response.statusLine();  
  int statusCode = response.getStatusCode();  
  String responseBody = response.getBody().asString();  
  System.out.println("Status Code :" + statusCode);  
  System.out.println("Status Line is :" + statusLine + "\t");  
  System.out.println("Body:" + responseBody);  
  }  
 }  

Parsing JSON by json simple -Java

package mine;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Js {

public void getWeather(String cityname) {

URL url;

try {
// Connect to URL
url = new URL("http://restapi.demoqa.com/utilities/weather/city/" + cityname);

URLConnection uc = url.openConnection();

BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

// Create Json Object to parse
JSONObject obj = (JSONObject) JSONValue.parseWithException(br);

// Get data by Key
cityname = (String) obj.get("City");
String temp = (String) obj.get("Temperature");
String humid = (String) obj.get("Humidity");
String windspeed = (String) obj.get("WindSpeed");
String winddirect = (String) obj.get("WindDirectionDegree");

System.out.println("City: " + cityname);
System.out.println("Tempreture: " + temp);
System.out.println("Humidity: " + humid);
System.out.println("WindSpeed: " + windspeed);
System.out.println("WindDirectionDegree: " + winddirect);

br.close();

} catch (Exception e) {

e.printStackTrace();
}

}

public static void main(String[] args) {
Js j = new Js();
j.getWeather("Vasco");

}
}

Tuesday, November 14, 2017

Show watch in Console Java

package mine;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class MyWatch implements Runnable {
DateFormat formate;
Calendar cal;
String time;

public void show() {

System.out.print("\r" + time);
}

@Override
public void run() {
try {
while (true) {

new GregorianCalendar();
cal = Calendar.getInstance();

formate = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
time = formate.format(date);
show();
Thread.sleep(1000);
}
} catch (Exception e) {
e.getMessage();
}

}

}

public class ShowWatch {

public static void main(String[] args) {
Thread t1 = new Thread(new MyWatch());

t1.start();

}
}

Saturday, November 11, 2017

Get Random numbers/value from the array in Java

package MyPackage;

import java.util.Random;

public class GenerateRandom {

public static void main(String[] args) {

// Create an aarray
final int numbers[] = { 11, 22, 33, 44, 55, 66 };

// Random Class
Random rand = new Random();

int number = rand.nextInt(6);

System.out.println(number);

System.out.println(numbers[number]);

}

}


-----------------------------------------------------------------------------------


package MyPackage;

import java.util.Random;

public class GenerateRandom {

public static void main(String[] args) {

// Create an aarray
final String name[] = { "Jack", "Stefen", "Alex", "Jeo", "Bill", "Jay" };

// Random Class
Random rand = new Random();

int number = rand.nextInt(6);

System.out.println("Index of the Array: " + number);

System.out.println("Random name form the Array: " + name[number]);

}

}

Deleting all the files from folder in Java

package MyPackage;

import java.io.File;
import org.apache.commons.io.FileUtils;

public class DeleteAllFiles {

public static void main(String[] args) throws Exception {
// Delete all the files in the folder
File filepath = new File("C:\\Users\\Mutturaj.h\\Desktop\\TimeStamp");
FileUtils.cleanDirectory(filepath);

}

}

Thursday, November 9, 2017

Time-stamp in Java

public class CalendarClass {

 public static String timeStamp() throws Exception{

  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
  Calendar cal = Calendar.getInstance();
  String date = dateFormat.format(cal.getTime());
  return date;
}
}


Output: 2017-11-09 16-26-35

Tuesday, November 7, 2017

String class in Java

package MyPackage;

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.exec.util.StringUtils;



public class StringOperations
{

public static void main(String[] args) {
String mystring="Muttturaj Hulagabal";

char text=mystring.charAt(1);

System.out.println(text);

int count=mystring.length();

System.out.println(count);

String afterTrim=mystring.trim();
System.out.println("Lenght after Trim"+afterTrim.length());

String anotherString="Muttturaj Hulagabal";
System.out.println("0 means true here"+mystring.compareTo(anotherString));

System.out.println("In Bytes here: "+mystring.getBytes());


String suffix="bal";
System.out.println(mystring.endsWith(suffix));

//Substring is important here, it gets Sub string starting from 10th Index
System.out.println("Substring of my string: "+mystring.substring(10));

//Substring is importent here, it gets Sub string starting from 10th Index and ending from 19th Index
System.out.println(mystring.substring(10, 19));


System.out.println(mystring.subSequence(0, 18));

//Add other string to your string
String duplic=mystring.concat(anotherString);
System.out.println(duplic);

//And here we can use campare string with string variable by using == by using intern() Method
if(mystring==new String("Muttturaj Hulagabal").intern())
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}

//Converting number to string is importent here

int i = 10;
double d=10.00;


//toString() Method is used to convert to String
String s1=Integer.toString(i);
String s2=Double.toString(d);

System.out.println(s1);
System.out.println(s2);

System.out.println(mystring.toLowerCase());

System.out.println(mystring.toUpperCase());

//valueOf() Method is here which will convert defferent types value into String.
int value=10;

String s10=String.valueOf(value);

System.out.println(s10);

//split() is an importent method here in the String class

String string="12345-67890";
String[] parts=string.split("-");
String part1=parts[0];
String part2=parts[1];

System.out.println(part1);
System.out.println(part2);

//org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
String split[]=StringUtils.split(string, "-");

String split1=split[0];
System.out.println(split1);

String split2=split[1];
System.out.println(split2);

//Lets split by "-"

String stringtopart="12-123-1234-12345-123456";

String[] parttomany=stringtopart.split("-");
System.out.println(parttomany.length);

for(int k=0;k {
System.out.println(parttomany[k]);
}


//Lets split by using Array list Java 8

ArrayList stringlist = (ArrayList) Pattern.compile("-").splitAsStream("12-123-1234-12345").collect(Collectors.toList());
System.out.println(stringlist);
for(int l=0;l System.out.println(stringlist.get(l));


}

}


Monday, November 6, 2017

Writing to PDf file by using PDFBox Java

package MyPackage;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class PDFWrite
{

public static void main(String[] args) throws Exception
       {

PDDocument doc=new PDDocument();

PDPage page=new PDPage();
doc.addPage(page);

int numberOfPages=doc.getNumberOfPages();
System.out.println(numberOfPages);

float version=doc.getVersion();

System.out.println(version);

PDDocumentInformation info=new PDDocumentInformation();

String title="Mutturaj Hulagabal";

info.setTitle(title);

System.out.println(info.getTitle());

String author = "Mutturaj Hulagabal";

info.setAuthor(author);

System.out.println(info.getAuthor());

PDPageContentStream stream=new PDPageContentStream(doc, page);

stream.beginText();

stream.setFont(PDType1Font.TIMES_BOLD, 20);

stream.newLineAtOffset(25,750);

stream.showText("Mutturaj Hulagabal");

stream.endText();

stream.close();

doc.save(filepath);

doc.close();

}

}

Sunday, November 5, 2017

Get excel data into data provider by using Apache POI java

Download Apache POI from here: https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.17-20170915.zip

package Learn;

import java.io.FileInputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ReadX
{
@DataProvider(name="data")
public Object[][] data() throws Exception
{
String filepath="C:/Users/Mutturaj.h/Desktop/Me.xlsx";

FileInputStream fis=new FileInputStream(filepath);

XSSFWorkbook wb=new XSSFWorkbook(fis);

XSSFSheet sheet=wb.getSheetAt(0);

Object[][] excelData;

int rows=sheet.getPhysicalNumberOfRows();

int cols=sheet.getRow(0).getLastCellNum();

String data=sheet.getRow(0).getCell(1).getStringCellValue();

System.out.println("Number of rows are: "+rows);

System.out.println("Number of columns are: "+cols);

System.out.println(data);

excelData=new Object[rows][cols];

for(int i=0;i {
for(int j=0;j {
excelData[i][j]=sheet.getRow(i).getCell(j).getStringCellValue();
}
}
return excelData;

}

@Test(dataProvider="data")
public void show(String name,String number){
System.out.println(name);
System.out.println(number);
}


}

Read PDF file by using PDFBOX Java


Download PFD Box from here:  https://pdfbox.apache.org/download





package MyPackage;

import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class ReadPDF
       {

public void readP() throws Exception
{
File filepath=new File("PDF file path");
PDDocument document = PDDocument.load(filepath);

int pages=document.getNumberOfPages();

System.out.println("Total Number of Pages in Document :"+pages);
     
//Instantiate PDFTextStripper class
      PDFTextStripper pdfStripper = new PDFTextStripper();

      //Retrieving text from PDF document
      String text = pdfStripper.getText(document);
      System.out.println(text);      
     
      //Closing the document
      document.close();

}
public static void main(String[] args) throws Exception {

ReadPDF p=new ReadPDF();
p.readP();

}

}


Write to Excel(.XLSX) using Java Apachi POI

package MyPackage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteX {

public void writeX() throws Exception
{

File f=new File("C:/Users/Mutturaj.h/Desktop/Me.xlsx");

FileInputStream fis=new FileInputStream(f);

XSSFWorkbook wb=new XSSFWorkbook(fis);

XSSFSheet sheet=wb.getSheet("Muttu2");

XSSFRow row=sheet.createRow(6);

XSSFCell cell=row.createCell(6);

cell.setCellValue("Muttu");

FileOutputStream fos=new FileOutputStream(f);

wb.write(fos);

public static void main(String[] args) throws Exception
{

WriteX x=new WriteX();
x.writeX();

}

}

Monday, May 15, 2017

7 Sleep Tips Just for Men

Source: http://blog.downlinens.com/7-sleep-tips-just-for-men/



Trying to count sheep and it just isn’t doing the trick when it comes to catching some shuteye? Sometimes men and women are affected differently by sleep and for men, it’s important to take a step back and figure out what to do to beat the bedtime blues. Here are 7 sleep tips just for men.

Sex
Women might like a good cuddle sesh or chat after a romp in the sack, but a lot of times men like to doze off. Why not, sex is relaxing, right? Orgasms release endorphins and can be key in ushering in peace and calm for easy sleep.

Ditch Oversleeping
Stayed up late last night and now you feel like you need to overcompensate? Don’t do it, man. Adding extra z’s during the day on top of your late night can really screw with your internal clock. Instead, wait till bedtime when you are really sleepy and get that rest your body craves.

Avoid all of These
You may have heard that falling asleep with a) music b) television c) alcohol will help promote a good night’s rest–but beware. It’s important to keep the bedroom associated with sleeping and sex only; the above may help some fall asleep, but can also be hindrance. Alcohol is said to be helpful too, but can have detrimental affects on sleep in the long run, as you don’t want to become dependent on it.

Mind Games
Believe it or not worrying about sleep can really affect the whole physical process because it stresses the body and mind in what’s called “learned insomnia.”  Instead of forcing yourself to bed or thinking about it too much, try relaxing with some deep breathing and do not think about sleep!

Prep Time
With busy work and school schedules, the next day is already on our minds when it hasn’t even arrived yet, and that can get stressful. Set up a little bedtime routine to prepare not only for bed, but also for the next day. Pack your bags and pick out your outfit for work or school. Brush your teeth and wash your face. Then, take some time to relax in bed with a book and try that deep breathing.

Nosh on Carbs+Protein
Dinner didn’t do it for you and your tummy is growling before bed–grab some cheese and crackers or some kind of carb/protein combination. Studies show that this combo can boost serotonin, a brain chemical that calms the mind and body. Try to indulge an hour before bedtime.

Keep the Quality

If you’re going to splurge your hard earned moolah on something, the bedroom is a good place to start. A comfortable mattress and pillows are crucial for proper sleep and a lot of times people will keep a mattress longer than they should (life expectancy is usually 9-10 years) without replacing it. Really do your research and figure out what appeals most to you when it comes to firm/soft builds. Also pay attention to allergens that can cause irritation and ultimately, sleep deprivation.