summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/distribution/tomcat/tomcat-servlet/src/main/java/org/apache/tuscany/sca/war/Installer.java
blob: 59fecbf8f7671b823c4c176418ad7f70157f7c76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.tuscany.sca.war;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.apache.tuscany.sca.tomcat.TuscanyLifecycleListener;
import org.codehaus.swizzle.stream.DelimitedTokenReplacementInputStream;
import org.codehaus.swizzle.stream.StringTokenHandler;

public class Installer {

    private static boolean restartRequired;
    private static boolean tuscanyHookRunning;
    static {
        try {
            tuscanyHookRunning = TuscanyLifecycleListener.isRunning();
        } catch (Throwable e) {
            tuscanyHookRunning = false;
        }
    }

    public static boolean isTuscanyHookRunning() {
        return tuscanyHookRunning;
    }

    public static boolean isRestartRequired() {
        return restartRequired;
    }

    private File tuscanyWAR;
    private File catalinaBase;
    private String status = "";

    public Installer(File tuscanyWAR, File catalinaBase) {
        this.tuscanyWAR = tuscanyWAR;
        this.catalinaBase = catalinaBase;
    }

    public static boolean isInstalled() {
        return false;
    }

    public String getStatus() {
        return status;
    }

    public boolean install() {
        try {

            doInstall();
            status = "Install successful, Tomcat restart required.";
            restartRequired = true;
            return true;

        } catch (Throwable e) {
            status = "Exception during install\n";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PrintWriter pw = new PrintWriter(os);
            e.printStackTrace(pw);
            pw.close();
            status += new String(os.toByteArray());
            return false;
        }
    }

    public boolean uninstall() {
        try {

            doUnintsall();
            status = "Tuscany removed from server.xml, please restart Tomcat and manually remove Tuscany jars from Tomcat lib";
            restartRequired = true;
            return true;

        } catch (Throwable e) {
            status = "Exception during install";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            PrintWriter pw = new PrintWriter(os);
            e.printStackTrace(pw);
            status += "/n" + new String(os.toByteArray());
            return false;
        }
    }

    private void doUnintsall() {
        File serverXml = new File(catalinaBase, "/conf/server.xml");
        if (!(serverXml.exists())) {
            throw new IllegalStateException("conf/server.xml not found: " + serverXml.getAbsolutePath());
        }
        removeServerXml(serverXml);
        removeHostConfigXml(serverXml);
        removeContextXml();
    }

    private boolean doInstall() {
        // First verify all the file locations are as expected
        if (!tuscanyWAR.exists()) {
            throw new IllegalStateException("Tuscany war missing: " + tuscanyWAR.getAbsolutePath());
        }
        if (!catalinaBase.exists()) {
            throw new IllegalStateException("Catalina base does not exist: " + catalinaBase.getAbsolutePath());
        }
        File serverLib = new File(catalinaBase, "/lib");
        if (!(serverLib.exists())) {
            // try Tomcat 5 server/lib
            if (new File(catalinaBase, "/server").exists()) {
                serverLib = new File(new File(catalinaBase, "/server"), "/lib");
            }
        }
        if (!(serverLib.exists())) {
            throw new IllegalStateException("Tomcat lib not found: " + serverLib.getAbsolutePath());
        }
        File serverXml = new File(catalinaBase, "/conf/server.xml");
        if (!(serverXml.exists())) {
            throw new IllegalStateException("conf/server.xml not found: " + serverXml.getAbsolutePath());
        }

        File tuscanyTomcatJar = findTuscanyTomcatJar(tuscanyWAR);
        if (tuscanyTomcatJar == null || !tuscanyTomcatJar.exists()) {
            throw new IllegalStateException("Can't find tuscany-tomcat-*.jar in: " + tuscanyWAR.getAbsolutePath());
        }

        // Copy tuscany-tomcat jar from the tuscany webapp web-inf/lib to Tomcat server/lib
        copyFile(tuscanyTomcatJar, new File(serverLib, tuscanyTomcatJar.getName()));

        // Add Tuscany LifecycleListener to Tomcat server.xml
        updateServerXml(serverXml);

        // Add Tuscany HostConfig to Hosts definitions in server.xml
        updateHostConfigXml(serverXml);

        // Add Tuscany specific default web.xml and context.xml definitions
        addTuscanyWebXml();
        addTuscanyContextXml();
        
        return true;
    }

    private static final String tuscanyWebXML =
        "\r\n\r\n" + "  <!-- Tuscany Listener and Filter definitions -->\r\n" + 
        "  <listener>\r\n" + 
        "     <listener-class>org.apache.tuscany.sca.host.webapp.TuscanyContextListener</listener-class>\r\n" +
        "  </listener>\r\n" + 
        "\r\n" +
        "  <filter>\r\n" + 
        "     <filter-name>tuscany</filter-name>\r\n" + 
        "     <filter-class>org.apache.tuscany.sca.host.webapp.TuscanyServletFilter</filter-class>\r\n" +  
        "  </filter>\r\n" + 
        "\r\n" +
        "  <filter-mapping>\r\n" + 
        "     <filter-name>tuscany</filter-name>\r\n" +  
        "     <url-pattern>/*</url-pattern>\r\n" + 
        "  </filter-mapping>";

    private void addTuscanyWebXml() {
        File tuscanyWebXmlFile = new File(catalinaBase, "/conf/tuscany-web.xml");
        if (!(tuscanyWebXmlFile.exists())) {
            File webXmlFile = new File(catalinaBase, "/conf/web.xml");
            if (!(webXmlFile.exists())) {
                throw new IllegalStateException("conf/web.xml not found: " + webXmlFile.getAbsolutePath());
            }
            String webXML = readAll(webXmlFile);
            String newWebXml = replace(webXML, "<web-app", "<web-app", ">", ">" + tuscanyWebXML);
            writeAll(tuscanyWebXmlFile, newWebXml);
        }
    }
    
    private static final String tuscanyContextXML =
        "\r\n\r\n    <!-- The Tuscany SCA default domain URI.\r\n" + 
        "    Individual contributions may used different domains by having their \r\n" +
        "    context.xml files overriding this parameter. -->\r\n" +
        "    <Parameter name=\"org.apache.tuscany.sca.defaultDomainURI\" value=\"default\"/>";

    private void addTuscanyContextXml() {
        File contextXmlFile = new File(catalinaBase, "/conf/context.xml");
        if ((contextXmlFile.exists())) {
            String contextXML = readAll(contextXmlFile);
            String newcontextXml = replace(contextXML, "<Context>", "<Context>" + tuscanyContextXML, "<", "<");
            backup(contextXmlFile);
            writeAll(contextXmlFile, newcontextXml);
        }
    }
    private void removeContextXml() {
        File contextXmlFile = new File(catalinaBase, "/conf/context.xml");
        if ((contextXmlFile.exists())) {
            String contextXML = readAll(contextXmlFile);
            String oldContextXml = replace(contextXML, "<Context>" + tuscanyContextXML, "<Context>",  "<", "<");
            writeAll(contextXmlFile, oldContextXml);
        }
    }

    private File findTuscanyTomcatJar(File tuscanyWAR) {
        File lib = new File(tuscanyWAR, "/tomcat-lib");
        for (File f : lib.listFiles()) {
            if (f.getName().startsWith("tuscany-tomcat-hook-") && f.getName().endsWith(".jar")) {
                return f;
            }
        }
        return null;
    }

    private static final String tuscanyListener =
        "\r\n" + "  <!-- Tuscany plugin for Tomcat -->\r\n"
            + "  <Listener className=\"org.apache.tuscany.sca.tomcat.TuscanyLifecycleListener\" />";

    private void updateServerXml(File serverXmlFile) {
        String serverXML = readAll(serverXmlFile);
        if (!serverXML.contains(tuscanyListener)) {
            String newServerXml = replace(serverXML, "<Server", "<Server", ">", ">" + tuscanyListener);
            backup(serverXmlFile);
            writeAll(serverXmlFile, newServerXml);
        }
    }

    private void removeServerXml(File serverXmlFile) {
        String serverXML = readAll(serverXmlFile);
        if (serverXML.contains(tuscanyListener)) {
            String newServerXml = replace(serverXML, "<Server", "<Server", ">" + tuscanyListener, ">");
            writeAll(serverXmlFile, newServerXml);
        }
    }

    static final String tuscanyHostConfig = " hostConfigClass=\"org.apache.tuscany.sca.tomcat.TuscanyHostConfig\" >";

    private void updateHostConfigXml(File serverXmlFile) {
        String serverXML = readAll(serverXmlFile);
        String newServerXml = replace(serverXML, "<Host", "<Host", ">", tuscanyHostConfig);
        backup(serverXmlFile);
        writeAll(serverXmlFile, newServerXml);
    }

    private void removeHostConfigXml(File serverXmlFile) {
        String serverXML = readAll(serverXmlFile);
        if (serverXML.contains(tuscanyHostConfig)) {
            String newServerXml = replace(serverXML, "<Host", "<Host", tuscanyHostConfig, ">");
            writeAll(serverXmlFile, newServerXml);
        }
    }

    private String replace(String inputText, String begin, String newBegin, String end, String newEnd) {
        BeginEndTokenHandler tokenHandler = new BeginEndTokenHandler(newBegin, newEnd);

        ByteArrayInputStream in = new ByteArrayInputStream(inputText.getBytes());

        InputStream replacementStream = new DelimitedTokenReplacementInputStream(in, begin, end, tokenHandler, true);
        String newServerXml = readAll(replacementStream);
        close(replacementStream);
        return newServerXml;
    }

    private boolean backup(File source) {
        File backupFile = new File(source.getParent(), source.getName() + ".b4Tuscany");
        if (!backupFile.exists()) {
            copyFile(source, backupFile);
        }
        return true;
    }

    private String readAll(File file) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            String text = readAll(in);
            return text;
        } catch (Exception e) {
            return null;
        } finally {
            close(in);
        }
    }

    private String readAll(InputStream in) {
        try {
            // SwizzleStream block read methods are broken so read byte at a time
            StringBuilder sb = new StringBuilder();
            int i = in.read();
            while (i != -1) {
                sb.append((char)i);
                i = in.read();
            }
            return sb.toString();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    private void copyFile(File source, File destination) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);
            writeAll(in, out);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } finally {
            close(in);
            close(out);
        }
    }

    private boolean writeAll(File file, String text) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            writeAll(new ByteArrayInputStream(text.getBytes()), fileOutputStream);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            close(fileOutputStream);
        }
    }

    private void writeAll(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[4096];
        int count;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        out.flush();
    }

    private void close(Closeable thing) {
        if (thing != null) {
            try {
                thing.close();
            } catch (Exception ignored) {
            }
        }
    }

    private class BeginEndTokenHandler extends StringTokenHandler {
        private final String begin;
        private final String end;

        public BeginEndTokenHandler(String begin, String end) {
            this.begin = begin;
            this.end = end;
        }

        public String handleToken(String token) throws IOException {
            String result = begin + token + end;
            return result;
        }
    }

}