I am trying to convert ppt into pdf using Apache POI but getting following error.Please help me out of this - apache-poi

Following code is used:
public static void main(String[] args) throws IOException {
FileInputStream is = new FileInputStream("C:/Users/hp/Downloads/sampPPT.ppt");
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
// clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide.draw(graphics);
// save the output
FileOutputStream out = new FileOutputStream("C:/Users/hp/Downloads/slide-" + idx + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
idx++;
}
}
This throws following exception:
Exception in thread "main" java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory (org.apache.poi.hslf.usermodel.HSLFSlideShowImpl and org.apache.poi.POIDocument are in unnamed module of loader 'app')
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.readCurrentUserStream(HSLFSlideShowImpl.java:340)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:154)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:127)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:116)
at org.apache.poi.hslf.usermodel.HSLFSlideShow.<init>(HSLFSlideShow.java:138)
at PPTConv.PPTConv.main(PPTConv.java:27)

To make an answer why such exceptions occur. Maybe it is helpful for others too:
This kind of exception occur if you mix Apache POI jars from different versions. This is not supported. See FAQ.
In that special case there probably are poi-*.jar and poi-scratchpad-*.jar from different versions in classpath. The class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl, which extends org.apache.poi.POIDocument, is contained in poi-scratchpad-*.jar while org.apache.poi.POIDocument is contained in poi-*.jar. If those *.jars are from different versions, then following can occur:
The org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of poi-scratchpad-3.15.jar calls currentUser = new CurrentUserAtom(directory); in code line 340. This is possible because it extends org.apache.poi.POIDocument and this has field protected DirectoryNode directory; in version 3.15 (poi-3.15.jar).
But the same class org.apache.poi.POIDocument of version 3.16 (poi-3.16.jar) has field private DirectoryNode directory;. So if org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of version 3.15 calls currentUser = new CurrentUserAtom(directory); in code line 340, but org.apache.poi.POIDocument is from version 3.16, then java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory is thrown because it really tries to access a private field now.

Related

Apache Batik No WriteAdapter is available?

I'm writing code to convert SVG's to PNG's:
package com.example;
import java.io.*;
import java.nio.file.Paths;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
public class Main {
public static void main(String [] args) throws Exception {
// read the input SVG document into TranscoderInput
String svgURI = Paths.get(args[0]).toUri().toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);
// define OutputStream to PNG Image and attach to TranscoderOutput
OutputStream ostream = new FileOutputStream("out.png");
TranscoderOutput output = new TranscoderOutput(ostream);
// create a JPEG transcoder
PNGTranscoder t = new PNGTranscoder();
// set the transcoding hints
t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, new Float(600));
t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, new Float(600));
// convert and write output
t.transcode(input, output);
// flush and close the stream then exit
ostream.flush();
ostream.close();
}
}
I get the following exceptions executing it with a variety of SVG's:
Exception in thread "main" org.apache.batik.transcoder.TranscoderException: null
Enclosed Exception:
Could not write PNG file because no WriteAdapter is availble
at org.apache.batik.transcoder.image.ImageTranscoder.transcode(ImageTranscoder.java:132)
at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstractTranscoder.java:142)
at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstractTranscoder.java:156)
at com.example.Main.main(Main.java:26)
Batik version (reported by Maven):
version=1.9
groupId=org.apache.xmlgraphics
artifactId=batik-transcoder
I get the same error with Batik 1.7.
Suggestions?
The problem was solved by Peter Coppens on the xmlgraphics-batik-users mailing list. The problem is that the Maven repository for Batik 1.9 is missing a dependency, which can be addressed by adding to pom.xml:
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-codec</artifactId>
<version>1.9</version>
</dependency>
The cryptic exception disappears and the code functions as expected with this addition. This was reported as a bug for Batk 1.7 (https://bz.apache.org/bugzilla/show_bug.cgi?id=44682).

'System.NullReferenceException' while defining an object XNA C#

I've recently been trying to make a game, and decided to start from scratch. However, I quickly encountered an error that wasn't a problem in the previous session of my game.
Me and my friend ran through several ideas of what might cause the error however we haven't been able to find.
Apparently it somehow creates an error when I'm trying to load an object using a different class(UI.UILoader) The main class is as followed:
namespace WindowsGame1.Classes
{
public static Game1 instance;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public MouseState mouseState;
public KeyboardState keyState;
public SpriteFont debugFont;
Instance inst;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
debugFont = Content.Load<SpriteFont>("debugFont");
inst.Load();
UI.UILoader.Load();
// TODO: use this.Content to load your game content here
}
The Class UILoader can be seen beneath where it tries to load two textures using Texture2D. However when it tries to load the first texture I recieve a 'System.NullReferenceException' error.
namespace WindowsGame1.Classes.UI
{
public static class UILoader
{
public static Texture2D cursorTexture;
public static Texture2D buttonTexture;
public static void Load()
{
cursorTexture = Game1.instance.Content.Load<Texture2D>("Interface/Cursor");
buttonTexture = Game1.instance.Content.Load<Texture2D>("Interface/Cursor");
}
}
}
I thought it might have something to do me using a different class to load(which I found odd) so I tried moving it all to the load content class in the main class, however, it didn't remove the error but instead of triggering during the loading session it now triggered when I tried to put the object to use(after the object should have been given a value and thus not be null)
I don't believe that the problem is with the picture I try to use since I already added it to the folder I'm using (I would post a picture but i don't have enough reputation)
If anyone have any idea what might be the cause of this error I would be happy to here your thoughts.

I am unable to fetch excel data to selenium code At ubuntu o/s

public class ReadAndWrite {
public static void main(String[] args) throws InterruptedException, BiffException, IOException
{
System.out.println("hello");
ReadAndWrite.login();
}
public static void login() throws BiffException, IOException, InterruptedException{
WebDriver driver=new FirefoxDriver();
driver.get("URL");
System.out.println("hello");
FileInputStream fi = new FileInputStream("/home/sagarpatra/Desktop/Xpath.ods");
System.out.println("hiiiiiii");
Workbook w = Workbook.getWorkbook(fi);
Sheet sh = w.getSheet(1);
//or w.getSheet(Sheetnumber)
//String variable1 = s.getCell(column, row).getContents();
for(int row=1; row <=sh.getRows();row++)
{
String username = sh.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("URL");
driver.findElement(By.name("Email")).sendKeys(username);
String password= sh.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
Thread.sleep(10000);
driver.findElement(By.name("Login")).click();
System.out.println("Waiting for page to load fully...");
Thread.sleep(30000);
}
driver.quit();
}
}
I don't know what is wrong with my code, or how to fix it. It outputs the following error:
Exception in thread "main" jxl.read.biff.BiffException: Unable to recognize OLE stream
at jxl.read.biff.CompoundFile.<init>(CompoundFile.java:116)
at jxl.read.biff.File.<init>(File.java:127)
at jxl.Workbook.getWorkbook(Workbook.java:221)
at jxl.Workbook.getWorkbook(Workbook.java:198)
at test.ReadTest.main(ReadTest.java:19)
I would try using Apache MetaModel instead. I have had better luck with that, than using JXL. Here is a example project I wrote that reads from a .XLSX file. I use this library to run tests on a Linux Jenkins server from .XLS files generated on MS Windows.
Also, it should be noted that this library is also perfect for making a parameterized DataProvider that queries a database with JDBC.
Using JXL, you limit yourself to one data type, either .XLS or .CSV. I believe MetaModel is actually using JXL under the hood and wrapping it to make it easier to use. So, it also would support the OpenOffice documents in the same fashion and suffer the same file compatibility issues.

apache-poi-3.9 + creating Dropdown

I am trying to create dropdown list in XLS using Apache-poi-3.9 .
Following code I have written ::
public class TestMacroTemplate {
/**
* #param args
* #throws IOException
*/
public static void main(String args[]) throws FileNotFoundException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Data Validation");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DVConstraint dvConstraint = DVConstraint
.createExplicitListConstraint(new String[] { "10", "20", "30" });
DataValidation dataValidation = new HSSFDataValidation(addressList,
dvConstraint);
dataValidation.setSuppressDropDownArrow(false);
sheet.addValidationData(dataValidation);
FileOutputStream fileOut = new FileOutputStream("XLCellDropDown.xls");
try {
workbook.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But it gives the following Exception :
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFSheet.addValidationData(Lorg/apache/poi/ss/usermodel/DataValidation;)V
at ejb.TestMacroTemplate.main(TestMacroTemplate.java:31)
And the same code works with Apache-poi-3.2
Please help me.
Thanks ,
Nirav
Apache POI have a FAQ on this very problem. I'll quote from there, as it'll solve your problem
My code uses some new feature, compiles fine but fails when live with a "MethodNotFoundException", "NoSuchMethodError" or "IncompatibleClassChangeError"
You almost certainly have an older version of POI on your classpath. Quite a few runtimes and other packages will ship an older version of POI, so this is an easy problem to hit without your realising.
The best way to identify the offending earlier jar file is with a few lines of java. These will load one of the core POI classes, and report where it came from.
ClassLoader classloader =
org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getResource(
"org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("Core POI came from " + path);
It works fine in Apache poi 3.9 and i have tested it.just incluse these jars
poi-scratchpad-3.9-20121203.jar
poi-3.9-20121203.jar
poi-examples-3.9-20121203.jar
poi-excelant-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar

Smooks GroovyContentHandlerFactory Exception when upgrading from 1.4 to 1.5.1?

I have recently upgraded my Smooks application from 1.4 to 1.5.1, but I keep getting the exception below:
Error when processing EDI file org.milyn.cdr.SmooksConfigurationException: Error
invoking #Initialize method 'initialize' on class 'org.milyn.smooks.scripting.groovy.GroovyContentHandlerFactory'.
I am pretty new to Smooks and Groovy, but this is an extract of my code, which was working in version 1.4.
I also have all the 1.5.1 classes in my classpath, including the 1.5 EDI definitions I am trying to load.
Smooks smooks = null;
try {
smooks = new Smooks();
}
catch(Exception exception) { System.out.println("Error " + exception); }
try {
smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d01b-mapping:*"));
// Create an exec context - no profiles....
ExecutionContext executionContext = smooks.createExecutionContext();
DOMResult domResult = new DOMResult();
// Configure the execution context to generate a report...
executionContext.setEventListener(new HtmlReportGenerator("EDI/reports/report.html"));
smooks.filterSource(new StreamSource((InputStream) bufferedinputstream), domResult);
Extract from GroovyContentHandlerFactory
#Initialize
public void initialize() throws IOException {
String templateText = StreamUtils.readStreamAsString(getClass().getResourceAsStream("ScriptedGroovy.ftl"));
classTemplate = new FreeMarkerTemplate(templateText);
Any help or ideas would be much appreciated as I have spent hours on trying to figure this one out.
Cheers, Matt

Resources