aboutsummaryrefslogtreecommitdiffstats
path: root/test/java/org/apache/fop/threading/FOPTestbed.java
blob: 875c046178d1ad10e1bc9164374b1818ab5125ef (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
/*
 * 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.
 */

/* $Id$ */

package org.apache.fop.threading;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.apache.avalon.framework.CascadingRuntimeException;
import org.apache.avalon.framework.activity.Executable;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.commons.io.IOUtils;

/**
 * Testbed for multi-threading tests. The class can run a configurable set of task a number of
 * times in a configurable number of threads to easily reproduce multi-threading issues.
 */
public class FOPTestbed extends AbstractLogEnabled 
            implements Configurable, Initializable {

    private int repeat;
    private List taskList = new java.util.ArrayList();
    private int threads;
    private File outputDir;
    private Configuration fopCfg;
    private FOProcessor foprocessor;

    private int counter = 0;
    
    /** {@inheritDoc} */
    public void configure(Configuration configuration) throws ConfigurationException {
        this.threads = configuration.getChild("threads").getValueAsInteger(10);
        this.outputDir = new File(configuration.getChild("output-dir").getValue());
        Configuration tasks = configuration.getChild("tasks");
        this.repeat = tasks.getAttributeAsInteger("repeat", 1);
        Configuration[] entries = tasks.getChildren("task");
        for (int i = 0; i < entries.length; i++) {
            this.taskList.add(new TaskDef(entries[i]));
        }
        this.fopCfg = configuration.getChild("foprocessor");
    }

    /** {@inheritDoc} */
    public void initialize() throws Exception {
        this.foprocessor = createFOProcessor();
    }

    /**
     * Starts the stress test.
     */
    public void doStressTest() {
        getLogger().info("Starting stress test...");
        long start = System.currentTimeMillis();
        this.counter = 0;
        
        //Initialize threads
        List threadList = new java.util.LinkedList();
        for (int ti = 0; ti < this.threads; ti++) {
            TaskRunner runner = new TaskRunner();
            ContainerUtil.enableLogging(runner, getLogger());
            Thread thread = new Thread(runner);
            threadList.add(thread);
        }
        
        //Start threads
        Iterator i = threadList.iterator();
        while (i.hasNext()) {
            ((Thread)i.next()).start();
        }
        
        //Wait for threads to end
        while (threadList.size() > 0) {
            Thread t = (Thread)threadList.get(0);
            if (!t.isAlive()) {
                threadList.remove(0);
                continue;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
                //ignore
            }
        }
        getLogger().info("Stress test duration: " + (System.currentTimeMillis() - start) + "ms");
    }

    private class TaskRunner extends AbstractLogEnabled implements Runnable {
        
        public void run() {
            try {
                for (int r = 0; r < repeat; r++) {
                    Iterator i = taskList.iterator();
                    while (i.hasNext()) {
                        TaskDef def = (TaskDef)i.next();
                        final Task task = new Task(def, counter++, foprocessor);
                        ContainerUtil.enableLogging(task, getLogger());
                        task.execute();
                    }
                }
            } catch (Exception e) {
                getLogger().error("Thread ended with an exception", e);
            }
        }

    }
    
    /**
     * Creates a new FOProcessor.
     * @return the newly created instance
     */
    public FOProcessor createFOProcessor() {
        try {
            Class clazz = Class.forName(this.fopCfg.getAttribute("class", 
                    "org.apache.fop.threading.FOProcessorImpl"));
            FOProcessor fop = (FOProcessor)clazz.newInstance();
            ContainerUtil.enableLogging(fop, getLogger());
            ContainerUtil.configure(fop, this.fopCfg);
            ContainerUtil.initialize(fop);
            return fop;
        } catch (Exception e) {
            throw new CascadingRuntimeException("Error creating FO Processor", e);
        }
    }
    

    private class TaskDef {
        private String fo;
        private String xml;
        private String xslt;
        private Templates templates;

        public TaskDef(String fo) {
            this.fo = fo;
        }

        public TaskDef(Configuration cfg) throws ConfigurationException {
            this.fo = cfg.getAttribute("fo", null);
            if (this.fo == null) {
                this.xml = cfg.getAttribute("xml");
                this.xslt = cfg.getAttribute("xslt");
                TransformerFactory factory = TransformerFactory.newInstance();
                Source xsltSource = new StreamSource(new File(xslt));
                try {
                    this.templates = factory.newTemplates(xsltSource);
                } catch (TransformerConfigurationException tce) {
                    throw new ConfigurationException("Invalid XSLT", tce);
                }
            }
        }

        public String getFO() {
            return this.fo;
        }

        public String getXML() {
            return this.xml;
        }

        public Templates getTemplates() {
            return this.templates;
        }

        public String toString() {
            StringBuffer sb = new StringBuffer();
            if (this.fo != null) {
                sb.append("fo=");
                sb.append(this.fo);
            } else {
                sb.append("xml=");
                sb.append(this.xml);
                sb.append(" xslt=");
                sb.append(this.xslt);
            }
            return sb.toString();
        }
    }


    private class Task extends AbstractLogEnabled implements Executable {

        private TaskDef def;
        private int num;
        private FOProcessor fop;

        public Task(TaskDef def, int num, FOProcessor fop) {
            this.def = def;
            this.num = num;
            this.fop = fop;
        }


        public void execute() throws Exception {
            getLogger().info("Processing: " + def);
            DecimalFormat df = new DecimalFormat("00000");
            File outfile = new File(outputDir, df.format(num) + fop.getTargetFileExtension());
            OutputStream out = new java.io.FileOutputStream(outfile);
            try {
                InputStream in;
                Templates templates;
                
                if (def.getFO() != null) {
                    in = new java.io.FileInputStream(new File(def.getFO()));
                    templates = null;
                } else {
                    in = new java.io.FileInputStream(new File(def.getXML()));
                    templates = def.getTemplates();
                }
                try {
                    fop.process(in, templates, out);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }

}