Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Newcomers » Newcomers » Need help to migrate Jetty 6.1 to Jetty 9.3(Jetty 6.1 Migration with Java 8)
Need help to migrate Jetty 6.1 to Jetty 9.3 [message #1790793] Mon, 18 June 2018 04:37
vibhas karn is currently offline vibhas karnFriend
Messages: 2
Registered: June 2018
Junior Member
Hello All,

I am trying to move our old legacy application which was working on Jetty 6.1 + JDK 1.7 to Jetty 9.3 + JDK 1.8.

In the process I came accross few java classes which I have re-written. I need you suggestion and possible some correction if any in my code.

I have few grey areas which I am not sure of , if they are correct or not which I will highlight in below quries.

Refering to my earlier post in stackoverflow: https://stackoverflow.com/questions/50811623/migrating-jetty-6-1-to-9-3-has-multiple-issue
, I re-write it like this.

Lets start with the old code 1st and then I will post the modified code:

==================================Old Code ===========================


package com.osm.services.webservice;

import java.io.File;
import java.io.FileNotFoundException;

import java.rmi.AlreadyBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.NCSARequestLog;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.handler.RequestLogHandler;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.jetty.security.UserRealm;
import org.mortbay.jetty.webapp.WebAppContext;

import com.osm.config.XmlConfigurable;
import com.osm.services.AbstractService;
import com.osm.services.ServiceControllerConfig;
import com.osm.services.ServiceUtilities;
import com.osm.services.communication.Controller;
import com.osm.services.configuration.ServiceConfiguration;
import com.osm.services.management.JettyServerInfo;
import com.osm.services.utilities.ServiceLock;


public class JettyServer extends AbstractService implements IJettyServer, IStatus {


@Override
public void initialize(final ServiceConfiguration genericConfig, final Controller controller, final int serviceId,
final ServiceLock lock) throws Exception {
if (genericConfig instanceof JettyServerConfiguration) {
configuration = (JettyServerConfiguration) genericConfig;
} else {
configuration = XmlConfigurable.createInstance(JettyServerConfiguration.class,
genericConfig.getXmlConfigElement());
}

server = new Server();
log.info("jetty version = " + Server.getVersion()); //frozen

maxWaitForSlave = getConfiguration().getMaxWaitForSlave();

final boolean debug = getConfiguration().getMortBayDebug();
log.info("mortbay debug = '" + debug + "'"); //frozen
org.mortbay.log.Log.getLog().setDebugEnabled(debug);

// Configure http
final boolean httpEnabled = getConfiguration().getHttpEnabled();

if (httpEnabled) {
// Setup http connector as nio or socket.
final boolean nio = getConfiguration().getNioEnabled();
Connector connector;

if (nio) {
connector = new SelectChannelConnector();
} else {
connector = new SocketConnector();
}

final int mainPort = getConfiguration().getHttpPort();

log.info("adding default connector on port '" + mainPort + "'"); //frozen
connector.setPort(mainPort);

server.addConnector(connector);
}

// Configure SSL
final boolean sslEnabled = getConfiguration().getSslEnabled();

if (sslEnabled) {
final int sslPort = getConfiguration().getSslPort();
final String sslKeyStore = getConfiguration().getSslKeyStore();
final String sslPassword = getConfiguration().getSslPassword();
final String sslKeyPassword = getConfiguration().getSslKeyPassword();
final String sslTrustPassword = getConfiguration().getSslTrustPassword();

//final boolean nio = configuration.getBooleanValue("NioEnabled", false); //frozen
//if(nio) {
//sslConnector = new SslSelectChannelConnector(); available in jetty 7
//} else {
final SslSocketConnector sslConnector = new SslSocketConnector();
sslConnector.setKeystore(sslKeyStore);
sslConnector.setTruststore(sslKeyStore);
sslConnector.setPassword(sslPassword);
sslConnector.setKeyPassword(sslKeyPassword);
sslConnector.setTrustPassword(sslTrustPassword);
sslConnector.setPort(sslPort);
log.info("adding ssl connector on port '" + sslPort + "'"); //frozen
server.addConnector(sslConnector);

//}
}

// Check we had 1 connector else the server is useless
if (server.getConnectors().length == 0) {
throw new FileNotFoundException("No connectors registered. Please see HttpEnable or SslEnable XML tags."); //frozen
}

// Configure the handlers
final HandlerCollection handlers = new HandlerCollection();

for (final WebAppContext webAppContext : getConfiguration().getWebAppContexts()) {
log.info("Adding WebAppContext " + webAppContext.getWar() + " at " + webAppContext.getContextPath()); //frozen
handlers.addHandler(webAppContext);
}

// See http://docs.codehaus.org/display/JETTY/Logging+Requests
final boolean accessLogEnabled = getConfiguration().getLogEnabled();

if (accessLogEnabled) {
final RequestLogHandler requestLogHandler = new RequestLogHandler();
final File logDir = ServiceUtilities.getLogDirectory();

if (!logDir.exists()) {
logDir.mkdirs();
}

final File logFile = new File(getConfiguration().getLogFormat());

if (!logFile.getParentFile().exists()) {
logFile.getParentFile().mkdirs();
}

final NCSARequestLog requestLog = new NCSARequestLog(getConfiguration().getLogFormat());
requestLog.setRetainDays(getConfiguration().getLogRetain());
requestLog.setAppend(getConfiguration().getLogAppend());
requestLog.setExtended(getConfiguration().getLogExtended());
requestLog.setLogTimeZone(getConfiguration().getLogTz());
requestLog.setLogLatency(getConfiguration().getLogLatency());
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
}

handlers.addHandler(new DefaultHandler());

server.setHandler(handlers);

server.setUserRealms(new UserRealm[] { new OSMUserRealm() });

JettyServerInfo.install(server);

super.initialize(configuration, controller, serviceId, lock);
}



}

================ The modified Code / New Code for above class ============================================


package com.osm.services.webservice;

import java.io.File;
import java.io.FileNotFoundException;

import java.rmi.AlreadyBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.WebAppContext;

import org.eclipse.jetty.server.ServerConnector; //import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.SslConnectionFactory;

import com.osm.config.XmlConfigurable;
import com.osm.services.AbstractService;
import com.osm.services.ServiceControllerConfig;
import com.osm.services.ServiceUtilities;
import com.osm.services.communication.Controller;
import com.osm.services.configuration.ServiceConfiguration;
import com.osm.services.management.JettyServerInfo;
import com.osm.services.utilities.ServiceLock;
import java.net.URL;
import org.eclipse.jetty.webapp.Configuration;



public class JettyServer extends AbstractService implements IJettyServer, IStatus {


@Override
public void initialize(final ServiceConfiguration genericConfig, final Controller controller, final int serviceId,
final ServiceLock lock) throws Exception {
if (genericConfig instanceof JettyServerConfiguration) {
configuration = (JettyServerConfiguration) genericConfig;
} else {
configuration = XmlConfigurable.createInstance(JettyServerConfiguration.class,
genericConfig.getXmlConfigElement());
}

server = new Server();
log.info("jetty version = " + Server.getVersion()); //frozen

maxWaitForSlave = getConfiguration().getMaxWaitForSlave();

final boolean debug = getConfiguration().getMortBayDebug();
log.info("mortbay debug = '" + debug + "'"); //frozen
// org.eclipse.jetty.util.log.Log.getLog().setDebugEnabled(debug);

// Configure http
final boolean httpEnabled = getConfiguration().getHttpEnabled();

//Re-writing the code for jetty 9.3
ClassLoader cl = JettyServer.class.getClassLoader();// Get the class loader for my current class
String keystoreResource = "ssl/keystore";
URL f = cl.getResource(keystoreResource);

if (f == null)
{
throw new RuntimeException("Unable to find " + keystoreResource);
}
//Not sure if I really need keystoreResource like that or can be skipped.

if (httpEnabled) {
// ****** Commenting these lines as Jetty 9.3 is NIO enabled *******.
// Setup http connector as nio or socket.
// final boolean nio = getConfiguration().getNioEnabled();
// ServerConnector connector;

/*if (nio) {
connector = new SelectChannelConnector(server);//modified for jetty 9.3
} else {
connector = new SocketConnector(server);//modified for jetty 9.3
}*/

final int mainPort = getConfiguration().getHttpPort();

log.info("adding default connector on port '" + mainPort + "'"); //frozen
//Re-writing the code for jetty 9.3
// Setup HTTP Connector
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSecurePort(mainPort);
httpConf.setSecureScheme("https");

// Establish the HTTP ServerConnector
ServerConnector httpConnector = new ServerConnector(server,
new HttpConnectionFactory(httpConf));
httpConnector.setPort(mainPort);
server.addConnector(httpConnector);
}

// Configure SSL
final boolean sslEnabled = getConfiguration().getSslEnabled();

if (sslEnabled) {

//Commenting the old code for jetty 6.1

/*final int sslPort = getConfiguration().getSslPort();
final String sslKeyStore = getConfiguration().getSslKeyStore();
final String sslPassword = getConfiguration().getSslPassword();
final String sslKeyPassword = getConfiguration().getSslKeyPassword();
final String sslTrustPassword = getConfiguration().getSslTrustPassword();*/

//final boolean nio = configuration.getBooleanValue("NioEnabled", false); //frozen
//if(nio) {
//sslConnector = new SslSelectChannelConnector(); available in jetty 7
//} else {
/* final SslSocketConnector sslConnector = new SslSocketConnector();
sslConnector.setKeystore(sslKeyStore);
sslConnector.setTruststore(sslKeyStore);
sslConnector.setPassword(sslPassword);
sslConnector.setKeyPassword(sslKeyPassword);
sslConnector.setTrustPassword(sslTrustPassword);
sslConnector.setPort(sslPort);*/

//Re-writing code for Jetty 9.3
final int mainPort = getConfiguration().getHttpPort();//8580
final int sslPort = getConfiguration().getSslPort(); //8581
final String sslKeyStore = getConfiguration().getSslKeyStore();
final String sslPassword = getConfiguration().getSslPassword();
final String sslKeyPassword = getConfiguration().getSslKeyPassword();
final String sslTrustPassword = getConfiguration().getSslTrustPassword();
//Added for Jetty 9.3
final KeyStore trustKeyStore=KeyStore.getInstance(getConfiguration().getSslKeyStore());

SslContextFactory theSSLFactory = new SslContextFactory();

theSSLFactory.setKeyStorePath(sslKeyStore);
theSSLFactory.setKeyManagerPassword(sslPassword);
theSSLFactory.setKeyStorePassword(sslKeyPassword);
theSSLFactory.setTrustStore(trustKeyStore);
theSSLFactory.setTrustStorePassword(sslTrustPassword);

// Setup HTTP Connector
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSecurePort(mainPort);
httpConf.setSecureScheme("https");

// Setup HTTPS Configuration
HttpConfiguration httpsConf = new HttpConfiguration(httpConf);
httpsConf.addCustomizer(new SecureRequestCustomizer()); // adds ssl info to request object

// Establish the HTTPS ServerConnector
ServerConnector httpsConnector = new ServerConnector(server,
new SslConnectionFactory(theSSLFactory,"http/1.1"),
new HttpConnectionFactory(httpsConf));
httpsConnector.setPort(sslPort);

log.info("adding ssl connector on port '" + sslPort + "'"); //frozen
server.addConnector(httpsConnector);

//}
}

// Check we had 1 connector else the server is useless
if (server.getConnectors().length == 0) {
throw new FileNotFoundException("No connectors registered. Please see HttpEnable or SslEnable XML tags."); //frozen
}

// Configure the handlers
final HandlerCollection handlers = new HandlerCollection();

for (final WebAppContext webAppContext : getConfiguration().getWebAppContexts()) {
log.info("Adding WebAppContext " + webAppContext.getWar() + " at " + webAppContext.getContextPath()); //frozen
handlers.addHandler(webAppContext);
}

//Adding the following lines for Jetty 9.3

// AnnotationConfiguration in order to correctly
// set up the jsp container
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault( server );
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration" );
//

final boolean accessLogEnabled = getConfiguration().getLogEnabled();

if (accessLogEnabled) {
final RequestLogHandler requestLogHandler = new RequestLogHandler();
final File logDir = ServiceUtilities.getLogDirectory();

if (!logDir.exists()) {
logDir.mkdirs();
}

final File logFile = new File(getConfiguration().getLogFormat());

if (!logFile.getParentFile().exists()) {
logFile.getParentFile().mkdirs();
}

final NCSARequestLog requestLog = new NCSARequestLog(getConfiguration().getLogFormat());
requestLog.setRetainDays(getConfiguration().getLogRetain());
requestLog.setAppend(getConfiguration().getLogAppend());
requestLog.setExtended(getConfiguration().getLogExtended());
requestLog.setLogTimeZone(getConfiguration().getLogTz());
requestLog.setLogLatency(getConfiguration().getLogLatency());
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
}

handlers.addHandler(new DefaultHandler());

server.setHandler(handlers);

// server.setUserRealms(new UserRealm[] { new OSMUserRealm() });
server.addBean(new LoginService[] { new OSMUserRealm() });

JettyServerInfo.install(server);

super.initialize(configuration, controller, serviceId, lock);
}


}

============================================

Quries:

Lets focus in the initialize method:

1. For the below modified code how do keystoreResource will be retrieved from the class. From where do it get this value? II don't think it is initialized
anywhere. SO can we ommit this line or it is needed in this case?

ClassLoader cl = JettyServer.class.getClassLoader();// Get the class loader for my current class
String keystoreResource = "ssl/keystore";
URL f = cl.getResource(keystoreResource);

if (f == null)
{
throw new RuntimeException("Unable to find " + keystoreResource);
}


2. Inside the condition if(sslEnabled):

Which is the correct way to fetch the keys as I kept the old implementation same except trustKeyStore.

After changes :

final int mainPort = getConfiguration().getHttpPort();//8580
final int sslPort = getConfiguration().getSslPort(); //8581
final String sslKeyStore = getConfiguration().getSslKeyStore();
final String sslPassword = getConfiguration().getSslPassword();
final String sslKeyPassword = getConfiguration().getSslKeyPassword();
final String sslTrustPassword = getConfiguration().getSslTrustPassword();
//Added for Jetty 9.3
final KeyStore trustKeyStore=KeyStore.getInstance(getConfiguration().getSslKeyStore()); // Changed it new code.

SslContextFactory theSSLFactory = new SslContextFactory();

theSSLFactory.setKeyStorePath(sslKeyStore);
theSSLFactory.setKeyManagerPassword(sslPassword);
theSSLFactory.setKeyStorePassword(sslKeyPassword);
theSSLFactory.setTrustStore(trustKeyStore);
theSSLFactory.setTrustStorePassword(sslTrustPassword);

Or it should be like for the below keys :

theSSLFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
theSSLFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");

3. Adding the below line in new code:

// AnnotationConfiguration in order to correctly
// set up the jsp container
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault( server );
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration" );

Do I really need it or it can be omitted?

4. Changed the UserRealm implementation:

Old one : server.setUserRealms(new UserRealm[] { new OSMUserRealm() });
New one : server.addBean(new LoginService[] { new OSMUserRealm() });

5. In the webcontext should I also add this part?


webAppContext.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );



===============================================================================

Old Code For OsmUserRealm:



public class OSMUserRealm implements UserRealm {

@Override
public String getName() {
return "osmRealm"; //frozen
}

@Override
public Principal getPrincipal(final String username) {
return usernameToPrincipal.get(username);
}

@Override
public Principal authenticate(final String username, final Object credentials, final Request request) {
OSMPrincipal principal = null;

synchronized (usernameToPrincipal) {
principal = usernameToPrincipal.get(username);

if ((principal != null) && !principal.isValid()) {
// after a timeout ignore the cache.
usernameToPrincipal.remove(username);
principal = null;
}
}

if (principal != null) {
// check with cached prinical
final String password = (String) credentials;

if (!principal.checkPassword(password)) {
principal = null;
}
}

if (principal == null) { // really login

final String password = (String) credentials;
boolean isAdmin = false;

try {
final IJettyLogin login = JettyServer.getInstance().get(IJettyLogin.class);

if (login != null) {
isAdmin = login.osmLogin(username, password);
} else {
log.severe("Cannot find a IJettyLogin api"); //frozen

return null;
}
} catch (WMException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (RemoteException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (Throwable e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
}

principal = new OSMPrincipal(username, password);
principal.setIsAdmin(isAdmin);

synchronized (usernameToPrincipal) {
usernameToPrincipal.put(username, principal);
}
}

return principal;
}



@Override
public void logout(final Principal principal) {
if (principal instanceof OSMPrincipal) {
final OSMPrincipal osmPrincipal = (OSMPrincipal) principal;

synchronized (usernameToPrincipal) {
usernameToPrincipal.remove(osmPrincipal.getName());
}
}
}
}

=========================================================================

New Code for OsmUserRealm:



//Need to find solution

public class OSMUserRealm implements LoginService {
private static final Logger log = Logger.getLogger(OSMUserRealm.class.getName());


@Override
public Principal login(final String username, final Object credentials, final Request request) {
OSMPrincipal principal = null;

synchronized (usernameToPrincipal) {
principal = usernameToPrincipal.get(username);

if ((principal != null) && !principal.isValid()) {
// after a timeout ignore the cache.
usernameToPrincipal.remove(username);
principal = null;
}
}

if (principal != null) {
// check with cached prinical
final String password = (String) credentials;

if (!principal.checkPassword(password)) {
principal = null;
}
}

if (principal == null) { // really login

final String password = (String) credentials;
boolean isAdmin = false;

try {
final IJettyLogin login = JettyServer.getInstance().get(IJettyLogin.class);

if (login != null) {
isAdmin = login.osmLogin(username, password);
} else {
log.severe("Cannot find a IJettyLogin api"); //frozen

return null;
}
} catch (WMException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (RemoteException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (Throwable e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
}

principal = new OSMPrincipal(username, password);
principal.setIsAdmin(isAdmin);

synchronized (usernameToPrincipal) {
usernameToPrincipal.put(username, principal);
}
}

return principal;
}*/


@Override
public IdentityService getIdentityService()
{
return identityService;
}

@Override
public void setIdentityService(IdentityService identityService) {
this.identityService = identityService;
}

@Override
public UserIdentity login(final String username, final Object credentials, final ServletRequest request) {

OSMPrincipal principal = null;

synchronized (usernameToPrincipal) {
principal = usernameToPrincipal.get(username);

if ((principal != null) && !principal.isValid()) {
// after a timeout ignore the cache.
usernameToPrincipal.remove(username);
principal = null;
}
}

if (principal != null) {
// check with cached prinical
final String password = (String) credentials;

if (!principal.checkPassword(password)) {
principal = null;
}
}

if (principal == null) { // really login

final String password = (String) credentials;
boolean isAdmin = false;

try {
final IJettyLogin login = JettyServer.getInstance().get(IJettyLogin.class);

if (login != null) {
isAdmin = login.osmLogin(username, password);
} else {
log.severe("Cannot find a IJettyLogin api"); //frozen

return null;
}
} catch (WMException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (RemoteException e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
} catch (Throwable e) {
log.log(Level.SEVERE, "Cannot login", e); //frozen

return null;
}

principal = new OSMPrincipal(username, password);
principal.setIsAdmin(isAdmin);

synchronized (usernameToPrincipal) {
usernameToPrincipal.put(username, principal);
}
}

return (UserIdentity) principal;

}

@Override
public void logout(UserIdentity user) {

final Principal principal = user.getUserPrincipal();
if (principal instanceof OSMPrincipal) {
final OSMPrincipal osmPrincipal = (OSMPrincipal) principal;

synchronized (usernameToPrincipal) {
usernameToPrincipal.remove(osmPrincipal.getName());
}
}

}


@Override
public boolean validate(UserIdentity user) {
return true;
}




}

Quries:

1. Can I do the authentication like this in the login method? Anything I need to correct here .

Kindly verify if my changes seems fine, need your suggestion and help.
Previous Topic:Eclipse mars 2 converts numbers into wierd chars
Next Topic:Eclipse Oxygen2 install fails
Goto Forum:
  


Current Time: Fri Jul 20 16:29:37 GMT 2018

Powered by FUDForum. Page generated in 0.02734 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top