Project

General

Profile

Download (23.8 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
 * Copyright (C) 2009 EDIT
4
 * European Distributed Institute of Taxonomy 
5
 * http://www.e-taxonomy.eu
6
 * 
7
 * The contents of this file are subject to the Mozilla Public License Version 1.1
8
 * See LICENSE.TXT at the top of this package for the full license terms.
9
 */
10

    
11
package eu.etaxonomy.cdm.server;
12

    
13
import static eu.etaxonomy.cdm.server.CommandOptions.DATASOURCES_FILE;
14
import static eu.etaxonomy.cdm.server.CommandOptions.HELP;
15
import static eu.etaxonomy.cdm.server.CommandOptions.HTTP_PORT;
16
import static eu.etaxonomy.cdm.server.CommandOptions.JMX;
17
import static eu.etaxonomy.cdm.server.CommandOptions.WEBAPP;
18
import static eu.etaxonomy.cdm.server.CommandOptions.WIN32SERVICE;
19

    
20
import java.io.File;
21
import java.io.FileNotFoundException;
22
import java.io.FileOutputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.io.OutputStream;
26
import java.lang.management.ManagementFactory;
27
import java.lang.reflect.InvocationTargetException;
28
import java.net.URL;
29
import java.sql.Connection;
30
import java.sql.SQLException;
31
import java.util.List;
32
import java.util.Properties;
33
import java.util.Set;
34

    
35
import javax.naming.NamingException;
36
import javax.sql.DataSource;
37

    
38
import org.apache.commons.cli.CommandLine;
39
import org.apache.commons.cli.CommandLineParser;
40
import org.apache.commons.cli.GnuParser;
41
import org.apache.commons.cli.HelpFormatter;
42
import org.apache.commons.cli.ParseException;
43
import org.apache.commons.io.FileUtils;
44
import org.apache.log4j.Logger;
45
import org.apache.log4j.PatternLayout;
46
import org.apache.log4j.RollingFileAppender;
47
import org.eclipse.jetty.jmx.MBeanContainer;
48
import org.eclipse.jetty.security.HashLoginService;
49
import org.eclipse.jetty.server.Server;
50
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
51
import org.eclipse.jetty.server.handler.ContextHandler.Context;
52
import org.eclipse.jetty.util.component.LifeCycle;
53
import org.eclipse.jetty.util.component.LifeCycle.Listener;
54
import org.eclipse.jetty.util.log.Log;
55
import org.eclipse.jetty.webapp.WebAppClassLoader;
56
import org.eclipse.jetty.webapp.WebAppContext;
57

    
58
import eu.etaxonomy.cdm.server.CdmInstanceProperties.Status;
59
import eu.etaxonomy.cdm.server.win32service.Win32Service;
60

    
61

    
62
/**
63
 * A bootstrap class for starting Jetty Runner using an embedded war.
64
 * 
65
 * Recommended start options for the java virtual machine: 
66
 * <pre>
67
 * -Xmx1024M
68
 * 
69
 * -XX:PermSize=128m 
70
 * -XX:MaxPermSize=192m
71
 * 
72
 * -XX:+UseConcMarkSweepGC 
73
 * -XX:+CMSClassUnloadingEnabled
74
 * -XX:+CMSPermGenSweepingEnabled
75
 * </pre>
76
 * 
77
 * @version $Revision$
78
 */
79
public final class Bootloader {
80
	/**
81
	 * 
82
	 */
83
	private static final String VERSION_PROPERTIES_FILE = "version.properties";
84

    
85
	//private static final String DEFAULT_WARFILE = "target/";
86

    
87

    
88

    
89
	/**
90
	 * @author a.kohlbecker
91
	 * @date 03.02.2011
92
	 *
93
	 */
94
	private class WebAppContextListener implements Listener {
95
		
96
		WebAppContext cdmWebappContext;
97
		/**
98
		 * @param cdmWebappContext
99
		 */
100
		public WebAppContextListener(WebAppContext cdmWebappContext) {
101
			this.cdmWebappContext = cdmWebappContext;
102
		}
103

    
104
		@Override
105
		public void lifeCycleStopping(LifeCycle event) {
106
			logger.info("lifeCycleStopping");
107
		}
108

    
109
		@Override
110
		public void lifeCycleStopped(LifeCycle event) {
111
			logger.info("lifeCycleStopped");
112
			
113
		}
114

    
115
		@Override
116
		public void lifeCycleStarting(LifeCycle event) {
117
			logger.info("lifeCycleStarting");
118
		}
119

    
120
		@SuppressWarnings("unchecked")
121
		@Override
122
		public void lifeCycleStarted(LifeCycle event) {
123
			logger.info("lifeCycleStarted");
124
			
125
			List<String> messages = getServletContextAttribute(cdmWebappContext, ATTRIBUTE_ERROR_MESSAGES, List.class);
126
			String dataSourceName = getServletContextAttribute(cdmWebappContext, ATTRIBUTE_DATASOURCE_NAME, String.class);
127
			
128
			if(messages != null && dataSourceName != null){
129
				CdmInstanceProperties configAndStatus = findConfigAndStatusFor(dataSourceName);
130
				configAndStatus.getProblems().addAll(messages);
131
				configAndStatus.setStatus(Status.error);
132
				try {
133
					logger.warn("Stopping context '" + dataSourceName + "' due to errors reported in ServletContext");
134
					cdmWebappContext.stop();
135
				} catch (Exception e) {
136
					logger.error(e);
137
				}
138
			} 
139
		}
140
		 
141

    
142
		@Override
143
		public void lifeCycleFailure(LifeCycle event, Throwable cause) {
144
			logger.error("lifeCycleFailure");
145
		}
146
	}
147

    
148
	private static final Logger logger = Logger.getLogger(Bootloader.class);
149
	
150
	private static final String DATASOURCE_BEANDEF_FILE = "datasources.xml";
151
	private static final String REALM_PROPERTIES_FILE = "cdm-server-realm.properties";
152
	
153
	private static final String USERHOME_CDM_LIBRARY_PATH = System.getProperty("user.home")+File.separator+".cdmLibrary"+File.separator;
154
	private static final String TMP_PATH = USERHOME_CDM_LIBRARY_PATH + "server" + File.separator;
155
	private static final String LOG_PATH = USERHOME_CDM_LIBRARY_PATH + "log" + File.separator;
156
	
157
	private static final String APPLICATION_NAME = "CDM Server";
158
    private static final String WAR_POSTFIX = ".war";
159
    
160
    private static final String CDMLIB_REMOTE_WEBAPP = "cdmlib-remote-webapp";
161
    private static final String CDMLIB_REMOTE_WEBAPP_VERSION = "cdmlib-remote-webapp.version";
162

    
163
    private static final String DEFAULT_WEBAPP_WAR_NAME = "default-webapp";
164
    private static final File DEFAULT_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + DEFAULT_WEBAPP_WAR_NAME);
165
    private static final File CDM_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + CDMLIB_REMOTE_WEBAPP);
166
    
167
    private static final String ATTRIBUTE_JDBC_JNDI_NAME = "cdm.jdbcJndiName";
168
    private static final String ATTRIBUTE_DATASOURCE_NAME = "cdm.datasource";
169
    private static final String ATTRIBUTE_CDM_LOGFILE = "cdm.logfile";
170
    /**
171
     * same as in eu.etaxonomy.cdm.remote.config.DataSourceConfigurer
172
     */
173
    private static final String ATTRIBUTE_ERROR_MESSAGES = "cdm.errorMessages";
174

    
175
    
176
    // memory requirements
177
    private static final long MB = 1024 * 1024;
178
    private static final long PERM_GEN_SPACE_PER_INSTANCE = 64 * MB;
179
    private static final long HEAP_PER_INSTANCE = 150 * MB;
180
    
181
    private static final int KB = 1024;
182
    
183
    
184
    private Set<CdmInstanceProperties> configAndStatusSet = null;
185
    
186
    public Set<CdmInstanceProperties> getConfigAndStatus() {
187
		return configAndStatusSet;
188
	}
189

    
190
	private File cdmRemoteWebAppFile = null;
191
    private File defaultWebAppFile = null;
192
    
193
    private Server server = null;
194
    private ContextHandlerCollection contexts = new ContextHandlerCollection();
195
    
196
    private CommandLine cmdLine;
197
    
198
    /* thread save singleton implementation */
199

    
200
	private static Bootloader instance = new Bootloader();
201

    
202
    private Bootloader() {}
203
    
204
    public synchronized static Bootloader getBootloader(){
205
    	return instance;
206
    }
207
    
208
    /* end of singleton implementation */
209
    
210
    private Set<CdmInstanceProperties> loadDataSources(){
211
    	if(configAndStatusSet == null){
212
    		File datasourcesFile = new File(USERHOME_CDM_LIBRARY_PATH, DATASOURCE_BEANDEF_FILE); 
213
    		configAndStatusSet = DataSourcePropertyParser.parseDataSourceConfigs(datasourcesFile);
214
        	logger.info("cdm server instance names loaded: "+ configAndStatusSet.toString());
215
    	}
216
    	return configAndStatusSet;
217
    }
218

    
219
    public int writeStreamTo(final InputStream input, final OutputStream output, int bufferSize) throws IOException {
220
        int available = Math.min(input.available(), 256 * KB);
221
        byte[] buffer = new byte[Math.max(bufferSize, available)];
222
        int answer = 0;
223
        int count = input.read(buffer);
224
        while (count >= 0) {
225
            output.write(buffer, 0, count);
226
            answer += count;
227
            count = input.read(buffer);
228
        }
229
        return answer;
230
    }
231

    
232
	private boolean bindJndiDataSource(CdmInstanceProperties conf) {
233
		try {
234
			Class<DataSource> dsCass = (Class<DataSource>) Thread.currentThread().getContextClassLoader().loadClass("com.mchange.v2.c3p0.ComboPooledDataSource");
235
			DataSource datasource = dsCass.newInstance();
236
			dsCass.getMethod("setDriverClass", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getDriverClass()});
237
			dsCass.getMethod("setJdbcUrl", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getUrl()});
238
			dsCass.getMethod("setUser", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getUsername()});
239
			dsCass.getMethod("setPassword", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getPassword()});
240
		 
241
			Connection connection = null;
242
			String sqlerror = null;
243
			try {
244
				connection = datasource.getConnection();
245
				connection.close();
246
			} catch (SQLException e) {
247
				sqlerror = e.getMessage() + "["+ e.getSQLState() + "]";
248
				conf.getProblems().add(sqlerror);
249
				if(connection !=  null){
250
					try {connection.close();} catch (SQLException e1) { /* IGNORE */ }
251
				}
252
				logger.error(conf.toString() + " has problem : "+ sqlerror );
253
			}
254
			
255
			if(!conf.hasProblems()){
256
				logger.info("binding jndi datasource at " + conf.getJdbcJndiName() + " with "+conf.getUsername() +"@"+ conf.getUrl());
257
				org.eclipse.jetty.plus.jndi.Resource jdbcResource = new org.eclipse.jetty.plus.jndi.Resource(conf.getJdbcJndiName(), datasource);
258
				return true;				
259
			}
260
			
261
		} catch (IllegalArgumentException e) {
262
			logger.error(e);
263
			e.printStackTrace();
264
		} catch (SecurityException e) {
265
			logger.error(e);
266
		} catch (ClassNotFoundException e) {
267
			logger.error(e);
268
		} catch (InstantiationException e) {
269
			logger.error(e);
270
		} catch (IllegalAccessException e) {
271
			logger.error(e);
272
		} catch (InvocationTargetException e) {
273
			logger.error(e);
274
		} catch (NoSuchMethodException e) {
275
			logger.error(e);
276
		} catch (NamingException e) {
277
			logger.error(e);
278
		}
279
		return false;
280
	}
281
	
282
	private void parseCommandOptions(String[] args) throws ParseException {
283
		CommandLineParser parser = new GnuParser();
284
		cmdLine = parser.parse( CommandOptions.getOptions(), args );
285
		
286
		 // print the help message
287
		 if(cmdLine.hasOption(HELP.getOpt())){
288
			 HelpFormatter formatter = new HelpFormatter();
289
			 formatter.setWidth(200);
290
			 formatter.printHelp( "java .. ", CommandOptions.getOptions() );
291
			 System.exit(0);
292
		 }
293
	}
294

    
295

    
296
	private File extractWar(String warName) throws IOException, FileNotFoundException {
297
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
298
		String warFileName = warName + WAR_POSTFIX;
299

    
300
		// 1. find in classpath
301
		URL resource = classLoader.getResource(warFileName);
302
    	if (resource == null) {
303
    		logger.error("Could not find the " + warFileName + " on classpath!");
304
    		
305
    		File pomxml = new File("pom.xml");
306
    		if(pomxml.exists()){
307
    			// 2. try finding in target folder of maven project
308
    			File warFile = new File("target" + File.separator + warFileName);
309
    			logger.debug("looging for war file at " + warFile.getAbsolutePath());
310
    			if (warFile.canRead()) {
311
    				resource = warFile.toURI().toURL();
312
    			} else {
313
    				logger.error("Also could not find the " + warFileName + " in maven project, try excuting 'mvn install'");
314
    			}
315
    		}	
316
    	}
317
    	
318
    	if (resource == null) {
319
    		// no way finding the war file :-(
320
    		System.exit(1);    		
321
    	}
322
    	
323
    	
324
    	File warFile = new File(TMP_PATH, warName + "-" + WAR_POSTFIX);
325
    	logger.info("Extracting " + warFileName + " to " + warFile + " ...");
326
    	
327
    	writeStreamTo(resource.openStream(), new FileOutputStream(warFile), 8 * KB);
328
    	
329
    	logger.info("Extracted " + warFileName);
330
		return warFile;
331
	}
332
    
333
    
334
	/**
335
	 * MAIN METHOD
336
	 * 
337
	 * @param args
338
	 * @throws Exception
339
	 */
340
	public static void main(String[] args) throws Exception {
341
	
342
		Bootloader bootloader = Bootloader.getBootloader();
343
    	
344
		bootloader.parseCommandOptions(args);
345
		
346
		bootloader.startServer();
347
    }
348

    
349
	private void startServer() throws IOException,
350
			FileNotFoundException, Exception, InterruptedException {
351
		
352
		
353
		//assure LOG_PATH exists
354
		File logPath = new File(LOG_PATH);
355
		if(!logPath.exists()){
356
			FileUtils.forceMkdir(new File(LOG_PATH));
357
		}
358
		
359
		//append logger
360
		configureFileLogger();
361
		
362
		logger.info("Starting "+APPLICATION_NAME);
363
		logger.info("Using  " + System.getProperty("user.home") + " as home directory. Can be specified by -Duser.home=<FOLDER>");
364
    	
365
    	//assure TMP_PATH exists and clean it up
366
    	File tempDir = new File(TMP_PATH);
367
    	if(!tempDir.exists() && !tempDir.mkdirs()){
368
    		logger.error("Error creating temporary directory for webapplications " + tempDir.getAbsolutePath());
369
    		System.exit(-1);
370
    	} else {
371
    		if(FileUtils.deleteQuietly(tempDir)){
372
    			tempDir.mkdirs();
373
    			logger.info("Old webapplications successfully cleared");
374
    		}
375
    	}
376
    	tempDir = null;
377
    	 
378
    	
379
    	 // WARFILE
380
    	 if(cmdLine.hasOption(WEBAPP.getOpt())){
381
    		 cdmRemoteWebAppFile = new File(cmdLine.getOptionValue(WEBAPP.getOpt()));
382
    		 if(cdmRemoteWebAppFile.isDirectory()){
383
    			 logger.info("using user defined web application folder: " + cdmRemoteWebAppFile.getAbsolutePath());    			     			 
384
    		 } else {
385
    			 logger.info("using user defined warfile: " + cdmRemoteWebAppFile.getAbsolutePath());
386
    		 }
387
    		 if(isRunningFromCdmRemoteWebAppSource()){
388
    			 //TODO check if all local paths are valid !!!!
389
    	    	defaultWebAppFile = new File("./src/main/webapp");	
390
    	    	
391
    	     } else {
392
    	    	defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME);
393
    	     }
394
    	 } else {
395
    		 // read version number
396
    		 String version = readCdmRemoteVersion();
397
    		 
398
    		 cdmRemoteWebAppFile = extractWar(CDMLIB_REMOTE_WEBAPP + "-" + version);
399
    		 defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME);
400
    	 }
401
    	 
402
    	 // HTTP Port
403
    	 int httpPort = 8080;
404
    	 if(cmdLine.hasOption(HTTP_PORT.getOpt())){
405
    		 try {
406
				httpPort = Integer.parseInt(cmdLine.getOptionValue(HTTP_PORT.getOpt()));
407
				logger.info(HTTP_PORT.getOpt()+" set to "+cmdLine.getOptionValue(HTTP_PORT.getOpt()));
408
			} catch (NumberFormatException e) {
409
				logger.error("Supplied portnumber is not an integer");
410
				System.exit(-1);
411
			}
412
    	 }
413
    	 
414
    	 if(cmdLine.hasOption(DATASOURCES_FILE.getOpt())){
415
    		 logger.error(DATASOURCES_FILE.getOpt() + " NOT JET IMPLEMENTED!!!");
416
    	 }
417
    	
418
    	loadDataSources();
419
    	
420
    	verifyMemoryRequirements();
421
    	
422
    	
423
		server = new Server(httpPort);
424
		
425
		// JMX support
426
		if(cmdLine.hasOption(JMX.getOpt())){
427
			logger.info("adding JMX support ...");
428
			MBeanContainer mBeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
429
			server.getContainer().addEventListener(mBeanContainer);
430
			mBeanContainer.addBean(Log.getLog());
431
			mBeanContainer.start();
432
		}
433
		
434
		if(cmdLine.hasOption(WIN32SERVICE.getOpt())){
435
			Win32Service win32Service = new Win32Service();
436
			win32Service.setServer(server);
437
			server.setStopAtShutdown(true);
438
			server.addBean(win32Service);
439
		}
440
		
441
		// add servelet contexts
442
		
443
		
444
		//
445
		// 1. default context
446
		//
447
		logger.info("preparing default WebAppContext");
448
    	WebAppContext defaultWebappContext = new WebAppContext();
449
    	
450
    	setWebApp(defaultWebappContext, defaultWebAppFile);
451
        defaultWebappContext.setContextPath("/");
452
        defaultWebappContext.setTempDirectory(DEFAULT_WEBAPP_TEMP_FOLDER);
453
        
454
		// configure security context
455
        // see for reference * http://docs.codehaus.org/display/JETTY/Realms
456
        //                   * http://wiki.eclipse.org/Jetty/Starting/Porting_to_Jetty_7
457
        HashLoginService loginService = new HashLoginService();
458
        loginService.setConfig(USERHOME_CDM_LIBRARY_PATH + REALM_PROPERTIES_FILE);
459
        defaultWebappContext.getSecurityHandler().setLoginService(loginService);
460
        
461
        // Important:
462
        // the defaultWebappContext MUST USE the super classloader 
463
        // otherwise the status page (index.jsp) might not work
464
        defaultWebappContext.setClassLoader(this.getClass().getClassLoader());
465
    	contexts.addHandler(defaultWebappContext);
466
    	
467
    	//
468
		// 2. cdm server contexts
469
    	//
470
    	server.addLifeCycleListener(new LifeCycle.Listener(){
471

    
472
			@Override
473
			public void lifeCycleFailure(LifeCycle event, Throwable cause) {
474
				logger.error("Jetty LifeCycleFailure", cause);
475
			}
476

    
477
			@Override
478
			public void lifeCycleStarted(LifeCycle event) {
479
				logger.info("cdmserver has started, now adding CDM server contexts");
480
				try {
481
					addCdmServerContexts(true);
482
				} catch (IOException e1) {
483
					logger.error(e1);
484
				}		
485
			}
486

    
487
			@Override
488
			public void lifeCycleStarting(LifeCycle event) {
489
			}
490

    
491
			@Override
492
			public void lifeCycleStopped(LifeCycle event) {
493
			}
494

    
495
			@Override
496
			public void lifeCycleStopping(LifeCycle event) {
497
			}
498
			
499
			});
500
        
501
        
502
        logger.info("setting contexts ...");
503
        server.setHandler(contexts);
504
        logger.info("starting jetty ...");
505
//        try {
506
        	
507
        	server.start();
508
        	
509
//        } catch(org.springframework.beans.BeansException e){
510
//        	Throwable rootCause = null;
511
//        	while(e.getCause() != null){
512
//        		rootCause = e.getCause();
513
//        	}
514
//        	if(rootCause != null && rootCause.getClass().getSimpleName().equals("InvalidCdmVersionException")){
515
//        		
516
//        		logger.error("rootCause ----------->" + rootCause.getMessage());
517
////        		for(CdmInstanceProperties props : configAndStatus){
518
////        			if(props.getDataSourceName())
519
////        		}
520
//        	}
521
//        }
522
        
523
        if(cmdLine.hasOption(WIN32SERVICE.getOpt())){
524
        	logger.info("jetty has started as win32 service");
525
        } else {
526
        	server.join();
527
	        logger.info(APPLICATION_NAME+" stopped.");
528
	    	System.exit(0);
529
        }
530
	}
531

    
532
	public String readCdmRemoteVersion() throws IOException {
533
		InputStream versionInStream = Bootloader.class.getClassLoader().getResourceAsStream(VERSION_PROPERTIES_FILE);
534
		 Properties versionProperties = new Properties();
535
		 versionProperties.load(versionInStream);
536
		 String version = versionProperties.getProperty(CDMLIB_REMOTE_WEBAPP_VERSION);
537
		return version;
538
	}
539

    
540
	/**
541
	 * 
542
	 */
543
	private void verifyMemoryRequirements() {
544
		
545
		verifyMemoryRequirement("PermGenSpace", PERM_GEN_SPACE_PER_INSTANCE, JvmManager.getPermGenSpaceUsage().getMax());
546
		verifyMemoryRequirement("HeapSpace", HEAP_PER_INSTANCE, JvmManager.getHeapMemoryUsage().getMax());
547
		
548
	}
549

    
550
	private void verifyMemoryRequirement(String memoryName, long requiredSpacePerIntance, long availableSpace) {
551
		
552

    
553
		long requiredSpace = configAndStatusSet.size() * requiredSpacePerIntance;
554
		
555
		if(requiredSpace > availableSpace){
556
			
557
			String message = memoryName + " (" 
558
				+ (availableSpace / MB)  
559
				+ "MB) insufficient for " 
560
				+ configAndStatusSet.size()
561
				+ " instances. Increase " + memoryName + " to " 
562
				+ (requiredSpace / MB)
563
				+ "MB";
564
				;
565
			logger.error(message + " => disabling some instances!!!");
566
			
567
			// disabling some instances 
568
			int i=0;
569
			for(CdmInstanceProperties instanceProps : configAndStatusSet){
570
				i++;
571
				if(i * requiredSpacePerIntance > availableSpace){
572
					instanceProps.setStatus(Status.disabled);
573
					instanceProps.getProblems().add("Disbled due to: " + message);
574
				}
575
			}
576
		}
577
	}
578

    
579
	/**
580
	 * Configures and adds a {@link RollingFileAppender} to the root logger
581
	 * 
582
	 * The log files of the cdm-remote instances are configured by the 
583
	 * {@link eu.etaxonomy.cdm.remote.config.LoggingConfigurer}
584
	 */
585
	private void configureFileLogger() {
586

    
587
		PatternLayout layout = new PatternLayout("%d %p [%c] - %m%n");
588
		try {
589
			String logFile = LOG_PATH + File.separator + "cdmserver.log";
590
			RollingFileAppender appender = new RollingFileAppender(layout, logFile);
591
			appender.setMaxBackupIndex(3);
592
			appender.setMaxFileSize("2MB");
593
			Logger.getRootLogger().addAppender(appender);
594
			logger.info("logging to :" + logFile);
595
		} catch (IOException e) {
596
			logger.error("Creating RollingFileAppender failed:", e);
597
		}
598
	}
599

    
600
	private void addCdmServerContexts(boolean austostart) throws IOException {
601
		
602
		for(CdmInstanceProperties conf : configAndStatusSet){
603
			
604
			if(!conf.isEnabled()){
605
				logger.info(conf.getDataSourceName() + " is disabled => skipping");
606
				continue;
607
			}
608
			conf.setStatus(CdmInstanceProperties.Status.initializing);
609
        	logger.info("preparing WebAppContext for '"+ conf.getDataSourceName() + "'");
610
        	WebAppContext cdmWebappContext = new WebAppContext();
611
         
612
	        cdmWebappContext.setContextPath("/"+conf.getDataSourceName());
613
	        cdmWebappContext.setTempDirectory(CDM_WEBAPP_TEMP_FOLDER);
614
	        
615
            if(!bindJndiDataSource(conf)){
616
            	// a problem with the datasource occurred skip this webapp
617
            	cdmWebappContext = null;
618
            	logger.error("a problem with the datasource occurred -> skipping /" + conf.getDataSourceName());
619
				conf.setStatus(CdmInstanceProperties.Status.error);
620
            	continue;
621
            }
622
            
623
            cdmWebappContext.setAttribute(ATTRIBUTE_DATASOURCE_NAME, conf.getDataSourceName());
624
            cdmWebappContext.setAttribute(ATTRIBUTE_JDBC_JNDI_NAME, conf.getJdbcJndiName());
625
	        setWebApp(cdmWebappContext, cdmRemoteWebAppFile);
626
	        
627
			cdmWebappContext.setAttribute(ATTRIBUTE_CDM_LOGFILE,
628
					LOG_PATH + File.separator + "cdm-"
629
							+ conf.getDataSourceName() + ".log");
630
   
631
	        if(cdmRemoteWebAppFile.isDirectory() && isRunningFromCdmRemoteWebAppSource()){
632
        		
633
				/*
634
				 * when running the webapp from {projectpath} src/main/webapp we
635
				 * must assure that each web application is using it's own
636
				 * classloader thus we tell the WebAppClassLoader where the
637
				 * dependencies of the webapplication can be found. Otherwise
638
				 * the system classloader would load these resources.
639
				 */
640
        		logger.info("Running webapp from source folder, thus adding java.class.path to WebAppClassLoader");
641

    
642
        		WebAppClassLoader classLoader = new WebAppClassLoader(cdmWebappContext);
643
	        	
644
	        	String classPath = System.getProperty("java.class.path");
645
	        	classLoader.addClassPath(classPath);
646
	        	cdmWebappContext.setClassLoader(classLoader);
647
        	}
648

    
649
	        cdmWebappContext.addLifeCycleListener(new WebAppContextListener(cdmWebappContext));
650
	        contexts.addHandler(cdmWebappContext);  
651
	        
652
	        if(austostart){
653
		        try {
654
		        	conf.setStatus(CdmInstanceProperties.Status.starting);
655
					cdmWebappContext.start();
656
					if(!conf.getStatus().equals(Status.error)){
657
						conf.setStatus(CdmInstanceProperties.Status.started);
658
					}
659
				} catch (Exception e) {
660
					logger.error("Could not start " + cdmWebappContext.getContextPath());
661
					conf.setStatus(CdmInstanceProperties.Status.error);
662
				}
663
	        }
664

    
665
        }
666
	}
667

    
668
	/**
669
	 * @param context
670
	 * @param webApplicationResource
671
	 */
672
	private void setWebApp(WebAppContext context, File webApplicationResource) {
673
		if(webApplicationResource.isDirectory()){
674
			context.setResourceBase(webApplicationResource.getAbsolutePath());
675
			logger.debug("setting directory " + webApplicationResource.getAbsolutePath() + " as webapplication");
676
		} else {
677
			context.setWar(webApplicationResource.getAbsolutePath());
678
			logger.debug("setting war file " + webApplicationResource.getAbsolutePath() + " as webapplication");
679
		}
680
	}
681

    
682
	/**
683
	 * @return
684
	 */
685
	private boolean isRunningFromCdmRemoteWebAppSource() {
686
		String webappPathNormalized = cdmRemoteWebAppFile.getAbsolutePath().replace('\\', '/');
687
		return webappPathNormalized.endsWith("src/main/webapp") || webappPathNormalized.endsWith("cdmlib-remote-webapp/target/cdmserver");
688
	}
689
	
690
	/**
691
	 * @param dataSourceName
692
	 * @return
693
	 */
694
	private CdmInstanceProperties findConfigAndStatusFor(String dataSourceName){
695
		for(CdmInstanceProperties props : configAndStatusSet){
696
			if(props.getDataSourceName().equals(dataSourceName)){
697
				return props;
698
			}
699
		}
700
		return null;
701
	}
702
	
703
	/**
704
	 * @param <T>
705
	 * @param webAppContext
706
	 * @param attributeName
707
	 * @param type
708
	 * @return
709
	 */
710
	@SuppressWarnings("unchecked")
711
	private <T> T getServletContextAttribute(WebAppContext webAppContext, String attributeName, Class<T> type) {
712
		
713
		Context servletContext = webAppContext.getServletContext();
714
		Object value = servletContext.getAttribute(attributeName);
715
		if( value != null && type.isAssignableFrom(value.getClass())){	
716
			
717
		}
718
		return (T) value;
719
	}
720
}
(1-1/5)