Create Password for already existing xls File - java

I am getting below exception while running.Need to protect xls file which is already exists.
java.io.FileNotFoundException: no such entry: "EncryptionInfo", had:
[] at
org.apache.poi.poifs.filesystem.DirectoryNode.getEntry(DirectoryNode.java:399)
at
org.apache.poi.poifs.filesystem.DirectoryNode.createDocumentInputStream(DirectoryNode.java:188)
at
org.apache.poi.poifs.crypt.EncryptionInfo.(EncryptionInfo.java:94)
at
org.apache.poi.poifs.crypt.EncryptionInfo.(EncryptionInfo.java:76)
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class xlsProtect {
public static void main(String[] args) {
try {
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("test"); // s3cr3t is your password to open sheet.
OPCPackage opc = OPCPackage.open(new File("C:/Users/test/Desktop/pdf/1.xls"), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs);
opc.save(os);
opc.close();
FileOutputStream fos = new FileOutputStream("C:/Users/test/Desktop/pdf/1.xls");
fs.writeFilesystem(fos);
fos.close();
fs.writeFilesystem(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

The Biff8EncryptionKey.setCurrentUserPassword() method has to be called after you've opened a .xls. See the following for encrypting both formats.
I've tested the .xls with Excel 2016 and Libre Office 6.0 - Libre Office currently can't open CryptoAPI encrypted files - if this is an issue for you, I think the example can be adapted to fallback to Binary RC4 encryption.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class EncryptTest {
public static void main(String[] args) throws Exception {
encryptHSSF();
encryptXSSF();
for (final String file : new String[] {"test.xls","test.xlsx"}) {
try (Workbook wb = WorkbookFactory.create(new File(file), "pass")) {
System.out.println(wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
}
}
}
public static void encryptHSSF() throws IOException, EncryptedDocumentException, InvalidFormatException {
generateFile("test.xls");
try (HSSFWorkbook hwb = (HSSFWorkbook)WorkbookFactory.create(new File("test.xls"))) {
Biff8EncryptionKey.setCurrentUserPassword("pass");
hwb.write();
}
}
public static void encryptXSSF() throws IOException, GeneralSecurityException {
generateFile("test.xlsx");
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("pass");
try (OutputStream os = enc.getDataStream(fs)) {
try (InputStream is = new FileInputStream("test.xlsx")) {
IOUtils.copy(is, os);
}
}
try (FileOutputStream fos = new FileOutputStream("test.xlsx")) {
fs.writeFilesystem(fos);
}
}
}
public static void generateFile(final String filename) throws IOException {
try (Workbook wb = filename.endsWith("x") ? new XSSFWorkbook() : new HSSFWorkbook()) {
wb.createSheet("test").createRow(0).createCell(0).setCellValue("Test");
try (FileOutputStream fos = new FileOutputStream(filename)) {
wb.write(fos);
}
}
}
}

Related

Cannot fetch the data from excel sheet in automation testing

Please check the code suggest correction:
package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DataDriveFramework {
public void readExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream fis = new FileInputStream(file);
Workbook loginWorkbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
loginWorkbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals("xls"))
{
loginWorkbook=new HSSFWorkbook(fis);
}
Sheet loginSheet=loginWorkbook.getSheet(sheetName);
int rowCount=loginSheet.getLastRowNum()-loginSheet.getFirstRowNum();
for(int i=1;1<rowCount+1;i++)
{
Row row=loginSheet.getRow(i);
String username=row.getCell(0).getStringCellValue();
String password=row.getCell(0).getStringCellValue();
test(username,password);
}
}
public void test(String username, String password)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
String baseURL="https://accounts.google.com";
driver.get(baseURL);
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/c-wiz/div/div[2]/div/div[2]/div/div[1]/div/div/button/span")).click();
driver.findElement(By.xpath("//*[#id=\"password\"]/div[1]/div/div[1]/input")).sendKeys(password);
driver.findElement(By.xpath("//*[#id=\"passwordNext\"]/div/button/span")).click();
driver.quit();
}
public static void main(String[] args)throws IOException {
DataDriveFramework readFile=new DataDriveFramework();
String filePath="C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\";
readFile.readExcel(filePath, "DataDriven.xls", "Sheet1");
}
}
The code is to fetch the data from excel sheet and login automatically.But I am getting an error--
"Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"
at com.framework.DataDriveFramework.readExcel(DataDriveFramework.java:31)
at com.framework.DataDriveFrame.main(DataDriveFrame.java:60)"
You missed a dot '.' in the below line in readExcel() method:
else if(fileExtension.equals("xls"))
it should be like:
else if(fileExtension.equals(".xls"))

Can i take a screenshot and paste it in a word file in appium using Java?

I'm currently using the below method to take screenshots and store them in a folder called 'Screenshots'. But what i want is, to take these screenshots and paste them in a word document according to the test cases to which they belong.
Is it possible? If so could somebody please guide me?
public String FailureScreenshotAndroid(String name) {
try {
Date d = new Date();
String date = d.toString().replace(":", "_").replace(" ", "_");
TakesScreenshot t = (TakesScreenshot)driver;
File f1 = t.getScreenshotAs(OutputType.FILE);//Temporary Location
String permanentLocation =System.getProperty("user.dir")+ "\\Screenshots\\"+name+date+".png";
File f2 = new File(permanentLocation);
FileUtils.copyFile(f1, f2);
return permanentLocation;
}catch (Exception e) {
String msg = e.getMessage();
return msg;
}
}
Try below:
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}

Unprotect word document using java

how can we unprotect the word document using java apache poi? I have protected the document as read-only using password pro-grammatically.Now I want to unprotect it. How can we do ? Is there any method to unprotect the document. I have used removePasswordProtection() but that document is not editable even after using that method.
The sample code that I have used for protection is
XWPFDocument document=new XWPFDocument();
document.enforceReadonlyProtection(strPassword,HashAlgorithm.sha1);
The document is getting protected successfully.
But when I am unprotecting document using the below code snippet it is not working.
if(document.isEnforcedReadonlyProtection())
{
if(document.validateProtectionPassword(strPassword))
{
document.removeProtectionEnforcement();
}
}
Can anyone help me what method that I can use to unprotect the document?
Cannot reproducing.
Following code produces two Word documents. One, WordProtected.docx, which is protected and one, WordUnprotected.docx in which protection is removed.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.poifs.crypt.HashAlgorithm;
class XWPFReadOnlyProtection {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
String strPassword = "password";
document.enforceReadonlyProtection(strPassword, HashAlgorithm.sha1);
FileOutputStream fileout = new FileOutputStream("WordProtected.docx");
document.write(fileout);
fileout.close();
document.close();
document = new XWPFDocument(new FileInputStream("WordProtected.docx"));
document.removeProtectionEnforcement();
fileout = new FileOutputStream("WordUnprotected.docx");
document.write(fileout);
fileout.close();
document.close();
}
}
use this code for Word to Protect
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class WordTest {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("D:\\govind.doc");
BufferedInputStream bin = new BufferedInputStream(in);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bin);
Biff8EncryptionKey.setCurrentUserPassword("P#ssw0rd");
HWPFDocument doc = new HWPFDocument(poiFileSystem);
Range range = doc.getRange();
FileOutputStream out = new FileOutputStream("D:\\govind.doc");
doc.write(out);
out.close();
}
}
this is use for protected word File unportected
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class wordFileTest {
public static void main(String[] args) throws IOException {
geenrateUnprotectedFile("D:\\","govind","1234");
}
public static void geenrateUnprotectedFile(String filePath,String fileName,String pwdtxt) {
try {
FileInputStream in = new FileInputStream(filePath+fileName+".doc");
BufferedInputStream bin = new BufferedInputStream(in);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bin);
Biff8EncryptionKey.setCurrentUserPassword(pwdtxt);
HWPFDocument doc = new HWPFDocument(poiFileSystem);
String docType=doc.getDocumentText();
FileOutputStream out = new FileOutputStream(filePath+fileName+"12.doc");
out.write(docType.getBytes());
System.out.println("don");
}catch (Exception e) {
e.printStackTrace();
}
}
}

How to add digital signature to Excel and JPG files?

I am using below code to generate and add digital signatures to the Excel file:
SignedObject signedHashObject =null;
signatureConfig.setKey((PrivateKey) privateKey);signatureConfig.setSigningCertificateChain(Collections.singletonList(Util.getX509Certificate(certificateAlias)));
OPCPackage pkg = OPCPackage.open(selectedFileName, PackageAccess.READ_WRITE);
signatureConfig.setOpcPackage(pkg);
SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(signatureConfig);
si.confirmSignature();
pkg.close();
Here the private key is java.security.mscapi.rsaprivatekey.
After fixing all the version compatibility issues, I am stuck with the below error,
The specified key of type sun.security.mscapi.RSAPrivateKey is not an RSAPrivateKey
I've fixed this now via #62159.
Make sure to set -Dorg.apache.xml.security.ignoreLineBreaks=true in the JVM properties.
Complete example, i.e. my test code:
import java.awt.geom.Rectangle2D;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
import org.apache.poi.poifs.crypt.dsig.SignatureInfo;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFTextBox;
public class CertTest {
static PrivateKey winKey;
static List<X509Certificate> winChain;
public static void main(String[] args) throws Exception {
System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");
HashAlgorithm hashes[] = { HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512 };
loadWinKey();
SignatureConfig signatureConfig = new SignatureConfig();
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2018, 1, 18, 12, 0, 0);
signatureConfig.setExecutionTime(cal.getTime());
for (final HashAlgorithm ha : hashes) {
try (final OPCPackage pkg = loadOPC("test-" + ha + ".pptx")) {
signatureConfig.setDigestAlgo(ha);
signatureConfig.setKey(winKey);
signatureConfig.setSigningCertificateChain(winChain);
signatureConfig.setOpcPackage(pkg);
SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(signatureConfig);
si.confirmSignature();
}
}
}
static void loadWinKey() throws Exception {
String alias = "poitest";
KeyStore keystore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
keystore.load(null, null);
winKey = (PrivateKey) keystore.getKey(alias, null);
winChain = Collections.singletonList((X509Certificate) keystore.getCertificate(alias));
}
static OPCPackage loadOPC(String fileName) throws Exception {
try (final XMLSlideShow ppt = new XMLSlideShow()) {
try (final FileOutputStream fos = new FileOutputStream(fileName)) {
XSLFTextBox tb = ppt.createSlide().createTextBox();
tb.setText("test");
tb.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
ppt.write(fos);
}
return OPCPackage.open(fileName, PackageAccess.READ_WRITE);
}
}
}

Printing results from PDF box output to a text file

I am working on a class which Parses a PDF document with PDF Box, its purpose is to create a text file (its name is PdfTestFile.txt) with the results. We have gotten it to print the parsed text to the console, but I don't know how to make it write the results to the .txt file that the class creates (name is PdfTestFile.txt).
I tried to use out.print(Text); but it gives me an error saying that:
out cannot be resolved
The class PdfEasyManager calls the class EasySearch in which we see the error mentioned above.
Below is the code that I have where the String Text is what I would like to print to the file PdfTestFile.txt:
Class " PdfEasyManager":
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class PdfEasyManager {
static BufferedWriter writer;
public static void main(String[] args) throws IOException {
//writer = new BufferedWriter(new FileWriter("Evergreen.txt"));
EasySearch easysearch = new EasySearch();
// pdfManager.setFilePath("PDFextTEST.pdf");
System.out.println(easysearch.ToText());
//out.println(easysearch.ToText());
}
}
Class "EasySearch" :
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class EasySearch {
private PDFParser parser;
private PDFTextStripper pdfStripper;
private PDDocument pdDoc ;
private COSDocument cosDoc ;
private String Text ;
private String filePath;
private File file;
static BufferedWriter writer;
//writer = new BufferedWriter(new FileWriter(BLnumber + (date.toString().substring(4, 10))+ ".org"));
public EasySearch() {
}
//public static void main(String args[]) throws Exception{
public String ToText() throws IOException
{
this.pdfStripper = null;
this.pdDoc = null;
this.cosDoc = null;
writer = new BufferedWriter(new FileWriter("PdfTestFile.txt"));
file = new File("C:/Users/Jon Smith/Desktop/Sample.pdf");
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdDoc.getNumberOfPages();
pdfStripper.setStartPage(1);// reading text from page 1
// pdfStripper.setEndPage(10);// to 10
pdfStripper.setEndPage(pdDoc.getNumberOfPages());// if you want to get text from full pdf file use this code
Text = pdfStripper.getText(pdDoc);
out.print(Text); //this is the line that gives me the error
return Text;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
You are using out which is not present in your class. Use System.out.print(Text).
Thanks for the help but
writer.write(Text);
solves the issue I was having

Categories

Resources