Unable get the sheet zoom value in apache poi - apache-poi

In apache poi we are able setting zoom value using sheet.setZoom(120). But How we will get zoom values when we copy/clone same sheet. I can not able to find a method srcSheet.getZoom();. what is alternative for this method?.

What can we do if apache poi lacks a method? We could take a look how it does coding similar methods. For example XSSFSheet..setZoom does nothing else than setting the zoomScale of the default CTSheetView. So if we would get the default sheet view, we could do the opposite and get the zoomScale.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetView;
import java.lang.reflect.Method;
public class ExcelXSSFSheetZoom {
static long getZoom(XSSFSheet sheet) throws Exception {
Method getDefaultSheetView = XSSFSheet.class.getDeclaredMethod("getDefaultSheetView");
getDefaultSheetView.setAccessible(true);
CTSheetView sheetview = (CTSheetView)getDefaultSheetView.invoke(sheet);
return sheetview.getZoomScale();
}
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
sheet.setZoom(120);
System.out.println(getZoom((XSSFSheet)sheet));
wb.write(new FileOutputStream("ExcelXSSFSheetZoom.xlsx"));
wb.close();
}
}

Related

How Do I Read and Write to an Excel Spreadsheet With Java?

Summary of Problem
I have created a simple program to read from and write to a spreadsheet. But it does not work. Does anyone know what I am doing wrong?
What I Have Tried
I have successfully been able to read from a spreadsheet. I have successfully been able to write to a spreadsheet. However, I cannot do both at the same time.
It seems that the createRow function overwrites the entire row. Thus, erasing previous data. This is a pretty severe constraint. It might be what is preventing me from reading and writing at the same time.
I noticed that the output says "The supplied file was empty (zero bytes long)". But I made sure that the path is correct and that there is indeed data in the spreadsheet. Not sure where that error is coming from.
I've tried following suggestions from other posts on Stack Overflow, but none of their suggestions including closing both the fileInputStream and fileOutputStream seems to affect my program at all.
My Code
package certExamPractice;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SpreadsheetPractice {
public static void main(String[] args) throws IOException {
String path = "C:/Users/james/Desktop/Spreadsheets/Spreadsheet4.xlsx";
FileInputStream fileInputStream = new FileInputStream(path);
FileOutputStream fileOutputStream = new FileOutputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workbook.createSheet("Sheet1");
Set<String> vir = new HashSet<String>();
vir.add(sheet.getRow(0).getCell(0).getStringCellValue());
vir.add(sheet.getRow(1).getCell(0).getStringCellValue());
vir.add(sheet.getRow(2).getCell(0).getStringCellValue());
vir.add(sheet.getRow(3).getCell(0).getStringCellValue());
sheet.getRow(0).createCell(1).setCellValue("zeta");
sheet.getRow(1).createCell(1).setCellValue("eta");
sheet.getRow(2).createCell(1).setCellValue("theta");
sheet.getRow(3).createCell(1).setCellValue("iota");
System.out.println("Vir = " + vir);
workbook.write(fileOutputStream);
workbook.close();
fileOutputStream.close();
}
}
My Spreadsheet
My spreadsheet.
The Output
Exception in thread "main" org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
at org.apache.poi.util.IOUtils.peekFirstNBytes(IOUtils.java:112)
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:209)
at org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:143)
at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:175)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:104)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:312)
at org.apache.poi.ooxml.util.PackageHelper.open(PackageHelper.java:47)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:299)
at certExamPractice.SpreadsheetPractice.main(SpreadsheetPractice.java:18)
The following code allows you to read from and write to a spreadsheet. You need to write the beginning code and the end code. Then you can read and write as you wish in the middle.
package certExamPractice;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class SpreadsheetPractice {
public static void main(String[] args) throws IOException{
//BEGINNING
String path = "C:/Users/james/Desktop/Spreadsheets/Spreadsheet4.xlsx";
FileInputStream fileInputStream = new FileInputStream(path);
Workbook workbook = WorkbookFactory.create(fileInputStream);
Sheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if (cell == null) { cell = row.createCell(0); }
//READ
Set<String> vir = new HashSet<String>();
vir.add(sheet.getRow(0).getCell(0).getStringCellValue());
vir.add(sheet.getRow(1).getCell(0).getStringCellValue());
vir.add(sheet.getRow(2).getCell(0).getStringCellValue());
vir.add(sheet.getRow(3).getCell(0).getStringCellValue());
System.out.println("Vir = " + vir);
//WRITE
sheet.getRow(0).createCell(1).setCellValue("zeta");
sheet.getRow(1).createCell(1).setCellValue("theta");
sheet.getRow(2).createCell(1).setCellValue("eta");
sheet.getRow(3).createCell(1).setCellValue("iota");
//END
try (OutputStream fileOutputStream = new FileOutputStream(path)) {
workbook.write(fileOutputStream);
}
workbook.close();
}
}

how to clear this programming error in getCellData in keyword driven framework for selenium webdriver?

I'm using this program in Keyword driven framework for selenium web driver tool. But due to this program i'm getting null pointer exception every time i tried to debug the code but cant find any solution. please suggest me the solution for that error.
package utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class ExcelUtils {
private static HSSFSheet ExcelWSheet;
private static HSSFWorkbook ExcelWBook;
private static HSSFCell Cell;
//This method is to set the File path and to open the Excel file
//Pass Excel Path and SheetName as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception
{
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new HSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
//This method is to read the test data from the Excel cell
//In this we are passing parameters/arguments as Row Num and Col Num
public static String getCellData(int RowNum, int ColNum) throws Exception{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
System.out.println(Cell);
String CellData = Cell.getStringCellValue();
System.out.println("."+CellData);
return CellData;
}
}

How to print RuntimeVisibleAnnotations in java ASM

I am new to ASM. I have a class file in which I have runtime visible annotations for methods. I want to parse this class file and select the annotation according to specific criteria. I looked into the documentation of ASM and tried with the visibleAnnotation. I can't seem to print the list of annotations of method which I can see in my class files.
My code is as
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.ClassReader;
public class ByteCodeParser {
public static void main(String[] args) throws Exception{
InputStream in=new FileInputStream("sample.class");
ClassReader cr=new ClassReader(in);
ClassNode classNode=new ClassNode();
//ClassNode is a ClassVisitor
cr.accept(classNode, 0);
//
Iterator<MethodNode> i = classNode.methods.iterator();
while(i.hasNext()){
MethodNode mn = i.next();
System.out.println(mn.name+ "" + mn.desc);
System.out.println(mn.visibleAnnotations);
}
}
}
The output is:
<clinit>()V
null
<init>()V
null
MyRandomFunction1()V
[org.objectweb.asm.tree.AnnotationNode#5674cd4d]
MyRandomFunction2()V
[org.objectweb.asm.tree.AnnotationNode#63961c42]
My RandomFunction 1 & 2 has annotations but I can't seem to understand [org.objectweb.asm.tree.AnnotationNode#5674cd4d].
I solved this issue myself, I had to iterate over the annotations which I didn't realize initally.
if (mn.visibleAnnotations != null) {
Iterator<AnnotationNode>j=mn.visibleAnnotations.iterator();
while (j.hasNext()) {
AnnotationNode an=j.next();
System.out.println(an.values);
}
}

PowerMocking static does not return expected object

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

Spring LDAP Template Usage

Please take a look at the test class below. I am trying to do an LDAP search with Spring LDAP Template. I am able to search and produce a list of entries corresponding to the search criteria without the Spring LDAP template by using the DirContext as shown in the method searchWithoutTemplate(). But when I use a LdapTemplate, I end up with a NPE as shown further below. I am sure I must be missing something. Can someone help please?
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapName;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.DefaultDirObjectFactory;
import org.springframework.ldap.core.support.LdapContextSource;
public class LDAPSearchTest {
//bind params
static String url="ldap://<IP>:<PORT>";
static String userName="cn=Directory Manager";
static String password="password123";
static String bindDN="dc=XXX,dc=com";
//search params
static String base = "ou=StandardUser,ou=XXXCustomers,ou=People,dc=XXX,dc=com";
static String filter = "(objectClass=*)";
static String[] attributeFilter = { "cn", "uid" };
static SearchControls sc = new SearchControls();
public static void main(String[] args) throws Exception {
// sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setReturningAttributes(attributeFilter);
searchWithTemplate(); //NPE
//searchWithoutTemplate(); //works fine
}
public static void searchWithTemplate() throws Exception {
DefaultDirObjectFactory factory = new DefaultDirObjectFactory();
LdapContextSource cs = new LdapContextSource();
cs.setUrl(url);
cs.setUserDn(userName);
cs.setPassword(password);
cs.setBase(bindDN);
cs.setDirObjectFactory(factory.getClass ());
LdapTemplate template = new LdapTemplate(cs);
template.afterPropertiesSet();
System.out.println((template.search(new LdapName(base), filter, sc,
new AttributesMapper() {
public Object mapFromAttributes(Attributes attrs)
throws NamingException {
System.out.println(attrs);
return attrs.get("uid").get();
}
})));
}
public static void searchWithoutTemplate() throws NamingException{
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
//env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext dctx = new InitialDirContext(env);
NamingEnumeration results = dctx.search(base, filter, sc);
while (results.hasMore()) {
SearchResult sr = (SearchResult) results.next();
Attributes attrs = sr.getAttributes();
System.out.println(attrs);
Attribute attr = attrs.get("uid");
}
dctx.close();
}
}
Exception is:
Exception in thread "main" java.lang.NullPointerException
at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:125)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:287)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:588)
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:546)
at LDAPSearchTest.searchWithTemplate(LDAPSearchTest.java:47)
at LDAPSearchTest.main(LDAPSearchTest.java:33)
I am using Spring 2.5.6 and Spring LDAP 1.3.0
A quick scan showed that it's the authenticationSource field of AbstractContextSource that is the culprit. That file includes the following comment on the afterPropertiesSet() method:
/**
* Checks that all necessary data is set and that there is no compatibility
* issues, after which the instance is initialized. Note that you need to
* call this method explicitly after setting all desired properties if using
* the class outside of a Spring Context.
*/
public void afterPropertiesSet() throws Exception {
...
}
That method then goes on to create an appropriate authenticationSource if you haven't provided one.
As your test code above is most definitely not running within a Spring context, and you haven't explicitly set an authenticationSource, I think you need to edit your code as follows:
...
cs.setDirObjectFactory(factory.getClass ());
// Allow Spring to configure the Context Source:
cs.afterPropertiesSet();
LdapTemplate template = new LdapTemplate(cs);

Resources