View pdf in JPanel - pdf

How to view the pdf in JPanel using PDfBox??
I have the Source Code Like below.
try {
PDDocument inputPDF = PDDocument.load(FilePath);
List<PDPage> AllPages = inputPDF.getDocumentCatalog().getAllPages();
inputPDF.close();
PDPage TestPage = (PDPage)AllPages.get(0);
PDFPagePanel pdfPanel = new PDFPagePanel();
pdfPanel.setPage(TestPage);
pnlRiwayatStatus.add(pdfPanel);
}
catch(Exception e){
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, e);
}
But thus source code NoClassDefFoundError

The missing class is mentioned in a comment:
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
This shows that you don't have the Apache Commons Logging jar in your class path.
According to the PDFBox web site, though, it is a required dependency:
Minimum Requirements
PDFBox has the following basic dependencies:
Java 6
commons-logging
Commons Logging is a generic wrapper around different logging frameworks, so you’ll either need to also use a logging library like log4j or let commons-logging fall back to the standard java.util.logging API included in the Java platform.
You should consider using Apache Maven for automatic dependency resolution.

Related

Android studio JavaDoc error throws a NullPointerException

Android studio cannot create JavaDoc. It throws a null pointer exception and cannot identify any of the android packed items.
...
/home/<user>/AndroidStudioProjects/<project>/app/src/main/java/com/example/simpleparadox/listycity/MainActivity.java:14: error: cannot access ViewGroup
public class MainActivity extends AppCompatActivity {
^
class file for android.view.ViewGroup not found
javadoc: error - fatal error encountered: java.lang.NullPointerException
javadoc: error - Please file a bug against the javadoc tool via the Java bug reporting page
(http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com)
for duplicates. Include error messages and the following diagnostic in your report. Thank you.
java.lang.NullPointerException
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$MembersPhase.runPhase(TypeEnter.java:934)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$Phase.doCompleteEnvs(TypeEnter.java:282)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$MembersPhase.doCompleteEnvs(TypeEnter.java:877)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$Phase.completeEnvs(TypeEnter.java:251)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$Phase.completeEnvs(TypeEnter.java:266)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$Phase.completeEnvs(TypeEnter.java:266)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter$Phase.completeEnvs(TypeEnter.java:266)
at jdk.compiler/com.sun.tools.javac.comp.TypeEnter.complete(TypeEnter.java:198)
at jdk.compiler/com.sun.tools.javac.code.Symbol.complete(Symbol.java:642)
at jdk.compiler/com.sun.tools.javac.code.Symbol$ClassSymbol.complete(Symbol.java:1326)
at jdk.compiler/com.sun.tools.javac.comp.Enter.complete(Enter.java:583)
at jdk.compiler/com.sun.tools.javac.comp.Enter.main(Enter.java:560)
at jdk.javadoc/jdk.javadoc.internal.tool.JavadocEnter.main(JavadocEnter.java:79)
at jdk.javadoc/jdk.javadoc.internal.tool.JavadocTool.getEnvironment(JavadocTool.java:206)
at jdk.javadoc/jdk.javadoc.internal.tool.Start.parseAndExecute(Start.java:576)
at jdk.javadoc/jdk.javadoc.internal.tool.Start.begin(Start.java:432)
at jdk.javadoc/jdk.javadoc.internal.tool.Start.begin(Start.java:345)
at jdk.javadoc/jdk.javadoc.internal.tool.Main.execute(Main.java:63)
at jdk.javadoc/jdk.javadoc.internal.tool.Main.main(Main.java:52)
7 errors
Then I found a work around which add -bootclasspath path_to_sdk_android_jar_file in the other command-line argument text box in the JavaDoc dialog.
However, newer Java deprecated -bootclasspath. It throws another error as follows:
error: option --boot-class-path not allowed with target 11
So I used -sourcepath instead. That brought the old error (NullPointerException).
I am pretty much lost at this point.
By the way, if I choose a class with only Java elements (no-android) and create JavaDoc to that specific file only, it creates JavaDoc nicely. But this is not a good workaround for a project with a lot of classes.
I've faced the same issue as yours with several imports errors..
The following solution worked for me ( I got it from mike192's answer, see the link here )
task javadoc(type: Javadoc) {
doFirst {
configurations.implementation
.filter { it.name.endsWith('.aar') }
.each { aar ->
copy {
from zipTree(aar)
include "**/classes.jar"
into "$buildDir/tmp/aarsToJars/${aar.name.replace('.aar', '')}/"
}
}
}
configurations.implementation.setCanBeResolved(true)
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
classpath += configurations.implementation
classpath += fileTree(dir: "$buildDir/tmp/aarsToJars/")
destinationDir = file("${project.buildDir}/outputs/javadoc/")
failOnError false
exclude '**/BuildConfig.java'
exclude '**/R.java'
}
All you need to do is to add the code to your build.gradle file right before your dependencies {}
Then, double click on your Ctrl button and execute the following command :
gradle javadoc
The result of the javadoc can be then found in your project's directory \app\build\outputs\javadoc
I hope this works for you

Regiser JacksonJsonProvider in Websphere liberty profile

I am trying to call a REST service from an EJB hoping to utilize Jackson's
#JsonIgnoreProperties(ignoreUnknown = true)
The following does the trick in wlp v8.5.5.9
Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
The same code produces a NullPointerException in the wlp v16.0.0.2
Caused by: java.lang.NullPointerException
at org.apache.cxf.jaxrs.impl.tl.ThreadLocalProviders.getContextResolver(ThreadLocalProviders.java:50)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.locateMapper(JacksonJsonProvider.java:634)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:413)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBodyReader(JAXRSUtils.java:1356)
at org.apache.cxf.jaxrs.impl.ResponseImpl.doReadEntity(ResponseImpl.java:438)
... 98 more
I have found a discussions triggered by the same problems in v8.5.5.9, but I am not sure how it could help me. As I noted I have no troubles with the code in the v8.5.5.9
Another discussion was related to the Jackson v2.x. Initially I used Jackson v1.9.13, but I have tried to switch to the newest Jeckson 2.8.0 version and apply the offered solution. The same outcome: application works in wlp 8.5.5.9 and produces the same error in v16.0.0.2.
Any ideas?
Update:
the problem could be avoided by extending the JacksonJsonProvider class and explicitly providing object mapper
public class MyJacksonJsonProvider extends JacksonJsonProvider {
public MyJacksonJsonProvider() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibilityChecker(objectMapper.getVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
setMapper(objectMapper);
}
}
and then registering it in the client
Client client = ClientBuilder.newClient().register(MyJacksonJsonProvider.class);
However it would be nice to understand if it is a bug or a feature.

Issue with Spring Security, Spring Webflow, file uploads and UTF-8

I have a problem very similar to the one described here: File Upload using Spring WebFlow 2.4.0, parameter not binded, but that one didn't mention anything about UTF-8 issues. I'm using Spring Framework 4.1.6, Spring Security 4.0.2 and Spring Webflow 2.4.2.
It revolves around StandardServletMultipartResolver vs. CommonsMultipartResolver as far as I can tell, but I'm not sure. If I use CommonsMultipartResolver I can upload files on any page except for Webflow pages fine and UTF-8 encoding works as well on all pages. However on the Webflow pages an exception is thrown trying to access the file . If I use StandardServletMultipartResolver then all of the file uploads work, including Webflow, but on any page that has a UTF-8 character, e.g., caractère, I get garbage.
The wierd thing is I can see in FireBug that the file is being posted when I use the commons resolver. Also, if I debug the RequestContext coming from Webflow I can also see the file buried 4 levels deep in requests. The code for the common resolver (see end of post for the standard resolver code):
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
MultipartHttpServletRequest multipartRequest = new DefaultMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest());
MultipartFile file = multipartRequest.getFile("file");
So, is this a Spring Security issue or a Spring Webflow problem? I suspect the commons resolver would work if I could cast the RequestContext above correctly, but I've tried numerous combinations with no luck. Any guidance on this would be greatly appreciated.
Here are some relevant configurations and code:
WebMvcConfig
#Bean
public CommonsMultipartResolver filterMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
return resolver;
}
SecurityConfig
#Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
http
//.csrf().disable()
.addFilterBefore(characterEncodingFilter, CsrfFilter.class)
...more settings...
SecurityInitializer
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
Webflow Action
<action-state id="uploadFile">
<evaluate expression="fileActions.uploadFile(recipe, flowRequestContext)"/>
<transition to="review"/>
</action-state>
Upload file method
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
MultipartHttpServletRequest multipartRequest = new StandardMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest());
MultipartFile file = multipartRequest.getFile("file");
...rest of code to save the file...
Turns out you can cast the RequestContext to get at the underlying MultipartHttpServletRequest but it's not pretty. Here's what I ended up with:
Upload file method
public FileResult uploadFile(Recipe recipe, RequestContext requestContext) {
logger.debug("uploadFile");
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
SecurityContextHolderAwareRequestWrapper wrapper1 = (SecurityContextHolderAwareRequestWrapper)context.getNativeRequest();
HttpServletRequestWrapper wrapper2 = (HttpServletRequestWrapper)wrapper1.getRequest();
FirewalledRequest firewall = (FirewalledRequest)wrapper2.getRequest();
MultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest)firewall.getRequest();
MultipartFile file = multipartRequest.getFile("file");
...rest of code to save the file...
Using this I get to keep the CommonsMultipartResolver, all file uploads in the app work whether Webflow or not, and I have no issues with UTF-8 and character mangling.
I'm not particularly happy with this solution (even though it works) since it's dependent upon a specific nesting of requests that could change in the future(?). I'm be interested if anyone else has run into the same UTF-8 issue and how they solved it, but for now I'm going to test the heck out of this and move on.

Exception error in google doc api

I am new to google api. I am trying to create a simple web application (Java EE) to read DocumentListFeed from google doc. My code in the servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DocsService service = new DocsService("Document List Demo");
service.setUserCredentials(NAME, PASSWORD);
response.getWriter().println("helloooooo");
//URL documentListFeedUrl = new URL("http://docs.google.com/feeds/documents/private/full");
URL documentListFeedUrl = new URL("https://docs.google.com/feeds/default/private/full?v=3");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries())
{
response.getWriter().println(entry.getTitle().getPlainText());
}
}
catch (Exception e)
{
response.getWriter().println(e);
}
}
But it is showing me the error: java.lang.NoClassDefFoundError: com/google/gdata/client/docs/DocsService
I am using Glassfish server and Ecllipse. And added external jar file: activation.jar, guava-r07.jar, mail.jar, servlet.jar, gdata-client-1.0.jar, gdata-client-meta-1.0.jar, gdata-core-1.0.jar, gdata-media-1.0.jar, gdata-docs-3.0.jar, gdata-docs-meta-3.0.jar.
I have copied this same code to java standard edition and it is working fine. Could please tell me why this thing is not working in Java EE? Is it a problem in GlassFish server?
It just means that the jars are not present in your Glassfish server classpath.
Add all the jars you listed to yuor glassfish server classpath. Since am not an Glassfish expert i cannot help you in adding the jars to your server.
In case of weblogic, you just need to package all the jars in your project APP-INF directory.
Hope it helps.

Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC'

I'm using Sap Jco to connect to SAP database with the front end being Java(JSF), When I connect to SAP with:
try {
mConnection =JCO.createClient("400", // SAP client
"c3026902", // userid
"********", // password
"EN", // language
"iwdf5020", // host name
"00"); // system number
mConnection.connect();
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
Problem I'm facing is when run the application for the first time, data is displayed but when I re-run it says "Could not load middleware layer 'com.sap.mw.jco.rfc.MiddlewareRFC' "
Can any one help me in resolving the issue?????
This sounds like the API cannot load the native driver files.
The SAP Java Connector consists of a native runtime part, that does the actuall communication and a Java API that wraps this functionality with a java api.
The Java API is inside the sapjco.jar and the native drivers are e.g on windows inside librfc32.dll and sapjcorfc.dll.
Place these dll's into your system path (e.g. windows: C:\WiNDOWS\system32) and it should run.
Cheers
Sebastian
Are your DLLs located in the Windows system32 folder? If so, are you probably using the wrong architecture? (x64 DLL on 32 bit or vice versa)
Also, are the DLLs the same version as the java api? If you have SAP GUI installed there could be older DLLs around.
Defining SAP connection:
For the Version 3,0 of the sapjco library there exists plenty of useful information. To create a connection following the instructions in:
http://www.browseye.com/linkShare.html?url=http://help.sap.com/saphelp_nwpi711/helpdata/en/46/fb807cc7b46c30e10000000a1553f7/content.htm?bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1&bwsCriterion=%22Setting%20Up%20Connection%22&bwsMatch=1
There are a few thing that you should take into account:
Place the dll file in the same place that the jar.
The dll must be the right version for your operating system and architecture otherwise you will get a native library error.
Example of code to create a connection to the server.
public class StepByStepClient
{
static String DESTINATION_NAME1 = "ABAP_AS_WITHOUT_POOL";
static String DESTINATION_NAME2 = "ABAP_AS_WITH_POOL";
static
{
Properties connectProperties = new Properties();
connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "ls4065");
connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "85");
connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "800");
connectProperties.setProperty(DestinationDataProvider.JCO_USER, "homofarber");
connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "laska");
connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "en");
createDestinationDataFile(DESTINATION_NAME1, connectProperties);
connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");
connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");
createDestinationDataFile(DESTINATION_NAME2, connectProperties);
}
static void createDestinationDataFile(String destinationName, Properties connectProperties)
{
File destCfg = new File(destinationName+".jcoDestination");
try
{
FileOutputStream fos = new FileOutputStream(destCfg, false);
connectProperties.store(fos, "for tests only !");
fos.close();
}
catch (Exception e)
{
throw new RuntimeException("Unable to create the destination files", e);
}
}
public static void step1Connect() throws JCoException
{
JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
System.out.println("Attributes:");
System.out.println(destination.getAttributes());
System.out.println();
}
}
In SAPJco 3.0 connections are build from the info contained in a “Destination”.
The documentation example use a properties file to save the “Destination”. However it is a non-secure way to keep connection info. As is indicated on the documentation in the hightlighted paragraph you can see on next link.
http://help.sap.com/saphelp_nwpi711/helpdata/en/48/5fb9f9b523501ee10000000a421937/content.htm?bwsCriterion=%22In%20practice%20you%20should%20avoid%20this%20for%20security%20reasons.%22&bwsMatch=1
You can keep connection info on a database or any other storage system if you create a custom “DestinationDataProvider” In the Examples provided with the SAPJco library there is an example of how to create a custom DestinationDataProvider.