itextpdf: loadLicenseFile issue - itext7

I'm on just started to play with itextpdf 7.2.2, and I see an issue while trying to load my trial license. Here is the code snapshot:
#Autowired
private ResourceLoader resourceLoader;
public void loadItextLicense() {
try {
String licenseFileName = "classpath:licenses/ae2b7b01aa4d3b744f5873d3e3b66182bce5fd6bc0cd4993b0504aabab7882ef.json";
Resource resource = resourceLoader.getResource(licenseFileName);
File lFile = resource.getFile();
log.info("File exists? " + lFile.exists());
LicenseKey.loadLicenseFile(lFile);
}
catch (Exception e) {
log.error("ItextService error: ", e);
}
}
Here is the exception stack trace:
java.lang.NoSuchFieldError: _objectFieldValueSeparatorWithSpaces
at com.itextpdf.licensing.base.util.JsonUtil$CustomPrettyPrinter.(JsonUtil.java:135)
at com.itextpdf.licensing.base.util.JsonUtil.serializeToString(JsonUtil.java:44)
at com.itextpdf.licensing.base.util.SigningUtil.getExpectedSignature(SigningUtil.java:67)
at com.itextpdf.licensing.base.util.SigningUtil.checkSignature(SigningUtil.java:52)
at com.itextpdf.licensing.base.actions.LoadLicenseEvent.validateLicenceFile(LoadLicenseEvent.java:118)
at com.itextpdf.licensing.base.actions.LoadLicenseEvent.getProperLicenseFile(LoadLicenseEvent.java:100)
at com.itextpdf.licensing.base.actions.LoadLicenseEvent.(LoadLicenseEvent.java:42)
at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:151)
at com.itextpdf.licensing.base.LicenseKey.loadListOfLicenses(LicenseKey.java:202)
at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:129)
at com.itextpdf.licensing.base.LicenseKey.loadLicenseFile(LicenseKey.java:88)
at com.cchs.microservice.contract.service.impl.ItextService.loadItextLicense(ItextService.java:26)
Any help would be greatly appreciated!

Related

classPool.get(className) throws RuntimeException cannot find class

I am trying to write a simple instrumentation agent using Javassist.
public class Agent implements ClassFileTransformer {
protected Instrumentation instrumentation;
protected ClassPool classPool;
public Agent(Instrumentation instrumentation){
this.instrumentation = instrumentation;
this.classPool = ClassPool.getDefault();
this.instrumentation.addTransformer(this);
}
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
try {
System.out.printf("%s.transform: %s\n", this.getClass().getCanonicalName(), className);
classPool.insertClassPath(new ByteArrayClassPath(className, classfileBuffer));
CtClass ctClass = classPool.get(className); /* <- throws error */
}
catch (Exception ex){
System.out.println(ex);
return null;
}
}
}
But I get the following errors:
java.lang.RuntimeException: cannot find java/lang/invoke/MethodHandleImpl: java.lang.invoke.MethodHandleImpl found in java/lang/invoke/MethodHandleImpl.class
The only class that doesn't throw this exception is the one in my project in the IDE (IntelliJ IDEA).
I tried to add the paths from the classpath manually, but that didn't help either. i.e.
String[] cpEntries = System.getProperty("java.class.path").split(File.pathSeparator);
for (String cpEntry : classpathEntries)
classPool.insertClassPath(cpEntry);
What am I missing? Thanks!
The problem is that className's separator is a /, while classPool.get(className) expects the . delimiter, so the fix is to replace those characters, i.e.:
String classNameDotted = className.replace('/', '.');
CtClass ctClass = classPool.get(classNameDotted);

Calling Spring Main Method from Another Class Error

I am working on a Plugin for an OpenFire Server. I am trying to integrate Spring into this plugin. When the plugin is initialized, I will like to call the Main Method for my Spring.
When I execute the Spring alone, it works fine, but when I call its main method from my plugin, I get an exception.
How am I suppose to call the Spring Main Method.
What am I missing. Any help will be appreciated. Thank you.
Spring Main Class:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
try {
SpringApplication.run(Application.class, args);
System.out.println("No error");
} catch (Exception e) {
System.out.println("Error " + e);
}
}
}
OpenFire Plugin:
public class FetchNewsPlugin implements Plugin {
#Override
public void initializePlugin(PluginManager manager, File pluginDirectory) {
Runnable r = new Runnable() {
public void run() {
String[] args = {};
Application.main(args);
}
};
new Thread(r).start();
System.out.println("Plugin Intitialized");
}
#Override
public void destroyPlugin() {
}
}
Log Output:
Exception in thread "Thread-13" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
at hello.Application.main(Application.java:11)
at org.clinton.openfire.plugin.FetchNewsPlugin$1.run(FetchNewsPlugin.java:20)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more
Where Exception is being thrown:
/**
* Finds and loads the class with the specified name from the URL search
* path. Any URLs referring to JAR files are loaded and opened as needed
* until the class is found.
*
* #param name the name of the class
* #return the resulting class
* #exception ClassNotFoundException if the class could not be found,
* or if the loader is closed.
* #exception NullPointerException if {#code name} is {#code null}.
*/
protected Class findClass(final String name)
throws ClassNotFoundException
{
final Class result;
try {
result = AccessController.doPrivileged(
new PrivilegedExceptionAction>() {
public Class run() throws ClassNotFoundException {
String path = name.replace('.', '/').concat(".class");
Resource res = ucp.getResource(path, false);
if (res != null) {
try {
return defineClass(name, res);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
} else {
return null;
}
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
throw (ClassNotFoundException) pae.getException();
}
if (result == null) {
throw new ClassNotFoundException(name);
}
return result;
}
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/clinton/git/Openfire/bin/build/lib/ant/slf4j-simple.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/clinton/git/Openfire/bin/build/lib/dist/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/clinton/git/Openfire/build/lib/ant/slf4j-simple.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/clinton/git/Openfire/build/lib/dist/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]
It seems like you are using URLClassLoader to load classes that your needed. However, an URLClassLoader should contain all items or jars it depends on not only the jar itself.
In other words, you'd better extract your jar and add all necessary items to your URLClassLoader.
In this way it should work. And please let me know if any problem.
And question https://stackoverflow.com/a/37339725/5619827 could be helpful.
Thanks #Gemini for helping, but I guess I was too dumb to follow his way. I found another workaround: Since the Spring could start successfully when executed alone. I bundled the Spring into a runnable jar file and executed using the following when th plugin starts:
private void startSpring() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("/usr/lib/jvm/java-8-oracle/bin/java", "-jar",
"/home/clinton/git/Maven/target/mavenproject2-1.0-SNAPSHOT.jar");
processBuilder.directory(new File("/home/clinton/git/Maven/Working"));
File log = new File("log");
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(Redirect.appendTo(log));
Process p = processBuilder.start();
assert processBuilder.redirectInput() == Redirect.PIPE;
assert processBuilder.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;
System.out.println("Started success");
//Process p = processBuilder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this helps someone too. I always find a way :)

How to transfer *.pgp files using SFTP spring Integration

We are developing generic automated application which will download *.pgp file from SFTP server.
The application working fine with *.txt files. But when we are trying to pull *.pgp files we are getting the below exception.
2016-03-18 17:45:45 INFO jsch:52 - SSH_MSG_SERVICE_REQUEST sent
2016-03-18 17:45:46 INFO jsch:52 - SSH_MSG_SERVICE_ACCEPT received
2016-03-18 17:45:46 INFO jsch:52 - Next authentication method: publickey
2016-03-18 17:45:48 INFO jsch:52 - Authentication succeeded (publickey).
sftpSession org.springframework.integration.sftp.session.SftpSession#37831f
files size158
java.io.IOException: inputstream is closed
at com.jcraft.jsch.ChannelSftp.fill(ChannelSftp.java:2884)
at com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2908)
at com.jcraft.jsch.ChannelSftp.access$500(ChannelSftp.java:36)
at com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1390)
at com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1340)
at org.springframework.util.StreamUtils.copy(StreamUtils.java:126)
at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:109)
at org.springframework.integration.sftp.session.SftpSession.read(SftpSession.java:129)
at com.sftp.test.SFTPTest.main(SFTPTest.java:49)
java code :
public class SFTPTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
DefaultSftpSessionFactory defaultSftpSessionFactory = applicationContext.getBean("defaultSftpSessionFactory", DefaultSftpSessionFactory.class);
System.out.println(defaultSftpSessionFactory);
SftpSession sftpSession = defaultSftpSessionFactory.getSession();
System.out.println("sftpSessikon "+sftpSession);
String remoteDirectory = "/";
String localDirectory = "C:/312421/temp/";
OutputStream outputStream = null;
List<String> fileAtSFTPList = new ArrayList<String>();
try {
String[] fileNames = sftpSession.listNames(remoteDirectory);
for (String fileName : fileNames) {
boolean isMatch = fileCheckingAtSFTPWithPattern(fileName);
if(isMatch){
fileAtSFTPList.add(fileName);
}
}
System.out.println("files size" + fileAtSFTPList.size());
for (String fileName : fileAtSFTPList) {
File file = new File(localDirectory + fileName);
/*InputStream ipstream= sftpSession.readRaw(fileName);
FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(ipstream));
ipstream.close();*/
outputStream = new FileOutputStream(file);
sftpSession.read(remoteDirectory + fileName, outputStream);
outputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static boolean fileCheckingAtSFTPWithPattern(String fileName){
Pattern pattern = Pattern.compile(".*\\.pgp$");
Matcher matcher = pattern.matcher(fileName);
if(matcher.find()){
return true;
}
return false;
}
}
Please suggest how to sort out this issue.
Thanks
The file type is irrelevant to Spring Integration - it looks like the server is closing the connection while reading the preamble - before the data is being fetched...
at com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2908)
at com.jcraft.jsch.ChannelSftp.access$500(ChannelSftp.java:36)
at com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1390)
at com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1340)
The data itself is not read until later (line 1442 in ChannelSftp).
So it looks like a server-side problem.

Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage name

I'm developing an app that processes files in ODS format.The code snippet is as follows:
public static void main(String[] args) throws IOException {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
display();
//print();
}
private static void display() throws IOException {
// Load the spreadsheet.
final OpenDocument doc = new OpenDocument();
doc.loadFrom("temperature3.ods");
String styleName = "Calibri";
StyleHeader header = new StyleHeader();
header.setStyleDisplay("Testing");
StyleMasterPage page = new StyleMasterPage();
page.setStyleHeader(header);
page.setStyleName(styleName);
OfficeMasterStyles off = new OfficeMasterStyles();
off.addMasterPage(off.getMasterPageFromStyleName(styleName));
doc.setMasterStyles(off);
// Show time !
final JFrame mainFrame = new JFrame("Viewer");
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
ODSViewerPanel viewerPanel = new ODSViewerPanel(doc, true);
mainFrame.setContentPane(viewerPanel);
mainFrame.pack();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocation(10, 10);
mainFrame.setVisible(true);
}
I intend loading the file into a jcomponent for easy manipulation but I'm having this error message in the netbeans console:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage named:Calibri
at org.jopendocument.model.office.OfficeMasterStyles.getMasterPageFromStyleName(Unknown Source)
at starzsmarine1.PrintSpreadSheet.display(PrintSpreadSheet.java:60)
at starzsmarine1.PrintSpreadSheet.main(PrintSpreadSheet.java:45)
Is there an alternative API for this purpose?

AfterThrowing advice not working Spring AOP

I cannot get my afterThrowing Spring AOP advice to fire,
I have made the point cut as generic as possible now and it still does not fire
I hope this is just a poor pointcut but I cannot see why, I would be grateful if anyone could see why
Advice
//Generic Exceptions
#AfterThrowing(value = "execution(* *(..)) throws Exception", throwing = "exception")
public void loggingGenericException(JoinPoint joinPoint, Exception exception) {
String classMethod = this.getClassMethod(joinPoint);
String stackTrace = "";
for (StackTraceElement element : exception.getStackTrace()) {
stackTrace += element.toString() + "\n";
}
String exceptionMessageAndStackTrace = exception.getMessage() + "\n" + stackTrace;
if (exception instanceof EmptyResultSetException) {
this.infoLevelLogging(joinPoint, classMethod);
} else {
this.errorLevelLogging(joinPoint, classMethod, exceptionMessageAndStackTrace);
}
}
Method that should be advised
public void getStudentTranscript(String studentId) throws RestClientException,IllegalArgumentException{
if (!this.serviceUrl.isEmpty()) {
if(studentId.isEmpty())
{
throw new IllegalArgumentException("studentId empty");
}
this.transcript = (Transcript) super.getForObject(this.serviceUrl,Transcript.class, studentId);
} else {
throw new IllegalArgumentException("url is empty");
}
}
If I run a test to check it is applied it is not working the test looks like this
#Test
public void testLoggingFiredOnExceptionInTranscriptRepository() throws Exception
{
Log log;
log = mock(Log.class);
when(log.isErrorEnabled()).thenReturn(true);
try {
loggingAspects.setLogger(log);
transcriptRepository.setServiceUrl("");
transcriptRepository.getStudentTranscript("12345");
} catch (RuntimeException e) {
System.out.println("e = " + e);
verify(log, times(1)).isErrorEnabled();
verify(log, times(1)).error(anyString());
}
}
The system out shows an exception fired
Can anyone offer any advice ( pun intended) :-)
Did you put the <aop:aspectj-autoproxy /> element in your spring configuration file? Otherwise, the AOP annotations won't be interpreted.
FYI, after having read your question, I created a sample project on my own and the #AfterThrowing annotation just works as it should.

Resources