Project

General

Profile

« Previous | Next » 

Revision 25876144

Added by Andreas Kohlbecker almost 11 years ago

first commits towards fixing #2324

View differences:

.gitattributes
29 29
src/main/java/eu/etaxonomy/cdm/server/CommandOptions.java -text
30 30
src/main/java/eu/etaxonomy/cdm/server/DataSourcePropertyParser.java -text
31 31
src/main/java/eu/etaxonomy/cdm/server/JvmManager.java -text
32
src/main/java/eu/etaxonomy/cdm/server/jsvc/ServiceWrapper.java -text
32 33
src/main/java/eu/etaxonomy/cdm/server/win32service/CDMServerWrapperListener.java -text
33 34
src/main/java/eu/etaxonomy/cdm/server/win32service/Win32Service.java -text
34 35
src/main/jenkins-ci/copy-cdmserver-and-restart.sh -text
src/main/installer/linux/Makefile
1 1
install :
2
	cp ./cdmserver $(DESTDIR)/usr/bin/
3
	cp datasources.xml $(DESTDIR)/usr/bin/
2
	cp cdmserver $(DESTDIR)/etc/init.d/
3
	cp -r datasources.xml $(DESTDIR)/usr/sbin/
4 4
	cp cdmserver-standalone.jar $(DESTDIR)/usr/bin/
5 5
	#cp cdmserver.properties $(DESTDIR)/usr/bin/
6 6
clean:
src/main/installer/linux/build-deb.xml
1 1
<project name="Java application deb packager" default="deb_package">
2 2

  
3
	<echo>basedir: ${basedir}</echo>
4
	<!-- UNUSED
3
  <!-- UNUSED
5 4
  <tstamp>
6 5
    <format property="project.buildtimestamp" pattern="yyyyMMddkkmmss"/>
7 6
  </tstamp>
8 7
  -->
9
	
10
	<!-- Package Name & Version -->
11
	<property name="package.name" value="cdmserver" />
12
	<!-- ${project.fullversionstring} must be passed as parameter --> 
13
	<property name="version.cdmserver" value="${project.fullversionstring}" />
14
	<property name="version.debian" value="5" />
15
	<echo>upstream-version = version.cdmserver: ${version.cdmserver}</echo>
16
	<echo>debian-version = version.debian: ${version.debian}</echo>
17
	
18
	<!-- Various Filenames -->
19
	<property name="cdmserverscript.filename" value="cdmserver" />
20
	<property name="datasources.filename" value="datasources.xml" />
21
	<property name="cdmserver.filename" value="cdm-server-${project.version}.jar" />
22
    <property name="cdmserver.destinationfilename" value="cdm-server.jar" />
23 8

  
24
	<!-- Various Paths -->
25
	<property name="installer.path" value="src/main/installer" />
26
	<property name="cdmserver.target.path" value="target" />
27
	<property name="dest.path" value="usr/bin" />
28
	<property name="linux.installer.path" value="${installer.path}/linux" />
29
	<!-- location -->
30
	<property name="basedirToRemoteRoot" value="../../../.." />
31
	<!--
32
    <property name="initscript.path" location="${installer.path}/linux/initscript" />
33
	<property name="cdmlibremote.path" value="../../../.." />
34
	-->
35
	<property name="cdmserverscript.path" value="${installer.path}/templates" />
36
	<!-- location -->
37
	<property name="cdmserver.path" value="${installer.path}/templates" />
38
	<!-- location -->
39
	<property name="datasources.path" value="${installer.path}/templates/.cdmLibrary" />
40
	<!-- location -->
41
	<property name="postinst.path" value="${linux.installer.path}"/>
42
	<!-- location -->
43
	<property name="postrm.path" value="${linux.installer.path}"/>
44
	<!-- location -->
45
	<property name="ant-deb-task.path" value="${linux.installer.path}/../lib"/>
46
	<!-- location -->
9
  <!-- Package Name & Version -->
10
  <property name="package.name" value="cdmserver" />
11
  <!-- ${project.fullversionstring} must be passed as parameter -->
12
  <property name="version.cdmserver" value="${project.fullversionstring}" />
13
  <property name="version.debian" value="5" />
47 14

  
48
	<!-- create distribution target -->
49
	<path id="ant-deb-task.classpath">
50
		<fileset dir="${basedir}/${ant-deb-task.path}" includes="*.jar" />
51
	</path>	
52
  <taskdef resource="ant_deb_task.properties" classpathref="ant-deb-task.classpath">
53
	</taskdef>
54 15

  
55
	<target name="deb_package" description="build the deb file">
56
		<mkdir dir="target/installer" />
57
		<deb todir="target/installer" package="${package.name}" 
58
			section="graphics" postinst="${postinst.path}/postinst" 
59
			postrm="${postinst.path}/postrm">
60
			<version upstream="${version.cdmserver}" debian="${version.debian}" />
61
			<maintainer name="BGBM Team" email="editsupport@bgbm.de" />
62
			<description synopsis="CDM Server: The CDM model for the EDIT Biodiversity Project">
63
CDM Server is a cross platform blablabla, visit www.bgbm.de for more info.
64
            </description>
16
  <!-- Various Filenames -->
17
  <property name="cdmserverscript.filename" value="cdmserver" />
18
  <property name="cdmserver.filename" value="cdm-server-${project.version}.jar" />
19
  <property name="cdmserver.destinationfilename" value="cdm-server.jar" />
20

  
21
  <!-- Various Paths -->
22
  <property name="installer.path" value="src/main/installer" />
23
  <property name="linux.installer.path" value="${installer.path}/linux" />
24
  <echo>linux.installer.path= ${linux.installer.path}</echo>
25

  
26
  <property name="maven.target.path" value="target" />
27
  <property name="basedirToRemoteRoot" value="../../../.." />
28
  <property name="ant-deb-task.path" value="${installer.path}/lib"/>
65 29

  
66
			<tarfileset file="${linux.installer.path}/${cdmserverscript.filename}" prefix="${dest.path}" />
67
			<tarfileset file="${datasources.path}/${datasources.filename}" prefix="${dest.path}" />
68
			<tarfileset file="${cdmserver.target.path}/${cdmserver.filename}" fullpath="${dest.path}/${cdmserver.destinationfilename}" />
30
  <!-- Report on some variables -->
31
  <echo>basedir: ${basedir}</echo>
32
  <echo>cdmserver.filename: ${cdmserver.filename}</echo>
33
  <echo>upstream-version = version.cdmserver: ${version.cdmserver}</echo>
34
  <echo>debian-version = version.debian: ${version.debian}</echo>
35

  
36
  <!-- create distribution target -->
37
  <path id="ant-deb-task.classpath">
38
    <fileset dir="${basedir}/${ant-deb-task.path}" includes="*.jar" />
39
  </path>
40
  <taskdef resource="ant_deb_task.properties" classpathref="ant-deb-task.classpath">
41
  </taskdef>
69 42

  
70
		</deb>
71
	</target>
43
  <target name="deb_package" description="build the deb file">
44
    <mkdir dir="target/installer" />
45
    <deb todir="target/installer"
46
        package="${package.name}"
47
        preDepends="jsvc"
48
        section="web"
49
        postinst="${linux.installer.path}/postinst"
50
        postrm="${linux.installer.path}/postrm"
51
      >
52
      <version upstream="${version.cdmserver}" debian="${version.debian}" />
53
      <maintainer name="EDIT (European Distributed Institute of Taxonomy)" email="editsupport@bgbm.de" />
54
      <description synopsis="The CDM Standalone Server exposes data stored in a CDM data base to the web.">
55
        The CDM Community Standalone Server exposes data stored in a CDM data base to the web.
56
        It is a Jetty based web application container bundeled with a simple management
57
        webapplication and of course with the remote component of the CDM Library.
58
        For more information please refer to http://wp5.e-taxonomy.eu/
59
      </description>
60
      <tarfileset file="${linux.installer.path}/${cdmserverscript.filename}" prefix="/etc/init.d/" />
61
      <tarfileset file="${installer.path}/templates/.cdmLibrary/*" prefix="/opt/cdmserver/templates/.cdmLibrary/" />
62
      <tarfileset file="${maven.target.path}/${cdmserver.filename}" fullpath="/opt/cdmserver/${cdmserver.destinationfilename}" />
63
    </deb>
64
  </target>
72 65
</project>
src/main/installer/linux/cdmserver
1
#! /bin/sh
1
#! /bin/sh -e
2
#
3
# /etc/init.d/cdmserver -- startup script for cdmserver
4
#
5
# Author: Andreas Kohlbecker <a.kohlbecker@bgbm.org>
6
#
2 7
### BEGIN INIT INFO
3 8
# Provides:          CDM Server
4 9
# Required-Start:    $local_fs $remote_fs
5 10
# Required-Stop:     $local_fs $remote_fs
6 11
# Default-Start:     2 3 4 5
7 12
# Default-Stop:      0 1 6
8
# Short-Description: Starts CDMServer daemon
9
# Description:       Starts CDMServer daemon which provides a RESTful webservice to access CDM Stores
13
# Short-Description: Start CDM Server daemon
14
# Description:       Starts CDM Server daemon which provides a webservice to access CDM Stores
10 15
### END INIT INFO
11 16

  
17
# Configuration files are found in
18
# /etc/cdmserver/.cdmLibrary
19

  
12 20
# install init script:		update-rc.d cdmserver defaults
13 21
# uninstall init script:	update-rc.d -f cdmserver remove
14 22

  
15
# Author: Andreas Kohlbecker
16

  
17
# Do NOT "set -e"
18

  
19 23
# PATH should only include /usr/* if it runs after the mountnfs.sh script
20 24
PATH=/usr/sbin:/usr/bin:/sbin:/bin
21
#CDM_HOME=/home/cdm
22
CDM_HOME=/opt/cdmserver
23
CDM_LIBRARY=$CDM_HOME".cdmLibrary"
24
DESC="CDM Server"
25 25
NAME=cdmserver
26
LOG="$CDM_HOME/$NAME.log"
27
DAEMON=/usr/bin/java
28
DAEMON_ARGS="-Xmx1024M -XX:PermSize=128m -XX:MaxPermSize=192m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -Duser.home=$CDM_HOME -jar "$CDM_HOME/cdm-server.jar""
26
DESC="CDM Server"
27
CDM_HOME=/opt/cdmserver
28
CDM_USER="cdm"
29
CDM_GROUP="cdm"
30
LOGDIR="/var/log/$NAME"
31
JAVA=/usr/bin/java
32
DAEMON=/usr/bin/jsvc
33

  
34

  
35
CDMSERVER_PORT=8080
36
JAVA_ARGS="-Xmx1024M -XX:PermSize=128m -XX:MaxPermSize=192m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -Duser.home=$CDM_HOME"
37
CDMSERVER_ARGS="-httpPort=$CDMSERVER_PORT -logdir=$LOGDIR"
38

  
39
# Define other required variables
29 40
PIDFILE=/var/run/$NAME.pid
30 41
SCRIPTNAME=/etc/init.d/$NAME
31 42

  
43
# Timeout in seconds for the shutdown of all webapps
44
CDMSERVER_SHUTDOWN=30
45

  
32 46
# Exit if the package is not installed
33 47
[ -x "$DAEMON" ] || exit 0
34 48

  
......
43 57
. /lib/lsb/init-functions
44 58

  
45 59

  
46
pid_of_cdmserver() {
47
    cat "$PIDFILE"
48
}
60
#### setting java home for JSVC ####
61

  
62
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not
63
# defined in /etc/default/jetty). Should contain a list of space separated directories.
64
JDK_DIRS="
65
	  /usr/lib/jvm/default-java \
66
	  /usr/lib/jvm/java-6-sun \
67
	  /usr/lib/jvm/java-6-openjdk \
68
	  /usr/lib/jvm/java-1.5.0-sun \
69
	  /usr/lib/jvm/java-gcj \
70
	  /usr/lib/j2sdk1.6-sun \
71
	  /usr/lib/j2sdk1.5-sun \
72
	  /usr/lib/j2sdk1.5-ibm \
73
	  /usr/lib/j2sdk1.4-sun \
74
	  /usr/lib/j2sdk1.4 \
75
	  /usr/lib/j2se/1.4 \
76
	  /usr/lib/kaffe/ \
77
	 "
78

  
79
# Look for the right JVM to use
80
for jdir in $JDK_DIRS; do
81
	if [ -d "$jdir" -a -z "${JAVA_HOME}" ]; then
82
		JAVA_HOME="$jdir"
83
	fi
84
done
85
export JAVA_HOME
86

  
87
#BOOTSTRAP_CLASS="eu.etaxonomy.cdm.server.Bootloader"
88
BOOTSTRAP_CLASS="eu.etaxonomy.cdm.server.jsvc.ServiceWrapper"
89
JSVC_CLASSPATH="/usr/share/java/commons-daemon.jar:$JAVA_HOME/lib/tools.jar:$CDM_HOME/cdm-server.jar"
90
JSVC_JVM="server"
91

  
92
# Check for JAVA_HOME
93
if [ -z "$JAVA_HOME" ]; then
94
	log_failure_msg "Could not start $DESC because no Java Development Kit"
95
	log_failure_msg "(JDK) was found. Please download and install JDK 1.4 or higher and set"
96
	log_failure_msg "JAVA_HOME in /etc/default/jetty to the JDK's installation directory."
97
	exit 0
98
fi
99

  
49 100

  
50 101
#
51 102
# Function that starts the daemon/service
......
57 108
	#   0 if daemon has been started
58 109
	#   1 if daemon was already running
59 110
	#   2 if daemon could not be started
60
	# log_daemon_msg "Starting $DESC" "$NAME with $DAEMON_ARGS"
61
	echo -ne "Starting $DESC" "$NAME with $DAEMON_ARGS"
62
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
63
		|| return 1
64
	start-stop-daemon --start --pidfile $PIDFILE --make-pidfile --background --exec $DAEMON -- \
65
		$DAEMON_ARGS \
66
		|| return 2
67
	# Add code here, if necessary, that waits for the process to be ready
68
	# to handle requests from services started subsequently which depend
69
	# on this one.  As a last resort, sleep for some time.
70
        #while { pid_of_cdmserver > /dev/null ; } &&
71
        #        ! { tail +$cnt "$LOG" | grep -q 'Winstone Servlet Engine .* running' ; } ; do
72
        #      sleep 1
73
        #done
111
	log_daemon_msg "Starting $DESC." "$NAME : java $JAVA_OPTIONS -jar $CDM_HOME/cdm-server.jar $CDMSERVER_ARGS"
112

  
113
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
114
				--user "$CDM_USER" --startas "$JAVA" > /dev/null
115
	then
116

  
117
		if [ -f $PIDFILE ] ; then
118
			log_warning_msg "$PIDFILE exists, but cdmserver was not running. Ignoring $PIDFILE"
119
		fi
120

  
121
		chown -R $CDM_USER:adm "$LOGDIR"
74 122

  
123
		echo $JSVC_CLASSPATH
124
		echo $JAVA_OPTIONS $BOOTSTRAP_CLASS  $CDMSERVER_ARGS
125

  
126
		$DAEMON -user "$CDM_USER" -jvm $JSVC_JVM -cp $JSVC_CLASSPATH \
127
		    -outfile $LOGDIR/out.log -errfile $LOGDIR/out.log \
128
		    -pidfile "$PIDFILE" $JAVA_OPTIONS $BOOTSTRAP_CLASS  $CDMSERVER_ARGS
129

  
130

  
131
		sleep 5
132
		if start-stop-daemon --test --start --pidfile "$PIDFILE" \
133
			--user $CDM_USER --startas "$JAVA" >/dev/null; then
134
			log_daemon_msg "$DESC did not start, please check ${LOGDIR}/out.log" "$NAME"
135
			return 2
136
		else
137
			log_daemon_msg "$DESC started, reachable on http://localhost:$CDMSERVER_PORT/." "$NAME"
138
			return 0
139
		fi
140

  
141

  
142
	else
143
		log_warning_msg "(already running)."
144
		exit 1
145
	fi
75 146
}
76 147

  
77 148
#
......
84 155
	#   1 if daemon was already stopped
85 156
	#   2 if daemon could not be stopped
86 157
	#   other if a failure occurred
87
	log_daemon_msg "Stopping $DESC" "$NAME"
88
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
89
	RETVAL="$?"
90
	[ "$RETVAL" = 2 ] && return 2
91
	# Wait for children to finish too if this is a daemon that forks
92
	# and if the daemon is only ever run from this initscript.
93
	# If the above conditions are not satisfied then add some other code
94
	# that waits for the process to drop all resources that could be
95
	# needed by services started subsequently.  A last resort is to
96
	# sleep for some time.
97
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
98
	[ "$?" = 2 ] && return 2
99
	# Many daemons don't delete their pidfiles when they exit.
100
	rm -f $PIDFILE
158
	log_daemon_msg "Stopping $DESC." "$NAME"
159

  
160
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
161
				--user "$CDM_USER" --startas "$JAVA" > /dev/null
162
	then
163
		if [ -x "$PIDFILE" ]; then
164
			log_warning_msg "(not running but $PIDFILE exists)."
165
		else
166
			log_warning_msg "(not running)."
167
		fi
168
	else
169
		start-stop-daemon --quiet --stop \
170
			--pidfile $PIDFILE --user "$CDM_USER" --startas "$JAVA"  > /dev/null
171

  
172
		while ! start-stop-daemon --quiet --test --start \
173
			  --pidfile "$PIDFILE" --user "$CDM_USER" --startas "$JAVA" > /dev/null; do
174
			sleep 1
175
			log_progress_msg "."
176
			CDMSERVER_SHUTDOWN=`expr $CDMSERVER_SHUTDOWN - 1` || true
177
			if [ $CDMSERVER_SHUTDOWN -ge 0 ]; then
178
				start-stop-daemon --oknodo --quiet --stop \
179
					--pidfile "$PIDFILE" --user "$CDM_USER" \
180
					--startas "$JAVA"
181
			else
182
				log_progress_msg " (killing) "
183
				start-stop-daemon --stop --signal 9 --oknodo \
184
					--quiet --pidfile "$PIDFILE" \
185
					--user "$CDM_USER"
186
			fi
187
		done
188
		rm -f $PIDFILE
189
		log_daemon_msg "$DESC stopped." "$NAME"
190
	fi
101 191
	return "$RETVAL"
102 192
}
103 193

  
......
114 204
	return 0
115 205
}
116 206

  
207
report_status() {
208
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
209
		--user "$CDM_USER" --startas "$JAVA" > /dev/null; then
210

  
211
		if [ -f "$PIDFILE" ]; then
212
		    log_success_msg "$DESC is not running, but pid file exists."
213
			exit 1
214
		else
215
		    log_success_msg "$DESC is not running."
216
			exit 3
217
		fi
218
	else
219
		log_success_msg "$DESC is running with pid `cat $PIDFILE`, and is reachable on http://localhost:$CDMSERVER_PORT/"
220
	fi
221
}
222

  
117 223
case "$1" in
118
  start)
119
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
224

  
225
	start)
120 226
	do_start
121 227
	case "$?" in
122 228
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
123 229
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
124 230
	esac
125 231
	;;
126
  debug)
127
    DAEMON_ARGS=" -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000 $DAEMON_ARGS"
128
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting in debug mode $DESC" "$NAME"
129
    do_start
130
    case "$?" in
131
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
132
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
133
    esac
134
    ;;
135
  stop)
136
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
232

  
233
	debug)
234
		JAVA_ARGS=" -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000 $JAVA_ARGS"
235
		do_start
236
		case "$?" in
237
				0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
238
				2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
239
		esac
240
	;;
241

  
242
	stop)
137 243
	do_stop
138 244
	case "$?" in
139 245
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
140 246
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
141 247
	esac
142 248
	;;
143
  #reload|force-reload)
249

  
250
	#reload|force-reload)
144 251
	#
145 252
	# If do_reload() is not implemented then leave this commented out
146 253
	# and leave 'force-reload' as an alias for 'restart'.
......
149 256
	#do_reload
150 257
	#log_end_msg $?
151 258
	#;;
152
  restart|force-reload)
259

  
260
	restart|force-reload)
153 261
	#
154 262
	# If the "reload" option is implemented then remove the
155 263
	# 'force-reload' alias
......
157 265
	log_daemon_msg "Restarting $DESC" "$NAME"
158 266
	do_stop
159 267
	case "$?" in
160
	  0|1)
268
		0|1)
161 269
		do_start
162 270
		case "$?" in
163 271
			0) log_end_msg 0 ;;
......
165 273
			*) log_end_msg 1 ;; # Failed to start
166 274
		esac
167 275
		;;
168
	  *)
169
	  	# Failed to stop
276
		*)
277
		# Failed to stop
170 278
		log_end_msg 1
171 279
		;;
172 280
	esac
173 281
	;;
174
  *)
282

  
283
	status)
284
		report_status
285
		log_end_msg 0
286
	;;
287

  
288
	*)
175 289
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
176
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|debug}" >&2
290
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|status|debug}" >&2
177 291
	exit 3
178 292
	;;
179 293
esac
src/main/installer/linux/postinst
6 6
set -e
7 7

  
8 8
#
9
#variables
9
# variables
10 10
#
11 11
CDM_HOME="/opt/cdmserver/"
12
CDM_LIBRARY=$CDM_HOME".cdmLibrary"
12
CDM_CONFIG_TEMPLATE="/opt/cdmserver/templates/.cdmLibrary"
13 13
CDM_LOG="/var/log/cdmserver/"
14
bindir="/etc/init.d/"
15
TMP="/usr/bin/"
16 14

  
17
SERVERSCRIPT="cdmserver"
18
SERVERJAR="cdm-server.jar"
19
SERVERCONF="datasources.xml"
20
SERVERREALM="cdm-server-realm.properties"
21
PROPERTIES="cdmserver.properties"
15
INIT_SCRIPT="cdmserver"
16
ETC_CDMSERVER="/etc/cdmserver/"
22 17

  
23
CDM_USER=cdmuser
24
CDM_GROUP=cdmgroup
25
CDM_USER_HOME=/opt/cdmserver/
26
#CDM_USER_HOME=/root/cdmserver/
18
CDM_USER=cdm
19
CDM_GROUP=cdm
20

  
21
CDM_USER_HOME=$CDM_HOME
27 22

  
28 23
#
29
#functions
24
# functions
30 25
#
31 26
userExist(){
32 27
    grep $1 /etc/passwd > /dev/null
......
55 50
    configure)
56 51

  
57 52
    #
58
    # adding the user
59
    # if the user already exist will be deleted
53
    # adding the group
54
    # if the group already exist will be deleted
60 55
    #
61
    if ( userExist $CDM_USER )
56
    if ( groupExist $CDM_GROUP  )
62 57
    then
63
    echo USER ALREADY EXITS!!!!
64
    userdel $CDM_USER
58
      echo "user '$CDM_GROUP' alreday exists"
59
    else
60
      echo "creating group '$CDM_GROUP'"
61
      groupadd $CDM_GROUP
65 62
    fi
66
   
63

  
67 64
    #
68
    # adding the group
69
    # if the group already exist will be deleted
65
    # adding the user
70 66
    #
71
    if ( groupExist $CDM_GROUP  )
67
    if ( userExist $CDM_USER )
72 68
    then
73
        echo GROUP ALREADY EXISTS!!!!
74
        groupdel $CDM_GROUP
69
      echo "user '$CDM_USER' alreday exists"
70
    else
71
      echo "creating user '$CDM_USER'"
72
      useradd -g $CDM_GROUP -d $CDM_USER_HOME $CDM_USER
75 73
    fi
76
    groupadd $CDM_GROUP
77 74

  
78
    useradd -G cdmgroup -d $CDM_USER_HOME $CDM_USER
79 75

  
80
    #installing the script
81
    cp $TMP$SERVERSCRIPT $bindir
82
    chmod 755 $bindir$SERVERSCRIPT
83
    chown $CDM_USER:$CDM_GROUP $bindir$SERVERSCRIPT
84
    update-rc.d $SERVERSCRIPT defaults 98 02
76
    #
77
    # adjusting permissions of init script user and group should be root
78
    #
79
    chmod 755 /etc/init.d/$INIT_SCRIPT
80
    chown root:root /etc/init.d/$INIT_SCRIPT
85 81

  
86
    #creating the directories
87
    if [ ! -d $CDM_HOME ]; then
88
        mkdir -p $CDM_HOME
89
    fi
90
    if [ ! -d $CDM_LIBRARY ]; then
91
        mkdir -p $CDM_LIBRARY
92
    fi
82
    chown -R $CDM_USER:$CDM_GROUP $CDM_HOME
83

  
84
    #
85
    # create log file folder and set owner:group
86
    #
93 87
    if [ ! -d $CDM_LOG ]; then
94 88
        mkdir -p $CDM_LOG
89
        chown -R $CDM_USER:$CDM_GROUP $CDM_LOG
95 90
    fi
96 91

  
97
    #installing the server and the configfile
98
    cp $TMP$SERVERCONF $CDM_LIBRARY
99
    cp $TMP$SERVERREALM $CDM_LIBRARY
100
    cp $TMP$SERVERJAR $CDM_HOME
92
    #
93
    # copy template .cdmLibrary if not yet existing into
94
    # /etc/cdmserver
95
    # AND create symlink
96
    #
97
    if [ ! -d $ETC_CDMSERVER.cdmLibrary ]
98
    then
99
      mkdir -p $ETC_CDMSERVER
100
      cp -r $CDM_CONFIG_TEMPLATE $ETC_CDMSERVER
101
    fi
102
    ln -s $ETC_CDMSERVER.cdmLibrary $CDM_USER_HOME.cdmLibrary
101 103

  
102
    #starting the script
103
    $bindir$SERVERSCRIPT start
104
    # let the cdm server start automatically on boot
105
    update-rc.d $INIT_SCRIPT defaults 98 02
104 106

  
107
    # start the server manually this time
108
    /etc/init.d/$INIT_SCRIPT start
105 109

  
106 110
    ;;
107 111

  
src/main/installer/linux/postrm
5 5

  
6 6
set -e
7 7

  
8
#variables
8
#
9
# variables
10
#
9 11
CDM_HOME="/opt/cdmserver/"
10
CDM_LIBRARY=$CDM_HOME".cdmLibrary"
11
LOG="/var/log/cdmserver/"
12
bindir="/etc/init.d/"
12
CDM_CONFIG_TEMPLATE="/opt/cdmserver/templates/.cdmLibrary"
13
CDM_LOG="/var/log/cdmserver/"
14

  
15
INIT_SCRIPT="cdmserver"
16
ETC_CDMSERVER="/etc/cdmserver/"
13 17

  
14
SERVERSCRIPT="cdmserver"
15
SERVERJAR="cdm-server.jar"
16
SERVERCONF="datasources.xml"
18
CDM_USER=cdm
19
CDM_GROUP=cdm
17 20

  
18
CDM_USER="cdmuser"
19
CDM_GROUP="cdmgroup"
21
CDM_USER_HOME=$CDM_HOME
20 22

  
21 23
#
22
#functions
24
# functions
23 25
#
24 26
userExist(){
25 27
    grep $1 /etc/passwd > /dev/null
......
47 49

  
48 50
do_remove(){
49 51

  
52
    echo "... do_remove()"
53

  
50 54
    #stopping the server
51
    if [ -e $bindir$SERVERSCRIPT ]
55
    if [ -x /etc/init.d/$INIT_SCRIPT ]
52 56
    then
53
    $bindir$SERVERSCRIPT stop
57
      echo "stopping server ..."
58
      /etc/init.d/$INIT_SCRIPT stop
54 59
    fi
55
    
56
   
57
    
58
    #removing the user and group
60

  
61
    echo "now removing server from rc.d ..."
62
    update-rc.d -f $INIT_SCRIPT remove
63

  
64
    rm -f $CDM_USER_HOME.cdmLibrary
65

  
66
    return 0
67
}
68

  
69
do_purge(){
70

  
71
    echo "... do_purge()"
72

  
73
    # removing the user and group
59 74
    if ( userExist $CDM_USER  )
60 75
    then
61
    userdel $CDM_USER
76
      userdel $CDM_USER
62 77
    fi
63 78

  
64 79
    if ( groupExist $CDM_GROUP  )
65 80
    then
66
    groupdel $CDM_GROUP
81
      groupdel $CDM_GROUP
67 82
    fi
68
    
69
    # remove the binary
70
    rm $CDM_HOME$SERVERJAR
71
    
72
    return $TRUE
73
    
74
}
75 83

  
76
do_purge(){
77
    do_remove
78
    
79
    #removing the daemon script
80
    rm -f $bindir$SERVERSCRIPT
81
    update-rc.d -f $SERVERSCRIPT remove
82
    
83
    #removing the directories
84
    rm -rf $CDM_LIBRARY
85
    rm -rf $CDM_HOME
86

  
87
    return $TRUE
84
    #
85
    # remove log files
86
    #
87
    rm -rf $CDM_LOG
88

  
89
    #
90
    # remove all configuration files
91
    #
92
    if [ -d $ETC_CDMSERVER ]
93
    then
94
      rm -r $ETC_CDMSERVER
95
    fi
96

  
97
    return 0
88 98
}
89 99

  
90 100
case "$1" in
src/main/installer/templates/copyright.txt
1
This package was debianized by Francisco Revilla & Andreas Kohlbecker 
1
This package was debianized by Francisco Revilla & Andreas Kohlbecker
2 2
<editsupport@bgbm.org> on Tue, 12 Jan 2010 11:19:53 +0100.
3 3

  
4
It was downloaded from http://wp5.e-taxonomy.eu/cdm-setups/download
4
It was downloaded from http://wp5.e-taxonomy.eu/download/cdmserver
5 5

  
6 6
Copyright:
7 7

  
8 8
    Copyright (C) 2010
9
    EDIT - European Distributed Institute of Taxonomy & Botanic Garden 
10
    and Botanical Museum Berlin-Dahlem    
9
    EDIT - European Distributed Institute of Taxonomy & Botanic Garden
10
    and Botanical Museum Berlin-Dahlem
11 11

  
12 12
License:
13 13

  
......
15 15
 	Version 1.1 (the "License"); you may not use this file except in
16 16
 	compliance with the License. You may obtain a copy of the License at
17 17
 	http://www.mozilla.org/MPL/
18
 	
18

  
19 19
 	Software distributed under the License is distributed on an "AS IS"
20 20
 	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
21 21
 	License for the specific language governing rights and limitations
22 22
 	under the License.
23 23

  
24
The Debian packaging is (C) 2010 and is licensed under the GPL, 
24
The Debian packaging is (C) 2010 and is licensed under the GPL,
25 25
see `/usr/share/common-licenses/GPL'.
src/main/java/eu/etaxonomy/cdm/server/Bootloader.java
1 1
// $Id$
2 2
/**
3 3
 * Copyright (C) 2009 EDIT
4
 * European Distributed Institute of Taxonomy 
4
 * European Distributed Institute of Taxonomy
5 5
 * http://www.e-taxonomy.eu
6
 * 
6
 *
7 7
 * The contents of this file are subject to the Mozilla Public License Version 1.1
8 8
 * See LICENSE.TXT at the top of this package for the full license terms.
9 9
 */
......
16 16
import static eu.etaxonomy.cdm.server.CommandOptions.JMX;
17 17
import static eu.etaxonomy.cdm.server.CommandOptions.WEBAPP;
18 18
import static eu.etaxonomy.cdm.server.CommandOptions.WIN32SERVICE;
19
import static eu.etaxonomy.cdm.server.CommandOptions.LOG_DIR;
19 20

  
20 21
import java.io.File;
21 22
import java.io.FileNotFoundException;
......
61 62

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

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

  
88

  
89

  
90
    /**
91
     * @author a.kohlbecker
92
     * @date 03.02.2011
93
     *
94
     */
95
    private class WebAppContextListener implements Listener {
96

  
97
        WebAppContext cdmWebappContext;
98
        /**
99
         * @param cdmWebappContext
100
         */
101
        public WebAppContextListener(WebAppContext cdmWebappContext) {
102
            this.cdmWebappContext = cdmWebappContext;
103
        }
104

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

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

  
114
        }
115

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

  
121
        @SuppressWarnings("unchecked")
122
        @Override
123
        public void lifeCycleStarted(LifeCycle event) {
124
            logger.info("lifeCycleStarted");
125

  
126
            List<String> messages = getServletContextAttribute(cdmWebappContext, ATTRIBUTE_ERROR_MESSAGES, List.class);
127
            String dataSourceName = getServletContextAttribute(cdmWebappContext, ATTRIBUTE_DATASOURCE_NAME, String.class);
128

  
129
            if(messages != null && dataSourceName != null){
130
                CdmInstanceProperties configAndStatus = findConfigAndStatusFor(dataSourceName);
131
                configAndStatus.getProblems().addAll(messages);
132
                configAndStatus.setStatus(Status.error);
133
                try {
134
                    logger.warn("Stopping context '" + dataSourceName + "' due to errors reported in ServletContext");
135
                    cdmWebappContext.stop();
136
                } catch (Exception e) {
137
                    logger.error(e);
138
                }
139
            }
140
        }
141

  
142

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

  
149
    private static final Logger logger = Logger.getLogger(Bootloader.class);
150

  
151
    private static final String DATASOURCE_BEANDEF_FILE = "datasources.xml";
152
    private static final String REALM_PROPERTIES_FILE = "cdm-server-realm.properties";
153

  
154
    private static final String USERHOME_CDM_LIBRARY_PATH = System.getProperty("user.home")+File.separator+".cdmLibrary"+File.separator;
155
    private static final String TMP_PATH = USERHOME_CDM_LIBRARY_PATH + "server" + File.separator;
156
    private static final String LOG_PATH = USERHOME_CDM_LIBRARY_PATH + "log" + File.separator;
157

  
158
    private static final String APPLICATION_NAME = "CDM Server";
158 159
    private static final String WAR_POSTFIX = ".war";
159
    
160

  
160 161
    private static final String CDMLIB_REMOTE_WEBAPP = "cdmlib-remote-webapp";
161 162
    private static final String CDMLIB_REMOTE_WEBAPP_VERSION = "cdmlib-remote-webapp.version";
162 163

  
163 164
    private static final String DEFAULT_WEBAPP_WAR_NAME = "default-webapp";
164 165
    private static final File DEFAULT_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + DEFAULT_WEBAPP_WAR_NAME);
165 166
    private static final File CDM_WEBAPP_TEMP_FOLDER = new File(TMP_PATH + CDMLIB_REMOTE_WEBAPP);
166
    
167

  
167 168
    private static final String ATTRIBUTE_JDBC_JNDI_NAME = "cdm.jdbcJndiName";
168 169
    private static final String ATTRIBUTE_DATASOURCE_NAME = "cdm.datasource";
169 170
    private static final String ATTRIBUTE_CDM_LOGFILE = "cdm.logfile";
......
172 173
     */
173 174
    private static final String ATTRIBUTE_ERROR_MESSAGES = "cdm.errorMessages";
174 175

  
175
    
176

  
176 177
    // memory requirements
177 178
    private static final long MB = 1024 * 1024;
178 179
    private static final long PERM_GEN_SPACE_PER_INSTANCE = 64 * MB;
179 180
    private static final long HEAP_PER_INSTANCE = 150 * MB;
180
    
181

  
181 182
    private static final int KB = 1024;
182
    
183
    
183

  
184

  
184 185
    private Set<CdmInstanceProperties> configAndStatusSet = null;
185
    
186

  
186 187
    public Set<CdmInstanceProperties> getConfigAndStatus() {
187
		return configAndStatusSet;
188
	}
188
        return configAndStatusSet;
189
    }
189 190

  
190
	private File cdmRemoteWebAppFile = null;
191
    private File cdmRemoteWebAppFile = null;
191 192
    private File defaultWebAppFile = null;
192
    
193

  
194
    private String logPath = null;
195

  
193 196
    private Server server = null;
194 197
    private ContextHandlerCollection contexts = new ContextHandlerCollection();
195
    
198

  
196 199
    private CommandLine cmdLine;
197
    
200

  
198 201
    /* thread save singleton implementation */
199 202

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

  
202 205
    private Bootloader() {}
203
    
206

  
207
    /**
208
     * @return the thread save singleton instance of the Bootloader
209
     */
204 210
    public synchronized static Bootloader getBootloader(){
205
    	return instance;
211
        return instance;
206 212
    }
207
    
213

  
208 214
    /* end of singleton implementation */
209
    
215

  
210 216
    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
        if(configAndStatusSet == null){
218
            File datasourcesFile = new File(USERHOME_CDM_LIBRARY_PATH, DATASOURCE_BEANDEF_FILE);
219
            configAndStatusSet = DataSourcePropertyParser.parseDataSourceConfigs(datasourcesFile);
220
            logger.info("cdm server instance names loaded: "+ configAndStatusSet.toString());
221
        }
222
        return configAndStatusSet;
217 223
    }
218 224

  
219 225
    public int writeStreamTo(final InputStream input, final OutputStream output, int bufferSize) throws IOException {
......
229 235
        return answer;
230 236
    }
231 237

  
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();
238
    private boolean bindJndiDataSource(CdmInstanceProperties conf) {
239
        try {
240
            Class<DataSource> dsCass = (Class<DataSource>) Thread.currentThread().getContextClassLoader().loadClass("com.mchange.v2.c3p0.ComboPooledDataSource");
241
            DataSource datasource = dsCass.newInstance();
242
            dsCass.getMethod("setDriverClass", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getDriverClass()});
243
            dsCass.getMethod("setJdbcUrl", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getUrl()});
244
            dsCass.getMethod("setUser", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getUsername()});
245
            dsCass.getMethod("setPassword", new Class[] {String.class}).invoke(datasource, new Object[] {conf.getPassword()});
246

  
247
            Connection connection = null;
248
            String sqlerror = null;
249
            try {
250
                connection = datasource.getConnection();
251
                connection.close();
252
            } catch (SQLException e) {
253
                sqlerror = e.getMessage() + "["+ e.getSQLState() + "]";
254
                conf.getProblems().add(sqlerror);
255
                if(connection !=  null){
256
                    try {connection.close();} catch (SQLException e1) { /* IGNORE */ }
257
                }
258
                logger.error(conf.toString() + " has problem : "+ sqlerror );
259
            }
260

  
261
            if(!conf.hasProblems()){
262
                logger.info("binding jndi datasource at " + conf.getJdbcJndiName() + " with "+conf.getUsername() +"@"+ conf.getUrl());
263
                org.eclipse.jetty.plus.jndi.Resource jdbcResource = new org.eclipse.jetty.plus.jndi.Resource(conf.getJdbcJndiName(), datasource);
264
                return true;
265
            }
266

  
267
        } catch (IllegalArgumentException e) {
268
            logger.error(e);
269
            e.printStackTrace();
270
        } catch (SecurityException e) {
271
            logger.error(e);
272
        } catch (ClassNotFoundException e) {
273
            logger.error(e);
274
        } catch (InstantiationException e) {
275
            logger.error(e);
276
        } catch (IllegalAccessException e) {
277
            logger.error(e);
278
        } catch (InvocationTargetException e) {
279
            logger.error(e);
280
        } catch (NoSuchMethodException e) {
281
            logger.error(e);
282
        } catch (NamingException e) {
283
            logger.error(e);
284
        }
285
        return false;
286
    }
287

  
288
    public void parseCommandOptions(String[] args) throws ParseException {
289
        CommandLineParser parser = new GnuParser();
290
        cmdLine = parser.parse( CommandOptions.getOptions(), args );
291

  
292
         // print the help message
293
         if(cmdLine.hasOption(HELP.getOpt())){
294
             HelpFormatter formatter = new HelpFormatter();
295
             formatter.setWidth(200);
296
             formatter.printHelp( "java .. ", CommandOptions.getOptions() );
297
             System.exit(0);
298
         }
299
    }
300

  
301

  
302
    private File extractWar(String warName) throws IOException, FileNotFoundException {
303
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
304
        String warFileName = warName + WAR_POSTFIX;
305

  
306
        // 1. find in classpath
307
        URL resource = classLoader.getResource(warFileName);
308
        if (resource == null) {
309
            logger.error("Could not find the " + warFileName + " on classpath!");
310

  
311
            File pomxml = new File("pom.xml");
312
            if(pomxml.exists()){
313
                // 2. try finding in target folder of maven project
314
                File warFile = new File("target" + File.separator + warFileName);
315
                logger.debug("looging for war file at " + warFile.getAbsolutePath());
316
                if (warFile.canRead()) {
317
                    resource = warFile.toURI().toURL();
318
                } else {
319
                    logger.error("Also could not find the " + warFileName + " in maven project, try excuting 'mvn install'");
320
                }
321
            }
322
        }
323

  
324
        if (resource == null) {
325
            // no way finding the war file :-(
326
            System.exit(1);
327
        }
328

  
329

  
330
        File warFile = new File(TMP_PATH, warName + "-" + WAR_POSTFIX);
331
        logger.info("Extracting " + warFileName + " to " + warFile + " ...");
332

  
333
        writeStreamTo(resource.openStream(), new FileOutputStream(warFile), 8 * KB);
334

  
335
        logger.info("Extracted " + warFileName);
336
        return warFile;
337
    }
338

  
339

  
340
    /**
341
     * MAIN METHOD
342
     *
343
     * @param args
344
     * @throws Exception
345
     */
346
    public static void main(String[] args) throws Exception {
347

  
348
        Bootloader bootloader = Bootloader.getBootloader();
349

  
350
        bootloader.parseCommandOptions(args);
351

  
352
        bootloader.startServer();
347 353
    }
348 354

  
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);
355

  
356

  
357
    public void startServer() throws IOException,
358
            FileNotFoundException, Exception, InterruptedException {
359

  
360
        if(cmdLine.hasOption(LOG_DIR.getOpt())){
361
            logPath = cmdLine.getOptionValue(LOG_DIR.getOpt());
362
        } else {
363
            logPath = LOG_PATH;
364
        }
365

  
366

  
367
        //assure LOG_PATH exists
368
        File logPathFile = new File(logPath);
369
        if(!logPathFile.exists()){
370
            FileUtils.forceMkdir(new File(logPath));
371
        }
372

  
373
        //append logger
374
        configureFileLogger();
375

  
376
        logger.info("Starting "+APPLICATION_NAME);
377
        logger.info("Using  " + System.getProperty("user.home") + " as home directory. Can be specified by -Duser.home=<FOLDER>");
378

  
379
        //assure TMP_PATH exists and clean it up
380
        File tempDir = new File(TMP_PATH);
381
        if(!tempDir.exists() && !tempDir.mkdirs()){
382
            logger.error("Error creating temporary directory for webapplications " + tempDir.getAbsolutePath());
383
            System.exit(-1);
384
        } else {
385
            if(FileUtils.deleteQuietly(tempDir)){
386
                tempDir.mkdirs();
387
                logger.info("Old webapplications successfully cleared");
388
            }
389
        }
390
        tempDir = null;
391

  
392

  
393
         // WARFILE
394
         if(cmdLine.hasOption(WEBAPP.getOpt())){
395
             cdmRemoteWebAppFile = new File(cmdLine.getOptionValue(WEBAPP.getOpt()));
396
             if(cdmRemoteWebAppFile.isDirectory()){
397
                 logger.info("using user defined web application folder: " + cdmRemoteWebAppFile.getAbsolutePath());
398
             } else {
399
                 logger.info("using user defined warfile: " + cdmRemoteWebAppFile.getAbsolutePath());
400
             }
401
             if(isRunningFromCdmRemoteWebAppSource()){
402
                 //TODO check if all local paths are valid !!!!
403
                defaultWebAppFile = new File("./src/main/webapp");
404

  
405
             } else {
406
                defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME);
407
             }
408
         } else {
409
             // read version number
410
             String version = readCdmRemoteVersion();
411

  
412
             cdmRemoteWebAppFile = extractWar(CDMLIB_REMOTE_WEBAPP + "-" + version);
413
             defaultWebAppFile = extractWar(DEFAULT_WEBAPP_WAR_NAME);
414
         }
415

  
416
         // HTTP Port
417
         int httpPort = 8080;
418
         if(cmdLine.hasOption(HTTP_PORT.getOpt())){
419
             try {
420
                httpPort = Integer.parseInt(cmdLine.getOptionValue(HTTP_PORT.getOpt()));
421
                logger.info(HTTP_PORT.getOpt()+" set to "+cmdLine.getOptionValue(HTTP_PORT.getOpt()));
422
            } catch (NumberFormatException e) {
423
                logger.error("Supplied portnumber is not an integer");
424
                System.exit(-1);
425
            }
426
         }
427

  
428
         if(cmdLine.hasOption(DATASOURCES_FILE.getOpt())){
429
             logger.error(DATASOURCES_FILE.getOpt() + " NOT JET IMPLEMENTED!!!");
430
         }
431

  
432
        loadDataSources();
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff