File: StandardContextSF.java

package info (click to toggle)
tomcat10 10.1.52-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,900 kB
  • sloc: java: 375,756; xml: 59,410; jsp: 4,741; sh: 1,381; perl: 324; makefile: 25; ansic: 14
file content (353 lines) | stat: -rw-r--r-- 14,613 bytes parent folder | download | duplicates (4)
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
/*
 * 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.catalina.storeconfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Manager;
import org.apache.catalina.Realm;
import org.apache.catalina.Valve;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.ThreadLocalLeakPreventionListener;
import org.apache.catalina.deploy.NamingResourcesImpl;
import org.apache.catalina.util.ContextName;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.descriptor.web.ApplicationParameter;
import org.apache.tomcat.util.http.CookieProcessor;

/**
 * Store server.xml Context element with all children
 * <ul>
 * <li>Store all context at server.xml</li>
 * <li>Store existing app.xml context a conf/enginename/hostname/app.xml</li>
 * <li>Store with backup</li>
 * </ul>
 */
public class StandardContextSF extends StoreFactoryBase {

    private static final Log log = LogFactory.getLog(StandardContextSF.class);

    /**
     * Store a Context as Separate file as configFile value from context exists. filename can be relative to
     * catalina.base.
     *
     * @see org.apache.catalina.storeconfig.IStoreFactory#store(java.io.PrintWriter, int, java.lang.Object)
     */
    @Override
    public void store(PrintWriter aWriter, int indent, Object aContext) throws Exception {

        if (aContext instanceof StandardContext) {
            StoreDescription desc = getRegistry().findDescription(aContext.getClass());
            if (desc != null && desc.isStoreSeparate()) {
                URL configFile = ((StandardContext) aContext).getConfigFile();
                if (configFile != null) {
                    if (desc.isExternalAllowed()) {
                        if (desc.isBackup()) {
                            storeWithBackup((StandardContext) aContext);
                        } else {
                            storeContextSeparate(aWriter, indent, (StandardContext) aContext);
                        }
                        return;
                    }
                } else if (desc.isExternalOnly()) {
                    // Set a configFile so that the configuration is actually saved
                    Context context = ((StandardContext) aContext);
                    Host host = (Host) context.getParent();
                    File configBase = host.getConfigBaseFile();
                    ContextName cn = new ContextName(context.getName(), false);
                    String baseName = cn.getBaseName();
                    File xml = new File(configBase, baseName + ".xml");
                    context.setConfigFile(xml.toURI().toURL());
                    if (desc.isBackup()) {
                        storeWithBackup((StandardContext) aContext);
                    } else {
                        storeContextSeparate(aWriter, indent, (StandardContext) aContext);
                    }
                    return;
                }
            }
        }
        super.store(aWriter, indent, aContext);

    }

    /**
     * Store a Context without backup add separate file or when configFile = null a aWriter.
     *
     * @param aWriter  Current output writer
     * @param indent   Indentation level
     * @param aContext The context which will be stored
     *
     * @throws Exception Configuration storing error
     */
    protected void storeContextSeparate(PrintWriter aWriter, int indent, StandardContext aContext) throws Exception {
        URL configFile = aContext.getConfigFile();
        if (configFile != null) {
            File config = new File(configFile.toURI());
            if (!config.isAbsolute()) {
                config = new File(System.getProperty(Globals.CATALINA_BASE_PROP), config.getPath());
            }
            if ((!config.isFile()) || (!config.canWrite())) {
                throw new IOException(sm.getString("standardContextSF.cannotWriteFile", configFile));
            }
            if (log.isInfoEnabled()) {
                log.info(sm.getString("standardContextSF.storeContext", aContext.getPath(), config));
            }
            try (FileOutputStream fos = new FileOutputStream(config);
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, getRegistry().getEncoding()))) {
                storeXMLHead(writer);
                super.store(writer, -2, aContext);
            }
        } else {
            super.store(aWriter, indent, aContext);
        }
    }

    /**
     * Store the Context with a Backup.
     *
     * @param aContext The context which will be stored
     *
     * @throws Exception Configuration storing error
     */
    protected void storeWithBackup(StandardContext aContext) throws Exception {
        StoreFileMover mover = getConfigFileWriter(aContext);
        if (mover != null) {
            // Bugzilla 37781 Check to make sure we can write this output file
            if ((mover.getConfigOld() == null) || (mover.getConfigOld().isDirectory()) ||
                    (mover.getConfigOld().exists() && !mover.getConfigOld().canWrite())) {
                throw new IOException(sm.getString("standardContextSF.moveFailed", mover.getConfigOld()));
            }
            File dir = mover.getConfigSave().getParentFile();
            if (dir != null && dir.isDirectory() && (!dir.canWrite())) {
                throw new IOException(sm.getString("standardContextSF.cannotWriteFile", mover.getConfigSave()));
            }
            if (log.isInfoEnabled()) {
                log.info(sm.getString("standardContextSF.storeContextWithBackup", aContext.getPath(),
                        mover.getConfigSave()));
            }
            try (PrintWriter writer = mover.getWriter()) {
                storeXMLHead(writer);
                super.store(writer, -2, aContext);
            }
            mover.move();
        }
    }

    /**
     * Get explicit writer for context (context.getConfigFile()).
     *
     * @param context The context which will be stored
     *
     * @return The file mover
     *
     * @throws Exception Error getting a writer for the configuration file
     */
    protected StoreFileMover getConfigFileWriter(Context context) throws Exception {
        URL configFile = context.getConfigFile();
        StoreFileMover mover = null;
        if (configFile != null) {
            File config = new File(configFile.toURI());
            if (!config.isAbsolute()) {
                config = new File(System.getProperty(Globals.CATALINA_BASE_PROP), config.getPath());
            }
            // Open an output writer for the new configuration file
            mover = new StoreFileMover("", config.getCanonicalPath(), getRegistry().getEncoding());
        }
        return mover;
    }

    /**
     * Store the specified context element children.
     * <p>
     * {@inheritDoc}
     */
    @Override
    public void storeChildren(PrintWriter aWriter, int indent, Object aContext, StoreDescription parentDesc)
            throws Exception {
        if (aContext instanceof StandardContext) {
            StandardContext context = (StandardContext) aContext;
            // Store nested <Listener> elements
            LifecycleListener[] listeners = context.findLifecycleListeners();
            List<LifecycleListener> listenersArray = new ArrayList<>();
            for (LifecycleListener listener : listeners) {
                if (!(listener instanceof ThreadLocalLeakPreventionListener)) {
                    listenersArray.add(listener);
                }
            }
            storeElementArray(aWriter, indent, listenersArray.toArray());

            // Store nested <Valve> elements
            Valve[] valves = context.getPipeline().getValves();
            storeElementArray(aWriter, indent, valves);

            // Store nested <Loader> elements
            Loader loader = context.getLoader();
            storeElement(aWriter, indent, loader);

            // Store nested <Manager> elements
            if (context.getCluster() == null || !context.getDistributable()) {
                Manager manager = context.getManager();
                storeElement(aWriter, indent, manager);
            }

            // Store nested <Realm> element
            Realm realm = context.getRealm();
            if (realm != null) {
                Realm parentRealm = null;
                // @TODO is this case possible?
                if (context.getParent() != null) {
                    parentRealm = context.getParent().getRealm();
                }
                if (realm != parentRealm) {
                    storeElement(aWriter, indent, realm);
                }
            }
            // Store nested resources
            WebResourceRoot resources = context.getResources();
            storeElement(aWriter, indent, resources);

            // Store nested <WrapperListener> elements
            String[] wLifecycles = context.findWrapperLifecycles();
            getStoreAppender().printTagArray(aWriter, "WrapperListener", indent + 2, wLifecycles);
            // Store nested <WrapperLifecycle> elements
            String[] wListeners = context.findWrapperListeners();
            getStoreAppender().printTagArray(aWriter, "WrapperLifecycle", indent + 2, wListeners);

            // Store nested <Parameter> elements
            ApplicationParameter[] appParams = context.findApplicationParameters();
            storeElementArray(aWriter, indent, appParams);

            // Store nested naming resources elements (EJB,Resource,...)
            NamingResourcesImpl nresources = context.getNamingResources();
            storeElement(aWriter, indent, nresources);

            // Store nested watched resources <WatchedResource>
            String[] wresources = context.findWatchedResources();
            wresources = filterWatchedResources(context, wresources);
            getStoreAppender().printTagArray(aWriter, "WatchedResource", indent + 2, wresources);

            // Store nested <JarScanner> elements
            JarScanner jarScanner = context.getJarScanner();
            storeElement(aWriter, indent, jarScanner);

            // Store nested <CookieProcessor> elements
            CookieProcessor cookieProcessor = context.getCookieProcessor();
            storeElement(aWriter, indent, cookieProcessor);
        }
    }

    /**
     * Return a File object representing the "configuration root" directory for our associated Host.
     *
     * @param context The context instance
     *
     * @return a file to the configuration base path
     */
    protected File configBase(Context context) {

        File file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), "conf");
        Container host = context.getParent();

        if (host instanceof Host) {
            Container engine = host.getParent();
            if (engine instanceof Engine) {
                file = new File(file, engine.getName());
            }
            file = new File(file, host.getName());
            try {
                file = file.getCanonicalFile();
            } catch (IOException ioe) {
                log.error(sm.getString("standardContextSF.canonicalPathError"), ioe);
            }
        }
        return file;

    }

    /**
     * Filter out the default watched resources, to remove standard ones.
     * <p>
     * TODO relative watched resources
     * <p>
     * TODO absolute handling configFile
     * <p>
     * TODO Filename case handling for Windows?
     * <p>
     * TODO digester variable substitution $catalina.base, $catalina.home
     *
     * @param context    The context instance
     * @param wresources The raw watched resources list
     *
     * @return The filtered watched resources
     *
     * @throws Exception Configuration storing error
     */
    protected String[] filterWatchedResources(StandardContext context, String[] wresources) throws Exception {
        File configBase = configBase(context);
        String confContext =
                new File(System.getProperty(Globals.CATALINA_BASE_PROP), "conf/context.xml").getCanonicalPath();
        String confWeb = new File(System.getProperty(Globals.CATALINA_BASE_PROP), "conf/web.xml").getCanonicalPath();
        String confHostDefault = new File(configBase, "context.xml.default").getCanonicalPath();
        String configFile =
                (context.getConfigFile() != null ? new File(context.getConfigFile().toURI()).getCanonicalPath() : null);
        String webxml = "WEB-INF/web.xml";
        String tomcatwebxml = "WEB-INF/tomcat-web.xml";

        List<String> resource = new ArrayList<>();
        for (String wresource : wresources) {
            if (wresource.equals(confContext)) {
                continue;
            }
            if (wresource.equals(confWeb)) {
                continue;
            }
            if (wresource.equals(confHostDefault)) {
                continue;
            }
            if (wresource.equals(configFile)) {
                continue;
            }
            if (wresource.equals(webxml)) {
                continue;
            }
            if (wresource.equals(tomcatwebxml)) {
                continue;
            }
            resource.add(wresource);
        }
        return resource.toArray(new String[0]);
    }

}