I run the following simple example for a Jersey application on a Grizzly server:
#Path("example")
public class example {
#POST
public Response someMethod(#Context Request r) {
System.out.println("Received request at : " + LocalDateTime.now());
Response response = Response.ok().build();
return response;
}
}
public class GrizzlyServerMain {
public static HttpServer startServer(String BASE_URI) throws IOException {
// Scans for JAX-RS resources and providers in the specified code-package
final ResourceConfig resourceConfig = new PackagesResourceConfig("Application");
// create and start a new instance of grizzly http server exposing the Jersey application at BASE_URI
return GrizzlyServerFactory.createHttpServer(BASE_URI, resourceConfig);
}
public static void main(String[] args) throws IOException {
String BASE_URI = "http://0.0.0.0:8000";
// Base URI the Grizzly HTTP server will listen on
startServer(BASE_URI);
//noinspection ResultOfMethodCallIgnored
System.in.read();
}
}
When I run it from IntelliJ, everything works as expected.
Connected to the target VM, address: '127.0.0.1:61163', transport:
'socket' Dec 30, 2016 4:00:07 PM
com.sun.jersey.api.core.PackagesResourceConfig init INFO: Scanning for
root resource and provider classes in the packages: Application Dec
30, 2016 4:00:08 PM com.sun.jersey.api.core.ScanningResourceConfig
logClasses INFO: Root resource classes found: class
Application.Greetings class Application.example Dec 30, 2016 4:00:08
PM com.sun.jersey.api.core.ScanningResourceConfig init INFO: No
provider classes found. Dec 30, 2016 4:00:08 PM
com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19.3
10/24/2016 03:43 PM' Dec 30, 2016 4:00:08 PM
org.glassfish.grizzly.http.server.NetworkListener start INFO: Started
listener bound to [0.0.0.0:8000] Dec 30, 2016 4:00:08 PM
org.glassfish.grizzly.http.server.HttpServer start INFO: [HttpServer]
Started
Received request at : 2016-12-30T16:00:13.097
Received request at : 2016-12-30T16:00:14.319
Received request at : 2016-12-30T16:00:15.583
Disconnected from the target VM, address:
'127.0.0.1:61163', transport: 'socket'
But when I create a JAR with all the dependencies, and as soon as I send the request from the client, I get:
WARNING: Exception during FilterChain execution
java.lang.IllegalStateException
at org.glassfish.grizzly.http.server.io.OutputBuffer.reset(OutputBuffer.java:217)
at org.glassfish.grizzly.http.server.Response.reset(Response.java:732)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:168)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:265)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:134)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:78)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:815)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:567)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:547)
at java.lang.Thread.run(Unknown Source)
Can you please tell me what could I be doing wrong?
The exception seems to have changed from IllegalStateException to IllegalArgumentException.
Have a look at Java Doc for ContainerProvider.
ContainerProvider is an SPI class and its implementation will be provided by the server you are using, in your case the Grizzly server.
As per Java Doc:
An implementation (a service-provider) identifies itself by placing a provider-configuration file (if not already present), "com.sun.jersey.spi.container.ContainerProvider" in the resource directory META-INF/services, and including the fully qualified service-provider-class of the implementation in the file..
So, I think you need to update "META-INF/services" to your jar and add the provider as "GrizzlyContainerProvider" (package qualified).
You can have a look at a similar post:
Grizzly and Jersey standalone jar
Related
I am using httpclient-3.0 library to parse data to cloud. When I run the application on my local machine (Windows 10), it works fine and the data gets parsed to the server and I receive success response, but when I deployed it on our server which runs on Windows server 2012 R2, it throws below error. I have used the same JDK as well I tried many ways like adding -Djdk.tls.client.protocols="TLSv1,TLSv1.1,TLSv1.2" in my java.security jdk file, but still the issue is not resolved.
Here is my code
PostMethod post = new PostMethod(apiUrl);
post.setParameter("authtoken", authToken);
post.setParameter("dateFormat", dateTimeFormat);
post.setParameter("data", emloyeesAttendanceJsonArr.toString());
HttpClient httpclient = new HttpClient();
// Configuring proxy
httpclient.getHostConfiguration().setProxy("**.**.**.**", ****);
try {
long timeTrace = System.currentTimeMillis();
int result = httpclient.executeMethod(post);
System.out.println(">> HTTP Response status code: "+result);
System.out.println(">> Response Time: "+(System.currentTimeMillis() - timeTrace));
.......
.......
.......
}
I appreciate any quick help and guidelines.
Here is the error I get
Mar 11, 2020 4:23:08 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: I/O exception (javax.net.ssl.SSLProtocolException) caught when processing
request: Connection reset
Mar 11, 2020 4:23:08 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: Retrying request
Mar 11, 2020 4:23:23 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: I/O exception (javax.net.ssl.SSLProtocolException) caught when processing
request: Connection reset
Mar 11, 2020 4:23:23 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: Retrying request
Mar 11, 2020 4:23:38 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: I/O exception (javax.net.ssl.SSLProtocolException) caught when processing
request: Connection reset
Mar 11, 2020 4:23:38 PM org.apache.commons.httpclient.HttpMethodDirector execute
WithRetry
INFO: Retrying request
javax.net.ssl.SSLProtocolException: Connection reset
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:126)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.ja
va:321)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.ja
va:264)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.ja
va:259)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:137)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:11
52)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocke
tImpl.java:1063)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl
.java:402)
at java.base/sun.security.ssl.SSLSocketImpl.ensureNegotiated(SSLSocketIm
pl.java:716)
at java.base/sun.security.ssl.SSLSocketImpl$AppOutputStream.write(SSLSoc
ketImpl.java:970)
at java.base/java.io.BufferedOutputStream.flushBuffer(BufferedOutputStre
am.java:81)
at java.base/java.io.BufferedOutputStream.flush(BufferedOutputStream.jav
a:142)
at java.base/java.io.FilterOutputStream.flush(FilterOutputStream.java:15
3)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequ
estBody(EntityEnclosingMethod.java:502)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodB
ase.java:1973)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.j
ava:993)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(Htt
pMethodDirector.java:397)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMe
thodDirector.java:170)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.jav
a:396)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.jav
a:324)
at af.aib.etl.AttendanceETL.fetchAndParseAttendanceRecord(AttendanceETL.
java:99)
at af.aib.attendance.ApplicationStartPoint.main(ApplicationStartPoint.ja
va:28)
Caused by: java.net.SocketException: Connection reset
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRe
cord.java:448)
at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInput
Record.java:165)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:108)
The local proxy and the server proxy were different that is why it was running fine on my local machine but not on the server, once I changed the proxy to the specific proxy which server was using then the application was working fine.
I want consum a rest service in http://localhost:8080/ with apache-camel using jetty. But this code not produce any request to the API. I am beginner in apache-camel and I want use to orchestation of differents microservices.
Code:
package example;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class ejemplo {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
context.setTracing(true);
context.addRoutes(new RouteBuilder(){
#Override
public void configure() throws Exception {
from("direct:start")
.log("Http Route started")
.setHeader(Exchange.HTTP_METHOD,simple("GET"))
.setHeader(Exchange.CONTENT_TYPE,simple("application/json"))
.to("jetty:http://0.0.0.0:8080/")
.process(new Processor(){
public void process(Exchange exchange) throws Exception {
System.out.println("I am a process....");
String msg = exchange.getIn().getBody().toString();
System.out.println(msg);
}
});
}
});
context.start();
}
}
Log:
sep 24, 2019 7:57:05 PM org.apache.camel.impl.DefaultCamelContext start
INFORMACIÓN: Apache Camel 2.17.1 (CamelContext: camel-1) is starting
sep 24, 2019 7:57:05 PM org.apache.camel.impl.DefaultCamelContext doStartCamel
INFORMACIÓN: Tracing is enabled on CamelContext: camel-1
sep 24, 2019 7:57:05 PM org.apache.camel.management.ManagedManagementStrategy doStart
INFORMACIÓN: JMX is enabled
sep 24, 2019 7:57:05 PM org.apache.camel.impl.converter.DefaultTypeConverter doStart
INFORMACIÓN: Loaded 208 type converters
sep 24, 2019 7:57:05 PM org.apache.camel.impl.DefaultRuntimeEndpointRegistry doStart
INFORMACIÓN: Runtime endpoint registry is in extended mode gathering usage statistics of all incoming and outgoing endpoints (cache limit: 1000)
sep 24, 2019 7:57:05 PM org.apache.camel.impl.DefaultCamelContext doStartCamel
INFORMACIÓN: AllowUseOriginalMessage is enabled. If access to the original message is not needed, then its recommended to turn this option off as it may improve performance.
sep 24, 2019 7:57:05 PM org.apache.camel.impl.DefaultCamelContext doStartCamel
INFORMACIÓN: StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
sep 24, 2019 7:57:05 PM org.eclipse.jetty.util.log.Log initialized
INFORMACIÓN: Logging initialized #1372ms
sep 24, 2019 7:57:06 PM org.apache.camel.impl.DefaultCamelContext doStartOrResumeRouteConsumers
INFORMACIÓN: Route: route1 started and consuming from: Endpoint[direct://httpRouter]
sep 24, 2019 7:57:06 PM org.apache.camel.impl.DefaultCamelContext start
INFORMACIÓN: Total 1 routes, of which 1 are started.
sep 24, 2019 7:57:06 PM org.apache.camel.impl.DefaultCamelContext start
INFORMACIÓN: Apache Camel 2.17.1 (CamelContext: camel-1) started in 1.466 seconds
This output not produces any response of the API in localhost:8080 but I think that the route is correct. I would want know if there are other ways of consume a rest service of a API REST using apache-camel.
Note that start is just a name and direct component allows you to invoke your route synchronously from other route, it seems like you are not doing just that
To check if the route is correct replace direct in your from endpoint to timer, e.g. from("timer://foo?fixedRate=true&period=10000"), for more details see camel docs
TLDR: Do I have to use different syntax to access my servlet if I am using Tomcat instead of Glassfish or jkd 1.7 instead of jdk 1.8? I can't get my jquery ajax to communicate with my servlet (in eclipse 1.7 jdk tomcat instead of netbeans 1.8 jdk glassfish)
I am trying to convert my project from Netbeans 1.8 JDK to Eclipse 1.7 JKD.
It worked fine in Netbeans. I have spent over 5 hours trying to get it to function on Eclipse now.
I think the problem is that it is not mapping my ajax "search" to the servlet "/search" .
The servlet is annotated
#WebServlet(name = "SearchServlet", urlPatterns = {"/search"})
I have to assume this works with JDK 1.7.....?
I had trouble adding a glassfish server the same as my netbeans. I managed to add it but then it vanished and I had no server available whatsoever until I gave up and put in a tomcat one. However I don't know if you're supposed to configure this any further.
I try to add glassfish server tools by dragging it into my IDE but it says Nothing to update: nothing to update. So I'm just sticking with tomcat.
Here is the log when I run my jsp:
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:animelist1' did not find a matching property.
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Mar 23 2015 14:11:21 UTC
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.21.0
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jdk1.7.0_79\jre
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.7.0_79-b15
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\apache-tomcat-8.0.21\endorsed
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_79\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin;.
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 772 ms
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.21
Apr 20, 2015 1:48:49 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:49 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1162 ms
Here is the log when I try to make a search by clicking the button on the jsp:
Apr 20, 2015 1:50:11 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet SearchServlet as unavailable
Apr 20, 2015 1:50:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet SearchServlet
javax.naming.NameNotFoundException: Name [main.SearchServlet/annj] is not bound in this Context. Unable to find [main.SearchServlet].
at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:573)
at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:461)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:144)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:121)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:817)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Further searches after the first give this:
POST http://localhost:8080/animelist1/search 404 (Not Found)jQuery.ajaxTransport.send # jquery-1.10.2.js:8706jQuery.extend.ajax # jquery-1.10.2.js:8136(anonymous function) # basic.js:8jQuery.event.dispatch # jquery-1.10.2.js:5095jQuery.event.add.elemData.handle # jquery-1.10.2.js:4766
I had to change my Environment variables to downgrade to JDK 1.7. I have put them below incase they are incorrect and are causing the issues (been messing around with them so much but I think they are right now):
(No added/changed User variables)
System variables:
Path
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin
JAVA_HOME
C:\Program Files\Java\jdk1.7.0_79
I am about to give up and revert to Netbeans 1.8 JDK and upload my web project to somewhere other than Google App Engine (which only works with 1.7). I will give it another hour incase anyone is able to help me but I have spent far too long wasting my time when there is another option.
Like I said I suspect the problem is something to do with my server configuration or some file related to that. Below I will paste my ajax and my servlet. They do both work in netbeans 1.8 jdk but perhaps they need changing for eclipse 1.7 jdk?
Thankyou for reading!
Jquery
$(document).ready(function () {
$('#searchForm').submit(function () {
$.ajax({
url: 'search',
type: 'POST',
dataType: 'text',
data: $('#searchForm').serialize(),
success: function (data) {
$('#displaySearchResults').html(data);
// $('#displaySearchResults').slideDown(500);
//
$("#sortable1").empty();
$.each(JSON.parse(data), function (listID, mapData) {
$("#sortable1").append(
"<li class=userList><div class=selectedItemId id=" + mapData.id + "><img class=selectedItemImg src="
+ mapData.url + " alt=" + mapData.name
+ " style='width:216px;height:300px'></img><div id='animeTitle'>"
+ mapData.name+ "</div></div></li>");
// <ul id="sortable1" class="connectedSortable">
// <li class="ui-state-default">Item 1</li>
// var d1 = mapData.id;
// var d2 = d1.replace("'","");
// var div = document.createElement(d2);
// document.body.appendChild(div);
// $("#"+divName).text(mapData.id);
// $("#displaySearchResults2").text(mapData.name);
// $("#displaySearchResults3").text(mapData.url);
});
}
});
return false;
});
});
Servlet
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.gson.Gson;
import entities.Anime;
import entities.Ann;
import entities.Info;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author J
*/
#WebServlet(name = "SearchServlet", urlPatterns = {"/search"})
public class SearchServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private AnnJAXB annj;
// #EJB
// private AnnJAXB annJAXB = new AnnJAXB();
#EJB
private Ann ann;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SearchServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet SearchServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
// Map <String, Object> map = new HashMap<String, Object>();
String searchQuery = request.getParameter("searchQuery");
// response.getWriter().write(searchQuery);
// map.put("searchQuery", searchQuery);
// returnResults(response, map);
returnResults(response, searchQuery);
}
private void returnResults(HttpServletResponse response, String searchQuery) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
ArrayList<Map> arrayOfMap = new ArrayList<Map>();
try {
for (Anime anime : annj.Unmarshalling(searchQuery).getAnn()) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", anime.getName());
map.put("id", anime.getId());
for (Info temp : anime.getAnime()) {
if (temp.getSrc() != null) {
map.put("url", temp.getSrc());
}
}
arrayOfMap.add(map);
}
response.getWriter().write(new Gson().toJson(arrayOfMap));
} catch (Exception e) {}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
TLDR: Do I have to use different syntax to access my servlet if I am using Tomcat instead of Glassfish or jkd 1.7 instead of jdk 1.8? I can't get my jquery ajax to communicate with my servlet (in eclipse 1.7 jdk tomcat instead of netbeans 1.8 jdk glassfish)
As I know , the notation
#WebServlet(name = "SearchServlet", urlPatterns = {"/search"})
only work in jdk 1.8
but if you still use jdk 1.7, forget the notation and fill web.xml with this map
<servlet>
<servlet-name>search</servlet-name>
<servlet-class>yourPackage.search</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>search</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>
I'm try to pass parameter that contains semicolon(reserved symbol) in REST service, but I have problem with Apache Tomcat
REST services wrote using Apache CXF 2.3
#GET
#Path("/getCmBuildAreas/{productName}/{projectName}/{buildConfiguration}")
#Produces(MediaType.APPLICATION_JSON)
public CmBuildAreas getCmBuildAreas(#PathParam("buildConfiguration") String buildConfiguration, #PathParam("productName") String productName, #PathParam("projectName") String projectName) {
...
}
Then I run query http://localhost:8080/DevManager/services/rest/getCmBuildAreas/QLARIUS/QLARIUS%3AMAINLINE_JAVA_STR/ANT_JAVA_BUILD%3B8 and received this error:
Jul 18, 2011 1:57:53 PM org.apache.cxf.jaxrs.utils.JAXRSUtils findTargetMethod
WARNING: No operation matching request path /DevManager/services/rest/getCmBuildAreas/QLARIUS/QLARIUS%3AAMAINLINE_JAVA_STR/ANT_JAVA_BUILD%3B8 is found, HTTP Method : GET, ContentType : */*, Accept : image/jpeg,application/x-ms-application,image/gif,application/xaml+xml,image/pjpeg,application/x-ms-xbap,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*,.
Jul 18, 2011 1:57:53 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: WebApplicationException has been caught : no cause is available
PS: if you need any additional information, ask.
The fact that Apache CXF 2.3 is not handling correctly encoded semicolons is due to a BUG in that version. It is fixed in versions 2.4, 2.3.4.
this error occurred what to do run the application??
Initializing AppEngine server
25/06/2010 9:16:57 AM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
25/06/2010 9:16:59 AM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed C:\Documents and Settings\kk\workspace\First\war\WEB-INF/appengine-web.xml
25/06/2010 9:16:59 AM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed C:\Documents and Settings\kk\workspace\First\war\WEB-INF/web.xml
25/06/2010 2:47:14 PM com.google.appengine.tools.development.DevAppServerImpl start
INFO: The server is running at http://localhost:8888/
edit (1) ::
when i m running the program http://localhost:8888/first
(copied from a comment to my answer)
i face Error 403 FORBIDDEN what to do now?
in the firstservlet.java i write only the following code
package first;
import java.io.IOException;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
whats the wrong??
403 Forbidden is a HTTP status code returned by a web server when a user agent requests a resource that the server does not allow them to
(wikipedia)
The server is up and running, accepted you request but can't respond because you're not allowed to access some resource. So the problem is inside the Firstapplication, maybe this aplication trys to access some file system resources and the server does not have sufficient privileges.