i have made a sample servlet program and on compiling it is giving error. Error says that none of my included packages exists. following is both my servlet class and errors.
classpath :
.;C:\Program
Files\Java\jdk1.7.0_45\bin;D:\apache-tomcat-7.0.37\lib\servlet-api.jar;D:\apache-tomcat-7.0.37\lib\jsp-api;
Path
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program
Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files
(x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program
Files\Java\jdk1.7.0_45\bin;D:\apache-tomcat-7.0.37\bin
Servlet class (Ch1Servlet.java)
import javax.servlet.*;
import javax.servlet.http.*;
import javax.io.*;
public class Ch1Servlet extends HttpServlet
{
public void doGet (HttpServletRequest request , HttpServletResponse response) throws IOException
{
PrintWriter out = response.getWriter();
java.util.Date today = new java.util.Date();
out.prtinln( "<html> " + "<body> " +
"<h1 align = center> HF\'s chapter1 servlet <h1>"
+ "<br>" +today+ "</body> " + "</html>"
) ;
}
}
ERROR
There was one error :
i have written -- >
import javax.io.*;
it should be -- >
import java.io.*;
and rest of the errors got sorted out after i restarted my system.
Related
First, I am a beginner in java servlets, maven projects and apis.
I am doing the following tutorial on getting started with google endpoints, which is a tutorial implementing the following maven project source code on github. On the web.xml, there is only one named Servlet, the EndpointsServlet like so:
<!-- wrap the backend with Endpoints Framework v2. -->
<servlet>
<servlet-name>EndpointsServlet</servlet-name>
<servlet-class>com.google.api.server.spi.EndpointsServlet</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value>com.example.echo.Echo</param-value>
</init-param>
</servlet>
What I dont understand is why are there no other servlets on the project? There are only 3 java classes in the main directory and none of them are servlet files. I am assuming that this project is a sample api with server side logic (such as routing and responding to requests) like any other servlet project which means there should be more than this servlet.
The comment on the web.xml is an obvious clue as to what it does but I dont really know what wrapping the backend with endpoints framework means. Also, I actually got the EndpointsServlet.java file and it says the servlet is a "handler for proxy-less API serving. This servlet understands and replies in JSON-REST. Again, I dont really understand this comment nor what the servlet does even reading it. Servlet code below:
package com.google.api.server.spi;
import com.google.api.server.spi.SystemService.EndpointNode;
import com.google.api.server.spi.config.ApiConfigException;
import com.google.api.server.spi.config.model.ApiClassConfig.MethodConfigMap;
import com.google.api.server.spi.config.model.ApiConfig;
import com.google.api.server.spi.config.model.ApiMethodConfig;
import com.google.api.server.spi.dispatcher.PathDispatcher;
import com.google.api.server.spi.handlers.ApiProxyHandler;
import com.google.api.server.spi.handlers.CorsHandler;
import com.google.api.server.spi.handlers.EndpointsMethodHandler;
import com.google.api.server.spi.handlers.ExplorerHandler;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map.Entry;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A handler for proxy-less API serving. This servlet understands and replies in JSON-REST.
*/
public class EndpointsServlet extends HttpServlet {
private static final String EXPLORER_PATH = "explorer";
private ServletInitializationParameters initParameters;
private SystemService systemService;
private PathDispatcher<EndpointsContext> dispatcher;
private CorsHandler corsHandler;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ClassLoader classLoader = getClass().getClassLoader();
this.initParameters = ServletInitializationParameters.fromServletConfig(config, classLoader);
this.systemService = createSystemService(classLoader, initParameters);
this.dispatcher = createDispatcher();
this.corsHandler = new CorsHandler();
}
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String method = getRequestMethod(request);
if ("OPTIONS".equals(method)) {
corsHandler.handle(request, response);
} else {
String path = Strings.stripSlash(
request.getRequestURI().substring(request.getServletPath().length()));
EndpointsContext context = new EndpointsContext(method, path, request, response,
initParameters.isPrettyPrintEnabled());
if (!dispatcher.dispatch(method, path, context)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().append("Not Found");
}
}
}
private String getRequestMethod(HttpServletRequest request) {
Enumeration headerNames = request.getHeaderNames();
String methodOverride = null;
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
if (headerName.toLowerCase().equals("x-http-method-override")) {
methodOverride = request.getHeader(headerName);
break;
}
}
return methodOverride != null ? methodOverride.toUpperCase() : request.getMethod();
}
private PathDispatcher<EndpointsContext> createDispatcher() {
PathDispatcher.Builder<EndpointsContext> builder = PathDispatcher.builder();
List<EndpointNode> endpoints = systemService.getEndpoints();
// We're building an ImmutableList here, because it will eventually be used for JSON-RPC.
ImmutableList.Builder<EndpointsMethodHandler> handlersBuilder = ImmutableList.builder();
for (EndpointNode endpoint : endpoints) {
ApiConfig apiConfig = endpoint.getConfig();
MethodConfigMap methods = apiConfig.getApiClassConfig().getMethods();
for (Entry<EndpointMethod, ApiMethodConfig> methodEntry : methods.entrySet()) {
if (!methodEntry.getValue().isIgnored()) {
handlersBuilder.add(
new EndpointsMethodHandler(initParameters, getServletContext(), methodEntry.getKey(),
apiConfig, methodEntry.getValue(), systemService));
}
}
}
ImmutableList<EndpointsMethodHandler> handlers = handlersBuilder.build();
for (EndpointsMethodHandler handler : handlers) {
builder.add(handler.getRestMethod(), Strings.stripTrailingSlash(handler.getRestPath()),
handler.getRestHandler());
}
ExplorerHandler explorerHandler = new ExplorerHandler();
builder.add("GET", EXPLORER_PATH, explorerHandler);
builder.add("GET", EXPLORER_PATH + "/", explorerHandler);
builder.add("GET", "static/proxy.html", new ApiProxyHandler());
return builder.build();
}
private SystemService createSystemService(ClassLoader classLoader,
ServletInitializationParameters initParameters) throws ServletException {
try {
SystemService.Builder builder = SystemService.builder()
.withDefaults(classLoader)
.setStandardConfigLoader(classLoader)
.setIllegalArgumentIsBackendError(initParameters.isIllegalArgumentBackendError())
.setDiscoveryServiceEnabled(true);
for (Class<?> serviceClass : initParameters.getServiceClasses()) {
builder.addService(serviceClass, createService(serviceClass));
}
return builder.build();
} catch (ApiConfigException | ClassNotFoundException e) {
throw new ServletException(e);
}
}
/**
* Creates a new instance of the specified service class.
*
* #param serviceClass the class of the service to create
*/
protected <T> T createService(Class<T> serviceClass) {
try {
return serviceClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(
String.format("Cannot instantiate service class: %s", serviceClass.getName()), e);
} catch (IllegalAccessException e) {
throw new RuntimeException(
String.format("Cannot access service class: %s", serviceClass.getName()), e);
}
}
}
EndpointsServlet handles all API calls with a certain path prefix. It takes a RESTful API call and translates it into POJO(s) and dispatches it to a Java method you've written, and then serializes the return value of that method to JSON. It does this based on how you annotate your code.
I have created a MDB bean and deployed in glassfish 4 and application got deployed successfully, but i am trying to put message in the queue using a standalone client. And i am getting this error.
**java.lang.NullPointerException
at com.sun.enterprise.naming.impl.SerialContext.getORB(SerialContext.java:347)
javax.naming.NamingException: Lookup failed for 'jms/myQueue' in SerialContext[myEnv={java.naming.provider.url=iiop://localhost:3700, java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext[myEnv={java.naming.provider.url=iiop://localhost:3700, java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is java.lang.NullPointerException]]
Caused by: javax.naming.NamingException: Unable to acquire SerialContextProvider for SerialContext[myEnv={java.naming.provider.url=iiop://localhost:3700, java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is java.lang.NullPointerException]**
MDB class code is::
package test;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
#MessageDriven(activationConfig = {
#ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/myQueue")
,
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
,
#ActivationConfigProperty(propertyName = "connectionFactoryLookup", propertyValue = "jms/myConnectionFactory")
})
public class testMDB1 implements MessageListener {
public testMDB1() {
}
#Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage t = (TextMessage) message;
try {
System.out.println("ye le " + t.getText());
} catch (JMSException ex) {
Logger.getLogger(TestMDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
and the client file is
package test;
import java.util.Properties;
import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.JMSProducer;
import javax.jms.Queue;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TestClient {
public static void main(String[] args) {
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
env.put(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
env.put(Context.PROVIDER_URL, "iiop://localhost:3700");
Context remoteContext = new InitialContext(env);
System.out.println("remote context" + remoteContext.getEnvironment());
Queue queue = (Queue) remoteContext.lookup("jms/myQueue");
JMSContext jmsContext = ((ConnectionFactory) remoteContext.lookup("jms/myConnectionFactory")).createContext();
JMSProducer producer = jmsContext.createProducer();
producer.send(queue, "hello ");
System.out.println("1. Sent TextMessage to the Queue");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
I have added gf-client.jar,orb-iiop.jar and appserv-rt.jar but nothing is solving my problem.
I came to know that glassfish 4.1 is having this bug where local client cant connect to the MDB. I tried the same with two ejb projects and it is working just fine.
In AEM, I'm trying to write a JSON object that contains a string object via a get servlet, like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObject.toString());
Response being of type SlingHttpServletResponse
When the servlet is accessed in a browser the is stripped with a warning coming out of the aem log:
03.08.2015 16:55:27.359 *WARN* [127.0.0.1 [1438617327343] GET /bin/integration.json HTTP/1.1] com.day.cq.rewriter.linkchecker.impl.LinkCheckerImpl Ignoring malformed URI: java.net.URISyntaxException: Illegal character in path at index 0: \
Link checker is bypassed for a lot of patterns including the link above.
For example the string object inside the json:
pageIntro:'this link doesn't work'
becomes:
pageIntro:'this link</a> doesn't work'
Any help would be much appreciated.
Cheers,
Alex
By doing a quick fiddle around AEM 6.0 , I am not able to reproduce this issue .
Following is what I did in the servlet. Attaching the snippet below. Is there anything else you are doing to achieve this ?
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#SlingServlet( label = "Stack Overflow - Sabya Test Servlet",
description = "Used for quick fiddle",
paths="/bin/sabya-servlet.json",
metatype = true
)
public class SabyaTestServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1335893917596088016L;
private static final Logger log = LoggerFactory
.getLogger(SabyaTestServlet.class);
#Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
log.trace("Sabya Test Servlet : doGet() starts .. ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("pageIntro", "this <a href='http://www.domain.com/my-section/page.html'>link</a> doesn't work");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObject.toString());
} catch (JSONException e) {
log.error("Something ridiculous has happened !! {}" , e);
}
log.trace("Sabya Test Servlet : doGet() ends .. ");
}
}
Request URL : http://localhost:4502/bin/sabya-servlet.json
Response :
{
pageIntro: "this <a href='http://www.domain.com/my-section/page.html'>link</a> doesn't work"
}
Note : I believe you are using org.apache.sling.commons.json.JSONObject .
I am wanting to use htmlunit to scrape data from a website. I am passing the address as an attribute from a form. I keep getting errors, it says the "java.lang.NoClassDefFoundError: com/gargoylesoftware/htmlunit/WebClient" even though I have the .jar files imported and the javadoc file location set correctly. Am I missing something?
package coreservlets;
import java.io.IOException;
import java.io.PrintWriter;
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 com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
#WebServlet("/WebScrape")
#SuppressWarnings("serial")
public class WebScrape extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// Create and initialize WebClient object
final WebClient webClient = new WebClient();
String Address = (String) request.getAttribute("address");
HtmlPage page = webClient.getPage(Address);
final HtmlDivision div = (HtmlDivision) page.getByXPath("//*[#id=\"LDPOffMarketPropertyInfo\"]//div//ul//li[4]//span[1]//text()");
out.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta name=" + "\"viewport\" " + "content=" + "\"initial-scale=1.0, user-scalable=no\" " + "/>\n" +
"<style type=" + "\"text/css\">\n" +
" html { height: 100% }\n" +
" body { height: 100%; margin: 0; padding: 0 }\n" +
" #default { height: 800px;\n"+
" width: 400px; }\n" +
" </style>\n" + div);
}
}
Assuming you use Eclipse, the build path is just that: the set of libraries used to build the application.
You also need the libraries to be available at runtime, inside your webapp. The servlet specification explains where the libraries of a webapp must go: in WEB-INF/lib.
Remove the jar files from the build path, and drop them in the folder WEB-INF/lib of your WebContent directory. This will automatically add them back to the build path, and also make them part of the deployed application, and thus available at runtime.
They will also appear under the Web App libraries node in the package explorer of Eclipse, confirming that these libraries are part of the webapp.
I am using the below code to upload a file in to tomcat5.5 and it gives me the following exception
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
could you please help me to find it out?
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("Status : "+isMultipart);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("upload.jsp");
}
}
this is the jar i use commons-fileupload-1.2.2.jar
The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.
And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.
See also:
How to upload files to server using JSP/Servlet?
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
How do I import the javax.servlet API in my Eclipse project?
use maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
or download commons-io.1.3.2.jar to your lib folder
Solution
By default, Struts is using Apache “commons-io.jar” for its file upload process. To fix it, you have to include this library into your project dependency library folder.
Get Directly
Get “commons-io.jar” from official website – http://commons.apache.org/io/
Get From Maven
The prefer way is get the “commons-io.jar” from Maven repository
File : pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
just put all apache comons jar and file upload jar in lib folder of tomcat
If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.
You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt
Now, Next add this downloaded files into your project:
Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93