NullPointerException on Apache Server Servlet using JPA - java

Im trying to display contents of table (test_dept) which is in SQLSERVER
I have created a connection profile also.
I have written a Servlet like below... But Im getting this error.
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
//import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = "/ServletClient")
public class ServletClient extends HttpServlet
{
#PersistenceUnit
EntityManagerFactory factory;
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
//ServletOutputStream out = resp.getOutputStream();
PrintWriter pw = resp.getWriter();
java.util.List list = factory.createEntityManager().createQuery("select f from test_dept f;").getResultList();
pw.println("<html><body bgcolor=silver text=green><table>");
for (Object tdp : list)
{
pw.println("In The Loop");
pw.println("<tr><td>" + ((TestDept) tdp).getDptnam() + "</td></tr>");
}
pw.println("</table>");
pw.println("<font size=35><b>List created AdapChain</b></font>");
pw.println("</body></html>");
}
}

I don't think any version of Apache Tomcat supports injection of EntityManager or EntityManagerFactory objects out of the box.
You need to choose a server platform that supports more of the JavaEE specification.

Related

Package doesnt exist error when trying to import my own package to servlet

im trying to import my own packages to a servlet im making, using tomcat.
The two java files im working with are the servlet (movieServlet.java), and another class im trying to import from a package (Movie.java)
The hierarchy of folders is:
classes
|
+--movieServlet.java
|
+--movie
|
+--Movie.java
movieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import movie.Movie;
#WebServlet(urlPatterns = {"/movieServlet"})
public class movieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Movie Movie = new Movie();
request.setAttribute("movies", Movie.getAllMovies());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsps/movies.jsp");
dispatcher.forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsps/movieDetails.jsp");
dispatcher.forward(request,response);
}
}
and this is the top of Movie.java (its a long file)
package movie;
import java.util.*;
import java.util.List;
import javax.sql.*;
import java.sql.*;
import javax.naming.InitialContext;
public class Movie implements java.io.Serializable
{
private static DataSource dataSource = null;
private static Connection c = null;
private int id;
private String title;
private String url;
private int year;
public Movie(){}
if theres more info needed please ask :), this has been reallllly bugging me.
I am new here so excuse me if my answer is not perfect. As you have mentioned that you want to import your own package which contains Movie class. I tried to implement all your main methods and it's running perfect and I am getting my value from Movie.java.
movieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import movie.Movie;
public class movieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Movie Movie = new Movie();
request.setAttribute("movies", Movie.getAllMovies());
out.println(request.getAttribute("movies"));
}
}
Movie.java
package movie;
public class Movie {
String s;
public Movie(){
s="hello zDoctor";
}
public String getAllMovies(){
return s;
}
}
servlet output
file structure

How to set response header for digital asset in AEM CQ6.1?

I have a request that if a user directly accesses a .pdf asset(for example, http://localhost:4505/content/dam/company/us/en/962059.pdf) from AEM CQ 6.1, I need to send a custom http respone header. This is what I wrote. This is only works if I open a .html page. But it doesn't work if I open a .pdf in browser. So what did I do wrong?
Thanks
package com.mycompany.wcm.filter;
import org.apache.felix.scr.annotations.*;
import org.apache.felix.scr.annotations.sling.SlingFilter;
import org.apache.felix.scr.annotations.sling.SlingFilterScope;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.*;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.runmode.RunMode;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Session;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
#SlingFilter(
label = "Sample Filter",
description = "Sample Description",
metatype = true,
generateComponent = true, // True if you want to leverage activate/deactivate
generateService = true,
order = -501, // The smaller the number, the earlier in the Filter chain (can go negative);
scope = SlingFilterScope.REQUEST)
#Properties({
#Property(
label = "Vendor",
name = "service.vendor",
value = "SampleVendor",
propertyPrivate = true
)
})
public class AssetFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response;
slingResponse.setHeader("myheader1","no-cache");
slingResponse.setHeader("myheader2","no-store");
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}
Just a update, initialy I thought the problem only happens to .pdf file, but this also happens to image file. So I created a regular JSP web application, and this code is working for regular web app. Is there something funny on AEM side?

how to write code for user task in JBPM

I am a newbie when it comes to JBPM. And while I have created the sample application with a script task and user task. When I remove user task the bpmn is executing fine. But when I keep UserTask it is throwing an exception.
Following is my code:
package com.Sservlet;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.drools.KnowledgeBase;
import org.drools.SystemEventListenerFactory;
import org.drools.builder.*;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.process.ProcessInstance;
import org.jbpm.bpmn2.handler.ServiceTaskHandler;
import org.jbpm.process.workitem.wsht.CommandBasedWSHumanTaskHandler;
import org.jbpm.task.*;
import org.jbpm.task.service.*;
public class SServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("Jcr.bpmn2"), ResourceType.BPMN2);
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
CommandBasedWSHumanTaskHandler taskHandler = new CommandBasedWSHumanTaskHandler(ksession);
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new ServiceTaskHandler());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.task");
TaskService taskService = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener());
TaskServiceSession taskSession = taskService.createSession();
// now register new users and groups
List list = taskSession.getTasksAssignedAsPotentialOwner("John", "en-UK");
taskHandler.connect();
ProcessInstance processInstance = ksession.startProcess("TestHandle");
System.out.println("hello here are");
}
}
I am receiving a No Persistence provider exception:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named org.jbpm.task
I don't need any database insertion here. It is a simple user-task. Is there any solution?

java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet

I want to implement a servlet and call it in a WebApp.
I am constantly get java.lang.ClassCastException: Servlet.Telnet cannot be cast to javax.servlet.Servlet from the Apache Tomcat Server. I made sure my class extends HttpServlet this is my code:
package Servlet;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.telnet.TelnetClient;
public class Servlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
TelnetClient telnet = new TelnetClient();
telnet.connect(request.getParameter("router"), 23);
PrintStream output = new PrintStream(telnet.getOutputStream());
output.println(request.getParameter("login"));
output.flush();
output.println(request.getParameter("password"));
output.flush();
out.printf("SUCCESS");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
out.printf("ERROR");
}
}
I renamed the package and the class and it works perfectly.

Addition of web service access in servlet unrecognized/unresolved; seen as "type".

I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.

Categories