Is it possible to copy all contents(Ctrl+A) in the notepad file and paste into Textarea in the webpage using Java /Selenium ?
Solution is as follows:
Code to copy contents of file into a textbox on webpage: This code copies and pastes the contents of one text file into Google search textbox on google.com and hits search button.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CopyFileToTextbox {
public static void main(String[] args) {
File inFile = new File("D:\\path\\to\\notepad\\file\\TextFile1.txt");
StringBuilder targetString = new StringBuilder("");
try {
FileReader fr = new FileReader(inFile);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((s = br.readLine()) != null) {
targetString.append(s);
}
} catch (IOException e) {
e.printStackTrace();
}
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
driver.findElement(By.name("q")).sendKeys(targetString);
driver.findElement(By.name("btnG")).click();
driver.quit();
}
}
Related
I am using PDFBOX and reading and saving the contents from PDF file . Requirement is text should be splitted to Header and Item in seperate array list .
PDF looks below.
Expected :
Following details PO,DeliveryDate,Vendor no should shown in arraylist 1 and other details like barcode,item number,description,quantity should shown in arraylist 2 .
Exisiting code for extracting data as txt from PDF.
PDFBoxReadFromFile.java
package pdfboxreadfromfile;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.io.*;
public class PDFBoxReadFromFile {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PDFManager pdfManager = new PDFManager();
pdfManager.setFilePath("C:\\Users\\34\\Documents\\test.pdf");
try {
String text = pdfManager.toText();
System.out.println(text);
File file = new File("C:/Users/34/eclipse-workspace/pdfboxreadfromfile/file.txt");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
pw.close();
} catch (IOException ex) {
//System.err.println(ex.getMessage());
Logger.getLogger(PDFBoxReadFromFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
PDFManager.Java
package pdfboxreadfromfile;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class PDFManager {
private PDFParser parser;
private PDFTextStripper pdfStripper;
private PDDocument pdDoc;
private COSDocument cosDoc;
private String Text;
private String filePath;
private File file;
public PDFManager() {
}
public String toText() throws IOException {
this.pdfStripper = null;
this.pdDoc = null;
this.cosDoc = null;
file = new File(filePath);
parser = new PDFParser(new RandomAccessFile(file, "r")); // update for PDFBox V 2.0
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdDoc.getNumberOfPages();
pdfStripper.setStartPage(0);
pdfStripper.setEndPage(pdDoc.getNumberOfPages());
Text = pdfStripper.getText(pdDoc);
return Text;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public PDDocument getPdDoc() {
return pdDoc;
}
}
java
Using java, I need to read a warc archive file, filter it depending on the content of the html page, and write a new archive file.
the following code reads the archive. how to reconstruct an org.archive.io.warc.WARCRecordInfo from an org.archive.io.ArchiveRecord?
import org.apache.commons.io.IOUtils;
import org.archive.io.ArchiveRecord;
import org.archive.io.warc.*;
import org.archive.wayback.resourcestore.resourcefile.WarcResource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;
public class Test126b {
public static void main() throws Exception {
File out = new java.io.File("out.warc.gz");
OutputStream bos = new BufferedOutputStream(new FileOutputStream(out));
WARCWriterPoolSettings settings = ...
WARCWriter writer = new WARCWriter(new AtomicInteger(), bos, out, settings);
File in = new java.io.File("in.warc.gz");
WARCReader reader = WARCReaderFactory.get(in);
Iterator<ArchiveRecord> it = reader.iterator();
while (it.hasNext()) {
ArchiveRecord archiveRecord = it.next();
if (archiveRecord.getHeader().getHeaderValue("WARC-Type") == "response") {
WARCRecord warcRecord = (WARCRecord) archiveRecord;
WarcResource warcResource = new WarcResource(warcRecord, reader);
warcResource.parseHeaders();
String url = warcResource.getWarcHeaders().getUrl();
System.out.println("+++ url: " + url);
byte[] content = IOUtils.toByteArray(warcResource);
String htmlPage = new String(content);
if (htmlPage.contains("hello world")) {
writer.writeRecord(warcRecordInfo) // how to reconstruct the WARCRecordInfo
}
}
}
reader.close();
writer.close();
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am new to Keyword Driven approach for selenium. I am getting NullPointerException while running below ExecuteTest.java
Folder Structure
Folder structure
Object.txt
Object.txt
TestCase.xlsx
TestCase.xlsx
Error Screenshot
Screenshot1
Screenshot2
Adding Debug screenshots
screenshot1
screenshot2
screenshot3
ReadGuru99Excel.java
import org.apache.poi.ss.usermodel.Sheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadGuru99ExcelFile {
public Sheet readExcel (String filePath,String fileName, String sheetName)throws IOException{
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook guru99Workbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")){
guru99Workbook = new XSSFWorkbook(inputStream);
} else if(fileExtensionName.equals(".xls")) {
guru99Workbook = new HSSFWorkbook(inputStream);
}
Sheet guru99Sheet =guru99Workbook.getSheet(sheetName);
return guru99Sheet;
}
}
ReadObject.Java
package operation;
import java.util.Properties;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.File;
public class ReadObject {
Properties p = new Properties();
public Properties getObjectRepository()throws IOException{
InputStream stream = new FileInputStream(new File (System.getProperty("user.dir")+"\\src\\objects\\object.txt"));
p.load(stream);
return p;
}
}
UIOperation.java
package operation;
import org.openqa.selenium.WebDriver;
import java.util.Properties;
import org.openqa.selenium.By;
public class UIOperation {
WebDriver driver ;
public UIOperation(WebDriver driver){
this.driver = driver;
}
public void perform(Properties p, String operation, String objectName, String objectType, String value) throws Exception{
System.out.println("");
switch(operation.toUpperCase()){
case "CLICK":
driver.findElement(this.getObject(p, objectName, objectType)).click();
break;
case "SETTEXT":
driver.findElement(this.getObject(p, objectName, objectType)).sendKeys(value);
break;
case "GOTOURL":
driver.get(p.getProperty(value));
break;
case "GETTEXT":
driver.findElement(this.getObject(p, objectName, objectType)).getText();
break;
default:
break;
}
}
private By getObject(Properties p, String objectName, String objectType) throws Exception{
if(objectType.equalsIgnoreCase("XPATH")){
return By.xpath(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("CLASSNAME")){
return By.className(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("NAME")){
return By.name(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("CSS")){
return By.cssSelector(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("LINK")){
return By.linkText(p.getProperty(objectName));
}else if(objectType.equalsIgnoreCase("PARTIALLINK")){
return By.partialLinkText(p.getProperty(objectName));
}else{
throw new Exception("Wrong object type");
}
}
}
ExecuteTest.java
package testcases;
import java.util.Properties;
import operation.ReadObject;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import excelExportAndFileIO.ReadGuru99ExcelFile;
public class ExecuteTest {
#Test
public void testLogin()throws Exception{
/**
* System.setProperty("webdriver.gecko.driver", "E:\\Selenium-2017\\geckodriver-v0.18.0-win64\\geckodriver.exe");
* //Now you can Initialize marionette driver to launch firefox
* DesiredCapabilities capabilities = DesiredCapabilities.firefox();
* capabilities.setCapability("marionette", true);
* WebDriver driver = new RemoteWebdriver(capabilities);
*
* WebDriver webdriver = new FirefoxDriver();
**/
WebDriver driver;
System.setProperty("webdriver.chrome.driver","E:\\Selenium-2017\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
ReadGuru99ExcelFile file = new ReadGuru99ExcelFile();
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(driver);
Sheet guru99Sheet = file.readExcel(System.getProperty("user.dir")+"\\test-output","TestCase.xlsx","KeywordFramework");
int rowCount =guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
System.out.println("first step clear");
for(int i = 0;i<rowCount+1; i++){
Row row =guru99Sheet.getRow(i);
System.out.println("2nd clear");
if(row.getCell(0).toString().length()==0){
System.out.println("4nd clear");
System.out.println(row.getCell(1).toString()+"-----"+row.getCell(2).toString()+"----"+row.getCell(3).toString()+"---"+row.getCell(4).toString());
System.out.println("3rd clear");
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString());
} else
System.out.println("New Testcase->" + row.getCell(0).toString()+"Started");
System.out.println("testerassumption");
}
}
}
First of all, please see this wonderful post about NullPointerException and how to fix it.
In your case, the stacktrace points the NullPointerException to be occuring at line 49 of the code in ExecuteTest.java, which points to this line of code
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString());
The issue here is that when you're trying to convert the contents of the cell in the getCell() method to a String, if there is nothing in the cell, then there would always be a NullPointerException.
You can either place a != null check before every cell or add a " " for every toString() method, like
operation.perform(allObjects, (row.getCell(1)+"").toString(), (row.getCell(2)+"").toString(), (row.getCell(3)+"").toString(), (row.getCell(4)+"").toString());
I created a OrientDB database using Java. Now I need to insert a dataset (a text file). I need help for this.
An example of file which i need to insert into my database.
My current code:
package creationdbgraph;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CreationDbGraph {
public static void main(String[] args)throws FileNotFoundException, IOException {
String nameDb="Graph";
String currentPath="remote:localhost/"+nameDb;
OServerAdmin serverAdmin;
try {
serverAdmin = new OServerAdmin(currentPath).connect("root", "19952916");
if(!serverAdmin.existsDatabase()){
serverAdmin.createDatabase(nameDb, "graph", "plocal");
OrientGraphNoTx g = new OrientGraphNoTx(currentPath);
OClass FromNode=g.createVertexType("FromNode", "V");
FromNode.createProperty("ID", OType.STRING);
OClass ToNode=g.createVertexType("ToNode", "V");
ToNode.createProperty("ID", OType.STRING);
g.createEdgeType("Edge", "E");
g.shutdown();
OrientGraph g1 = new OrientGraph(currentPath);
File file = new File("C:\\Users\\USER\\Downloads\\orientdb-community-2.2.20\\dataset.txt");
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNext()) {
OrientVertex node1=g1.addVertex("class:FromNode");
OrientVertex node2=g1.addVertex("class:ToNode");
if(scanner.hasNextInt())
{
node1.setProperty("ID",scanner.nextInt());
continue;
}
node2.setProperty("ID",scanner.nextInt());
node1.addEdge("Edge", node2);
}
}
System.out.println(list);
g1.shutdown();
}
serverAdmin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your case is pretty simple, if the file is not huge (< millions of rows) you can use the graph batch insert: http://orientdb.com/docs/2.2.x/Graph-Batch-Insert.html
May I know how to write the output to the text file same as output shown by show() function. For example when I executed this code:
p.show();
output:
(TOP (S (NP (PRP$ My) (NN name)) (VP (VBZ is) (NP (NNP David.))))
when I executed this code:
System.out.println(p.toString());
output:
My name is David.
So, when I tried to write this output to text file by using this code:
fout.write((p.toString()+newline).getBytes());
output in text file same as the output shown by "System.out.println(p.toString());".
So, how to write same output as shown by show() function to the text file?
Full Codes:
package com.mycompany.app;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class ChunkParser {
public static void main(String[] args) throws IOException {
InputStream modelIn = new FileInputStream("D:/NetBeansProjects/my-app/src/main/resources/en-parser-chunking.zip");
FileInputStream fin=new FileInputStream("D:/NetBeansProjects/my-app/textfile.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine=br.readLine();
System.out.println("Full Text: "+"\n"+strLine+"\n");
try {
ParserModel pmodel = new ParserModel(modelIn);
Parser parserc = ParserFactory.create(pmodel);
Parse topParses[] = ParserTool.parseLine(strLine, parserc, 1);
FileOutputStream fout=new FileOutputStream("D:/NetBeansProjects/my-app/ChunkParser.txt");
String newline = System.getProperty("line.separator");
for (Parse p : topParses){
p.show();
System.out.println(p.toString());
fout.write((p.toString()+newline).getBytes());
}
fout.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
fin.close();
}
}
}
Instead of calling p.show() use p.show(sb) where sb is a StringBuffer. Then you can fetch the text from the StringBuffer. Have a deeper look in the documentation of opennlp next time.