Getting started with embedded Jetty - jetty

I just got started with embedded jetty. I'm stuck at some error messages. It's simple and straightforward few lines code, which I found online and wanted to test out.
import org.jaxen.Context;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHolder;
public class Main {
public static void main(String[] args) throws Exception {
ServletHolder sh = new ServletHolder(ServletContainer.class);
sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
sh.setInitParameter("com.sun.jersey.config.property.packages", "jerseyplusjetty");
Server server = new Server(80);
ServletContextHandler sch = new ServletContextHandler(server, "/");
sch.addServlet(sh, "/*");
server.start();
server.join();
}
}
I have all jetty jars in java build path. But I kept getting errors: The constructor ServletHolder(Class) is undefined, The constructor Server(int) is undefined, ServletContextHandler cannot be resolved to a type.
If I remove the parameter inside ServletHolder and Server, it stops complaining. e.g. if I have: ServletHolder sh = new ServletHolder(); Server server = new Server();
But that's not right. I read Jetty docs and ServletHolder class can take parameters. Am I missing something here?

Just FYI on embedded Jetty in general... I have created a github project that I humbly submit may cover most of the embedded jetty issues that keep cropping up.
I've got examples for AbstractHandlers, Servlets, Jersey Servlets, static files, webapps and what not. Still working on RoR and Sinatra, but will get there.
See https://github.com/ZenGirl/EmbeddedJettyRepository for details.
Anyone want to contribute, just ask.

The version of ServletHolder I have takes a String or a servlet in the constructor. So instead of doing
new ServletHolder(ServletContainer.class) you should do new ServletHolder(ServletContainer.class.getCanonicalName()) or new ServletHolder(new ServletContainer()).
ServletContainer is a strange name for a servlet, make sure it is actually a servlet.
Also, be aware that there are number of different versions of Jetty (you're using an old one because in the new one all the classes are in org.eclipse.jetty package), and it's easy to pick up example code that refers to a different version to the one you've got. I would get jetty 7.2.2 from maven and use the example code here.

Related

is there any replacement class of WebSocketServerFactory in jetty 10?

Jetty 9 has WebSocketServerFactory class but in jetty 10 there is no such class present.
What is the alternative way without using WebSocketServerFactory?
Below factory class created in jetty 9. Now I want to upgrade to jetty 10 but facing difficulties. any suggestions please!!
public class UpgradeSocketServerFactory extends WebSocketServerFactory
{
private static final Executor executor = CustomExecutors.newFabricCachedThreadPool(10, "jetty-threads");
private static final ByteBufferPool bufferPool = new ArrayByteBufferPool(0, 0, 64*1024);
public UpgradeSocketServerFactory(WebSocketPolicy policy)
{
super(policy, executor, bufferPool);
}
#Override
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
{
return new sendCustomObject();
}
}
Note: UpgradeSocketServerFactory Contractor calling from other class.
Since your question was unclear about the struggles you are having, I'll just assume it's the createWebSocket() method. If this is not the case, use the Question section at the official issue tracker to have a conversation about your struggles (stackoverflow is for narrow focused and specific development questions)
https://github.com/eclipse/jetty.project/issues/new/choose
The WebSocketCreator is still there, that's how you should be using the WebSocketServletFactory and/or WebSocketServerFactory.
Steps to take:
change your Jetty 9 code to NOT extend from WebSocketServerFactory
use WebSocketCreator instead to create a custom websocket instance of your endpoint
register your WebSocketCreator by mapping it to a URL pathSpec.
Use the NativeWebSocketServerContainerInitializer.configure() in your embedded code to do that.
See: https://github.com/jetty-project/embedded-jetty-websocket-examples/blob/9.4.x/native-jetty-websocket-example/src/main/java/org/eclipse/jetty/demo/EventServer.java
Jetty 9 technique
// Setup the basic application "context" for this application at "/"
// This is also known as the handler tree (in jetty speak)
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// Configure specific websocket behavior
NativeWebSocketServletContainerInitializer.configure(context,
(servletContext, nativeWebSocketConfiguration) ->
{
// Configure default max size
nativeWebSocketConfiguration.getPolicy().setMaxTextMessageBufferSize(65535);
// Add websockets
nativeWebSocketConfiguration.addMapping("/events/*", new EventEndpointCreator());
});
// Add generic filter that will accept WebSocket upgrade.
WebSocketUpgradeFilter.configure(context);
Now, time to upgrade to Jetty 10/11.
Change name of WebSocketCreator to JettyWebSocketCreator
You'll use JettyWebSocketServletContainerInitializer.configure() instead.
See: https://github.com/jetty-project/embedded-jetty-websocket-examples/blob/11.0.x/native-jetty-websocket-example/src/main/java/org/eclipse/jetty/demo/EventServer.java
Jetty 11 technique
// Setup the basic application "context" for this application at "/"
// This is also known as the handler tree (in jetty speak)
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// Configure specific websocket behavior
JettyWebSocketServletContainerInitializer.configure(context, (servletContext, wsContainer) ->
{
// Configure default max size
wsContainer.setMaxTextMessageSize(65535);
// Add websockets
wsContainer.addMapping("/events/*", new EventEndpointCreator());
});

Inject Jar and replace classes in running JVM

I want to be able to replace and add some classes to an already running JVM. I read that I need to use CreateRemoteThread, but I don't completely get it. I read this post on how to do it (Software RnD), but I can't figure out what it does and why. Besides that, it only introduces new classes, but doesn't change existing ones. How can I do it with C++?
You don't even need CreateRemoteThread - there is an official way to connect to remote JVM and replace loaded classes by using Attach API.
You need a Java Agent that calls Instrumentation.redefineClasses.
public static void agentmain(String args, Instrumentation instr) throws Exception {
Class oldClass = Class.forName("org.pkg.MyClass");
Path newFile = Paths.get("/path/to/MyClass.class");
byte[] newData = Files.readAllBytes(newFile);
instr.redefineClasses(new ClassDefinition(oldClass, newData));
}
You'll have to add MANIFEST.MF with Agent-Class attribute and pack the agent into a jar file.
Then use Dynamic Attach to inject the agent jar into the running VM (with process ID = pid).
import com.sun.tools.attach.VirtualMachine;
...
VirtualMachine vm = VirtualMachine.attach(pid);
try {
vm.loadAgent(agentJarPath, options);
} finally {
vm.detach();
}
A bit more details in the article.
If you insist on using C/C++ instead of Java API, you may look at my jattach utility.

Use wsse security header in soap message (Visual Studio 2015, .Net Framework 4.5)

I would like to consume a Soap Service provided by DHL. You can find the wsdl here: https://wsbexpress.dhl.com/sndpt/expressRateBook?WSDL
Therefore I created a new ClassLibrary in Visual Studio 2015 targeting .net framework 4.5.
Then I added a Web Reference to the created project by providing the wsdl address. I generated a proxy file with all types and ports in it but my first problem is, that the generated Service extends from System.Web.Services.Protocols.SoapHttpClientProtocol. As I read in recent posts it is not possible to get the wsse header to that proxy. Some posts advise to add wse but it seems wse is not supported by newer Visual Studio versions.
I tried to generate my proxy by svcutil. After that I added the generated .cs file to the project and copied the content of the generated config file to app.config. (of cause I removed the web reference)
Now the Service class extends System.ServiceModel.ClientBase. (I thought the generator in VS uses svctool internally. If microsoft want people to use wcf why does the generator generate non-wcf proxy files.
I also created a nunit testproject which should test my service, but If I use the version with the svcutil generated version I get an error. I try to translate it to english as the error is displayed in german:
Could not find a default endpoint element which points to the service contract. As I figured out this is because the proxy is in its own class library and therefor doesn't really have an app.config. But my test project is a class library too.
What would be the actual way to consume a web service which needs ws security Username/Password auth these days?
You can add the Web Reference in compatibility mode (I am guessing you are doing so). If you are not adding the reference in compatibility mode, do the following:
Right click on references Add Service Reference-> Advanced -> Add Web Reference (Below the compatibility section), type the URL of the WS and add the reference.
The WSE2.0 extensions are available as a Nuget Package at:
https://www.nuget.org/packages/Microsoft.Web.Services2/
Install the nuget package on the package manager console running the following nugget command:
Install-Package Microsoft.Web.Services2
After you installed the nuget package, you need to make sure your project is referencing the following DLL's:
System.Web
System.Web.Services
Microsoft.Web.Services2 (This will be added after you install the nuget package)
In order to use the WSE2.0 extensions, you need to actually modify the Proxy class that was created when you added the WebReference to inherit from "Microsoft.Web.Services2.WebServicesClientProtocol" instead of "System.Web.Services.Protocols.SoapHttpClientProtocol". Be aware that if you update the WebReference, the Proxy class will inherit againfrom SoapHttpClientProtocol.
Add the following using clauses to the code consuming the Proxy class:
using Microsoft.Web.Services2;
using Microsoft.Web.Services2.Security;
using Microsoft.Web.Services2.Security.Tokens;
After you make this changes, you code should look something like this:
var token = new UsernameToken("theUser", "thePassword", PasswordOption.SendHashed);
var serviceProxy = new ExpressRateBook.gblExpressRateBook();
SoapContext requestContext = serviceProxy.RequestSoapContext;
requestContext.Security.Timestamp.TtlInSeconds = 60;
requestContext.Security.Tokens.Add(token);
//The rest of the logic goes here...
I added the screenshot down below for your reference:
NOTE: I was unable to test the code since I am unfamiliar with the actual methods that you need to consume, the code displayed is just an example of what I saw in the proxy class, update it according to your needs. It should work fine if you follow the steps described before. Check the following link for more detailed instructions:
https://msdn.microsoft.com/en-us/library/ms819938.aspx
You can configure you Service Reference to add the Security Header as AW Rowse describes at http://cxdeveloper.com/article/implementing-ws-security-digest-password-nonce-net-40-wcf:
private void Configure()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
defaultBinding = new BasicHttpBinding
{
Security =
{
Mode = BasicHttpSecurityMode.Transport,
Transport =
{
ClientCredentialType = HttpClientCredentialType.Digest
}
}
};
defaultToken = new UsernameToken(UserName, Password, PasswordOption.SendHashed);
defaultSecurityHeader = MessageHeader.CreateHeader(
"Security",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
defaultToken.GetXml(new XmlDocument())
);
}
And create you client/proxy like this:
public consulta_informacao_respttClient CriaConsultaClinicaClient()
{
var client = new consulta_informacao_respttClient(defaultBinding, new EndpointAddress("https://resqa.homologacao.unimed.coop.br/chs-integration-external-services-ptu-clinical/proxy-services/execute-query/execute-query-proxy-service"));
client.ClientCredentials.UserName.UserName = UserName;
client.ClientCredentials.UserName.Password = Password;
var scope = new OperationContextScope(client.InnerChannel);
OperationContext.Current.OutgoingMessageHeaders.Add(defaultSecurityHeader);
return client;
}
The properties you will need to create in your class are:
private BasicHttpBinding defaultBinding;
private UsernameToken defaultToken;
private MessageHeader defaultSecurityHeader;
You won't need to configure anything in app/web.config.

Apply HTTP basic authentication to jax ws (HttpSpiContextHandler) in embedded Jetty

There are some similar questions for earlier versions of Jetty (pre 9) but none that address this specific problem :
Server server = new Server();
System.setProperty("com.sun.net.httpserver.HttpServerProvider",
JettyHttpServerProvider.class.getName());
JettyHttpServer jettyServer = new JettyHttpServer(server, true);
Endpoint endpoint = Endpoint.create(new SOAPService()); // this class to handle all ws requests
endpoint.publish(jettyServer.createContext("/service")); // access by path
server.start()
Simplified code example above to show the only way that I have found to bridge between Jetty and incoming soap requests to my jax-ws service. All settings are in code with no web.xml, this is part of a larger solution that has multiple contexts and connections for different purposes (servlets etc..)
I have tried to add a handler class to the jettyServer.createContext("/service",new handler()) to see if I can perform a header extraction to simulate basic auth but it never gets executed.
My problem is that i cannot find a way to specify, by code against the Jetty server, to use basic authentication. Using the setSecurityHandler method of a ServletContextHandler is easy and works great for other contexts, i just can't figure out how to use this concept for the jax-ws service.
Any help would be much appreciated.
p.s. SSL is already implemented, I just need to add http basic auth.
For anyone else that may of come across the same problem here is the answer that i stumbled on eventually.
final HttpContext httpContext = jettyServer.createContext("/service");
com.sun.net.httpserver.BasicAuthenticator a = new com.sun.net.httpserver.BasicAuthenticator("") {
public boolean checkCredentials (String username, String pw)
{
return username.equals("username") && pw.equals("password");
}
};
httpContext.setAuthenticator(a);
endpoint.publish(httpContext);//access by path
You can expand the checkCredentials for something a bit more sophisticated of course, but this shows the basic working method.

Embed jetty in java app and export as jar

I'm making a java application which embeds a Jetty web server, which in turn serves content developed with Google Web Toolkit. It's all working fine when run in Eclipse, but when I export it as a jar file all I get is a Jetty error message saying "File not found".
The Jetty server is launched like this:
WebAppContext handler = new WebAppContext();
handler.setResourceBase("./war");
handler.setDescriptor("./war/WEB-INF/web.xml");
handler.setContextPath("/");
handler.setParentLoaderPriority(true);
server.setHandler(handler);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I suspect that the problem is the relative paths used in handler.setResourceBase() and handler.setDescriptor(). I've googled and tested lots of solutions to this but so far to no avail. Particularly I've tried using something like getClass().getResource("./war").toExternalForm() but this just throws Null exceptions.
I also tried:
ProtectionDomain protectionDomain = Start.class.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
but that only results in a Jetty serving a directory listing of the java classes.
Is there any way to do this?
Copy all files of the compiled GWT application into one of your Java packages. For instance:
my.webapp.resources
html/MyPage.html
gwtmodule/gwtmodule.nocache.js
...
(html, gwtmodule will become Java packages as well).
Configure the embedded Jetty instance to serve these files.
final String webDir = this.getClass().
getClassLoader().getResource("my/webapp/resources").toExternalForm();
final Context root = new Context(server, "/", Context.SESSIONS);
root.setContextPath("/");
root.setResourceBase(webDir);
root.addServlet(MyGwtService.class, "/servlets/v01/gwtservice");
This approach works for me both when the application is run from eclipse as well as when it is deployed.
I've posted a detailed description on how to do this here:
http://h30499.www3.hp.com/t5/HP-Software-Developers-Blog/Embedding-Jetty-in-a-Java-Main-Application/ba-p/6107503
It looks like ClassLoader.getResource does not understand an empty string or . or / as an argument. In my jar file I had to move all stuf to WEB-INF. So the code looks like
`contextHandler.setResourceBase(EmbeddedJetty.class.getClassLoader().getResource("WEB-INF").toExternalForm());`
so the context looks like this then:
ContextHandler:744 - Started o.e.j.w.WebAppContext#48b3806{/,jar:file:/Users/xxx/projects/dropbox/ui/target/ui-1.0-SNAPSHOT.jar!/WEB-INF,AVAILABLE}