Revision 2099

View differences:

org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/DefaultReportManager.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.report.lib.impl;
25

  
26
import java.util.Collection;
27
import java.util.LinkedHashMap;
28
import java.util.Map;
29
import javax.json.JsonObject;
30
import org.apache.commons.lang3.StringUtils;
31
import org.gvsig.expressionevaluator.SymbolTable;
32
import org.gvsig.fmap.dal.feature.FeatureQuery;
33
import org.gvsig.fmap.dal.feature.FeatureStore;
34
import org.gvsig.report.lib.api.Report;
35
import org.gvsig.report.lib.api.ReportBuilder;
36
import org.gvsig.report.lib.api.ReportConfig;
37
import org.json.JSONObject;
38
import org.gvsig.report.lib.api.ReportDataSet;
39
import org.gvsig.report.lib.api.ReportManager;
40
import org.gvsig.report.lib.api.ReportServer;
41
import org.gvsig.report.lib.api.ReportServerConfig;
42
import org.gvsig.report.lib.api.ReportServices;
43
import org.gvsig.report.lib.api.ReportViewCapture;
44
import org.gvsig.report.lib.api.commands.CommandFactory;
45
import org.gvsig.report.lib.impl.commands.CaptureViewFactory;
46
import org.gvsig.report.lib.impl.commands.GetDatasetFactory;
47
import org.gvsig.report.lib.impl.commands.GetImageFactory;
48
import org.gvsig.report.lib.impl.commands.HelpFactory;
49
import org.gvsig.report.lib.impl.commands.ListDatasetsFactory;
50
import org.gvsig.report.lib.impl.commands.ListViewsFactory;
51
import org.gvsig.report.lib.impl.reportbuilder.DefaultReportBuilder;
52
import org.gvsig.tools.bookmarksandhistory.Bookmarks;
53
import org.gvsig.tools.bookmarksandhistory.History;
54
import org.gvsig.tools.bookmarksandhistory.impl.BaseBookmarks;
55
import org.gvsig.tools.bookmarksandhistory.impl.BaseHistory;
56
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
57

  
58
/**
59
 *
60
 * @author jjdelcerro
61
 */
62
public class DefaultReportManager implements ReportManager {
63

  
64
    private ReportServer defaultServer = null;
65

  
66
    private final Map<String, CommandFactory> commandFactories;
67
    private Bookmarks<ReportBuilder> userDefinedReportBookmarks;
68
    private History<ReportBuilder> userDefinedReportHistory;
69

  
70
    @SuppressWarnings("OverridableMethodCallInConstructor")
71
    public DefaultReportManager() {
72
        this.commandFactories = new LinkedHashMap<>();
73

  
74
        this.registerCommandFactory(new CaptureViewFactory());
75
        this.registerCommandFactory(new GetDatasetFactory());
76
        this.registerCommandFactory(new HelpFactory());
77
        this.registerCommandFactory(new ListDatasetsFactory());
78
        this.registerCommandFactory(new ListViewsFactory());
79
        this.registerCommandFactory(new GetImageFactory());
80

  
81
        this.userDefinedReportBookmarks = new BaseBookmarks<>();
82
        this.userDefinedReportHistory = new BaseHistory<>(20);
83
    }
84

  
85
    @Override
86
    public Collection<CommandFactory> getCommandFactories() {
87
        return commandFactories.values();
88
    }
89

  
90
    @Override
91
    public void registerCommandFactory(CommandFactory factory) {
92
        this.commandFactories.put(factory.getName(), factory);
93
    }
94

  
95
    @Override
96
    public ReportServer getDefaultServer() {
97
        return this.defaultServer;
98
    }
99

  
100
    @Override
101
    public void setDefaultServer(ReportServer server) {
102
        this.defaultServer = server;
103
    }
104

  
105
    @Override
106
    public ReportServer createServer(ReportServerConfig config) {
107
        DefaultReportServer server = new DefaultReportServer(this, config);
108
        if (this.defaultServer == null) {
109
            this.defaultServer = server;
110
        }
111
        return server;
112
    }
113

  
114
    @Override
115
    public ReportDataSet createDataSet(
116
            ReportServices services,
117
            String name,
118
            FeatureStore store
119
    ) {
120
        return new DefaultReportDataSet(services, name, store);
121
    }
122

  
123
    @Override
124
    public ReportServerConfig createServerConfig(ReportServices services) {
125
        DefaultReportServerConfig config = new DefaultReportServerConfig(this, services);
126
        return config;
127
    }
128

  
129
    @Override
130
    public ReportServerConfig createServerConfig(ReportServices services, String jsonConfig) {
131
        DefaultReportServerConfig config = new DefaultReportServerConfig(this, services);
132
        if (!StringUtils.isEmpty(jsonConfig)) {
133
            config.fromJSON(new JSONObject(jsonConfig));
134
        }
135
        return config;
136
    }
137

  
138
    @Override
139
    public ReportViewCapture createViewCapture(ReportServerConfig config) {
140
        return new DefaultReportViewCapture(config);
141
    }
142

  
143
    @Override
144
    public SymbolTable createReportSymbolTable() {
145
        return new ReportSymbolTable();
146
    }
147

  
148
    @Override
149
    public ReportBuilder createReportBuilder() {
150
        ReportBuilder r = new DefaultReportBuilder();
151
        return r;
152
    }
153

  
154
    @Override
155
    public Bookmarks<ReportBuilder> getUserDefinedReportBookmarks() {
156
        return this.userDefinedReportBookmarks;
157
    }
158

  
159
    @Override
160
    public History<ReportBuilder> getUserDefinedReportHistory() {
161
        return this.userDefinedReportHistory;
162
    }
163

  
164
    @Override
165
    public void setUserDefinedReportHistory(History<ReportBuilder> history) {
166
        this.userDefinedReportHistory = history;
167
    }
168

  
169
    @Override
170
    public void setUserDefinedReportBookmarks(Bookmarks<ReportBuilder> userDefinedReportBookmarks) {
171
        this.userDefinedReportBookmarks = userDefinedReportBookmarks;
172
    }
173

  
174
    @Override
175
    public ReportDataSet createDataSet(FeatureStore store) {
176
        return new DefaultReportDataSet(this.defaultServer.getServices(), store.getName(), store);
177
    }
178

  
179
    @Override
180
    public ReportDataSet createDataSet(FeatureStore store, FeatureQuery query) {
181
        return new DefaultReportDataSet(this.defaultServer.getServices(), store.getName(), store, query);
182
    }
183

  
184
    @Override
185
    public Report createReport(ReportConfig config) {
186
        DefaultReport r = new DefaultReport(config);
187
        return r;
188
    }
189

  
190
    @Override
191
    public ReportConfig createReportConfig() {
192
        DefaultReportConfig r = new DefaultReportConfig();
193
        return r;
194
    }
195

  
196
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/HttpHandler.java
1
package org.gvsig.report.lib.impl;
2

  
3
import java.io.IOException;
4
import java.net.URLDecoder;
5
import java.util.Locale;
6
import org.apache.commons.lang3.StringUtils;
7
import org.apache.http.HttpException;
8
import org.apache.http.HttpRequest;
9
import org.apache.http.HttpResponse;
10
import org.apache.http.HttpStatus;
11
import org.apache.http.MethodNotSupportedException;
12
import org.apache.http.entity.ByteArrayEntity;
13
import org.apache.http.entity.ContentType;
14
import org.apache.http.nio.entity.NStringEntity;
15
import org.apache.http.nio.protocol.BasicAsyncRequestConsumer;
16
import org.apache.http.nio.protocol.BasicAsyncResponseProducer;
17
import org.apache.http.nio.protocol.HttpAsyncExchange;
18
import org.apache.http.nio.protocol.HttpAsyncRequestConsumer;
19
import org.apache.http.nio.protocol.HttpAsyncRequestHandler;
20
import org.apache.http.protocol.HttpContext;
21
import static org.gvsig.report.lib.api.ReportServer.INFO;
22
import static org.gvsig.report.lib.api.ReportServer.WARN;
23
import org.gvsig.report.lib.api.commands.Command;
24
import org.slf4j.Logger;
25
import org.slf4j.LoggerFactory;
26

  
27

  
28
/**
29
 *
30
 * @author jjdelcerro
31
 */
32
public class HttpHandler implements HttpAsyncRequestHandler<HttpRequest> {
33

  
34
    private static final Logger LOG = LoggerFactory.getLogger(HttpHandler.class);
35
    
36
    private final DefaultReportServer server;
37

  
38
    public HttpHandler(DefaultReportServer server) {
39
        super();
40
        this.server = server;
41
    }
42

  
43
    @Override
44
    public HttpAsyncRequestConsumer<HttpRequest> processRequest(
45
            final HttpRequest request,
46
            final HttpContext context) {
47
        // Buffer request content in memory for simplicity
48
        return new BasicAsyncRequestConsumer();
49
    }
50

  
51
    @Override
52
    public void handle(
53
            final HttpRequest request,
54
            final HttpAsyncExchange httpexchange,
55
            final HttpContext context) throws HttpException, IOException {
56
        final HttpResponse response = httpexchange.getResponse();
57
        handleInternal(request, response, context);
58
        httpexchange.submitResponse(new BasicAsyncResponseProducer(response));
59
    }
60

  
61
    private void handleInternal(
62
            final HttpRequest request,
63
            final HttpResponse response,
64
            final HttpContext context) throws HttpException, IOException {
65

  
66
        final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
67
        if (!method.equals("GET")) {
68
            this.server.log(WARN, "Method not supported, Only GET supported.");
69
            throw new MethodNotSupportedException(method + " method not supported");
70
        }
71

  
72
        final String target = request.getRequestLine().getUri();
73
        final String line = URLDecoder.decode(target, "UTF-8");
74
        final String[] args = StringUtils.split(line, '/');
75
        final int argc = args.length -1;
76

  
77
        Command command = this.server.getCommand(args[0]);
78
        if( command == null) {
79
            this.server.log(WARN, "Command '"+line+"' not found.");
80
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
81
            final NStringEntity entity = new NStringEntity(
82
                    "<html><body><h1>Command " + line
83
                    + " not found</h1></body></html>",
84
                    ContentType.create("text/html", "UTF-8"));
85
            response.setEntity(entity);
86
            return;
87
        }
88
        if( !command.getNumArgs().contains(argc) ) {
89
            this.server.log(WARN, "Command '"+line+"', invalid number of arguments.");
90
            response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
91
            final NStringEntity entity = new NStringEntity(
92
                    "<html><body><h1>Number of arguments invalid in " + line
93
                    + "</h1></body></html>",
94
                    ContentType.create("text/html", "UTF-8"));
95
            response.setEntity(entity);
96
            return;
97
        }
98
        Object ret;
99
        try {
100
            ret = command.call(argc, args);
101
        } catch(Exception ex) {
102
            LOG.warn("Can't server command '"+line+"'.", ex);
103
            this.server.log(WARN, "Command '"+line+"', error "+ex.getMessage()+".");
104
            response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
105
            final NStringEntity entity = new NStringEntity(
106
                    "<html><body><h1>Error processing " + line
107
                    + "</h1><p>"+ex.toString()+"</p></body></html>",
108
                    ContentType.create("text/html", "UTF-8"));
109
            response.setEntity(entity);
110
            return;
111
        }
112
        if( ret == null ) {
113
            this.server.log(WARN, "Command '"+line+"' return null.");
114
            response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
115
            final NStringEntity entity = new NStringEntity(
116
                    "<html><body><h1>Process " + line
117
                    + " return null</h1></body></html>",
118
                    ContentType.create("text/html", "UTF-8"));
119
            response.setEntity(entity);
120
            return;
121
        }
122
        if( ret instanceof byte[] ) {
123
            response.setStatusCode(HttpStatus.SC_OK);
124
            final ByteArrayEntity entity = new ByteArrayEntity(
125
                    (byte[]) ret,
126
                    ContentType.create(command.getMimeType(), "UTF-8"));
127
            response.setEntity(entity);
128
            this.server.log(INFO, "Command '"+line+"' ok.");
129
            return;
130
        }
131
        response.setStatusCode(HttpStatus.SC_OK);
132
        final NStringEntity entity = new NStringEntity(
133
                ret.toString(),
134
                ContentType.create(command.getMimeType(), "UTF-8"));
135
        response.setEntity(entity);
136
        this.server.log(INFO, "Command '"+line+"' ok.");
137
    }
138

  
139
    
140

  
141

  
142

  
143

  
144
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/DefaultSelectionOfFeatures.java
1
package org.gvsig.report.lib.impl;
2

  
3
import java.util.ArrayList;
4
import java.util.Iterator;
5
import java.util.List;
6
import java.util.NoSuchElementException;
7
import org.apache.commons.collections.CollectionUtils;
8
import org.apache.commons.lang3.mutable.MutableInt;
9
import org.gvsig.fmap.dal.exception.DataException;
10
import org.gvsig.fmap.dal.feature.Feature;
11
import org.gvsig.fmap.dal.feature.FeatureReference;
12
import org.gvsig.fmap.dal.feature.FeatureSet;
13
import org.gvsig.report.lib.api.ReportDataSet.SelectionOfFeatures;
14
import org.gvsig.tools.ToolsLocator;
15
import org.gvsig.tools.exception.BaseException;
16
import org.gvsig.tools.task.SimpleTaskStatus;
17
import org.gvsig.tools.task.TaskStatusManager;
18
import org.gvsig.tools.visitor.VisitCanceledException;
19
import org.gvsig.tools.visitor.Visitable;
20
import org.gvsig.tools.visitor.Visitor;
21

  
22
/**
23
 *
24
 * @author jjdelcerro
25
 */
26
public class DefaultSelectionOfFeatures
27
        implements SelectionOfFeatures {
28

  
29
    private class FeatureReferenceIteratorToFeatureIteratorAdapter implements Iterator<Feature> {
30

  
31
        private final Iterator<FeatureReference> iterator;
32
        private int count;
33

  
34
        public FeatureReferenceIteratorToFeatureIteratorAdapter(Iterator<FeatureReference> iterator) {
35
            this.iterator = iterator;
36
            this.count = 0;
37
        }
38

  
39
        @Override
40
        public boolean hasNext() {
41
            int limit = dataSet.getLimit();
42
            if (limit < this.count) {
43
                return false;
44
            }
45
            return this.iterator.hasNext();
46
        }
47

  
48
        @Override
49
        public Feature next() {
50
            int limit = dataSet.getLimit();
51
            if (limit < this.count) {
52
                throw new NoSuchElementException();
53
            }
54
            this.count++;
55
            FeatureReference fr = this.iterator.next();
56
            try {
57
                return fr.getFeature();
58
            } catch (DataException ex) {
59
                throw new RuntimeException(ex);
60
            }
61
        }
62

  
63
    }
64

  
65
    private List<FeatureReference> references;
66
    private List<String> referenceCodes;
67
    private final DefaultReportDataSet dataSet;
68

  
69
    public DefaultSelectionOfFeatures(DefaultReportDataSet dataSet) {
70
        this.dataSet = dataSet;
71
        this.references = new ArrayList<>();
72
        this.referenceCodes = null;
73
    }
74

  
75
    private void resolveReferenceCodes() {
76
        if (this.referenceCodes == null) {
77
            return;
78
        }
79
        for (String referenceCode : this.referenceCodes) {
80
            FeatureReference reference = this.dataSet.getStore().getFeatureReference(referenceCode);
81
            this.references.add(reference);
82
        }
83
        this.referenceCodes = null;
84
    }
85

  
86
    @Override
87
    public Feature get64(long pos) {
88
        if (this.referenceCodes != null) {
89
            this.resolveReferenceCodes();
90
        }
91
        int limit = this.dataSet.getLimit();
92
        if (limit > 0 && pos > limit) {
93
            throw new ArrayIndexOutOfBoundsException((int) pos);
94
        }
95
        try {
96
            FeatureReference reference = this.references.get((int) pos);
97
            return reference.getFeature();
98
        } catch (DataException ex) {
99
            throw new RuntimeException("Can't retrieve feature from reference.", ex);
100
        }
101
    }
102

  
103
    public FeatureReference getReference(int pos) {
104
        if (this.referenceCodes != null) {
105
            this.resolveReferenceCodes();
106
        }
107
        FeatureReference reference = this.references.get(pos);
108
        return reference;
109
    }
110

  
111
    
112
    @Override
113
    public long size64() {
114
        int limit = this.dataSet.getLimit();
115
        int size;
116
        if (this.referenceCodes == null) {
117
            size = this.references.size();
118
        } else {
119
            size = this.referenceCodes.size();
120
        }
121
        if (limit > 0 && limit < size) {
122
            size = limit;
123
        }
124
        return size;
125
    }
126

  
127
    @Override
128
    public boolean isEmpty() {
129
        if (this.referenceCodes == null) {
130
            return this.references.isEmpty();
131
        }
132
        return this.referenceCodes.isEmpty();
133
    }
134

  
135
    @Override
136
    public Iterator<Feature> iterator() {
137
        if (this.referenceCodes != null) {
138
            this.resolveReferenceCodes();
139
        }
140
        return new FeatureReferenceIteratorToFeatureIteratorAdapter(this.references.iterator());
141
    }
142

  
143
    @Override
144
    public void accept(Visitor visitor) throws BaseException {
145
        if (this.referenceCodes != null) {
146
            this.resolveReferenceCodes();
147
        }
148
        int count = 0;
149
        int limit = this.dataSet.getLimit();
150
        for (FeatureReference reference : this.references) {
151
            try {
152
                if( limit>0 ) {
153
                    if( count >= limit ) {
154
                        break;
155
                    }
156
                    count++;
157
                }
158
                visitor.visit(reference.getFeature());
159
            } catch (VisitCanceledException ex) {
160
                break;
161
            } catch (Exception ex) {
162

  
163
            }
164
        }
165
    }
166

  
167
    @Override
168
    public void clear() {
169
        this.referenceCodes = null;
170
        this.references = new ArrayList<>();
171
    }
172

  
173
    @Override
174
    public void add(Feature feature) {
175
        this.add(feature.getReference());
176
    }
177

  
178
    @Override
179
    public void add(FeatureReference reference) {
180
        if (this.referenceCodes != null) {
181
            this.resolveReferenceCodes();
182
        }
183
        this.references.add(reference);
184
    }
185

  
186
    @Override
187
    public void add(String referenceCode) {
188
        if (CollectionUtils.isEmpty(this.references)) {
189
            if (this.referenceCodes == null) {
190
                this.referenceCodes = new ArrayList<>();
191
            }
192
            this.referenceCodes.add(referenceCode);
193
        } else {
194
            FeatureReference reference = this.dataSet.getStore().getFeatureReference(referenceCode);
195
            this.references.add(reference);
196
        }
197

  
198
    }
199

  
200
    @Override
201
    public void addAll(Iterator<Feature> features) {
202
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
203
        SimpleTaskStatus status = manager.createDefaultSimpleTaskStatus("DataSet");
204
        status.setIndeterminate();
205
        status.setAutoremove(true);
206
        status.add();
207
        int n = 0;
208
        try {
209
            if (this.referenceCodes != null) {
210
                this.resolveReferenceCodes();
211
            }
212
            while (features.hasNext()) {
213
                Feature f = features.next();
214
                this.references.add(f.getReference());
215
                status.setCurValue(n++);
216
            }
217
        } finally {
218
            status.terminate();
219
        }
220
    }
221

  
222
    @Override
223
    public void addAll(Visitable features) {
224
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
225
        final SimpleTaskStatus status = manager.createDefaultSimpleTaskStatus("DataSet");
226
        status.setIndeterminate();
227
        status.setAutoremove(true);
228
        status.add();
229
        final MutableInt n = new MutableInt(0);
230
        try {
231
            if (this.referenceCodes != null) {
232
                this.resolveReferenceCodes();
233
            }
234
            features.accept(new Visitor() {
235
                @Override
236
                public void visit(Object obj) throws VisitCanceledException, BaseException {
237
                    Feature f = (Feature) obj;
238
                    references.add(f.getReference());
239
                    status.setCurValue(n.intValue());
240
                    n.increment();
241
                }
242
            });
243
        } catch (BaseException ex) {
244
            throw new RuntimeException("Can't set features to dataset", ex);
245
        } finally {
246
            status.terminate();
247
        }
248

  
249
    }
250

  
251
    @Override
252
    public void addStoreSelection() {
253
        try {
254
            FeatureSet selection = this.dataSet.getStore().getFeatureSelection();
255
            this.addAll(selection);
256
        } catch (DataException ex) {
257
            throw new RuntimeException("Can't set features from current selection.", ex);
258
        }
259
    }
260

  
261
    @Override
262
    public List<Feature> toList() {
263
        List<Feature> adapter = new UnmodifiableBasicList64ToListAdapter<>(this);                
264
        return adapter;
265
    }
266

  
267
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/JRFeatureStoreDataSource.java
1
package org.gvsig.report.lib.impl;
2

  
3
import ar.com.fdvs.dj.domain.CustomExpression;
4
import java.util.HashMap;
5
import java.util.Map;
6
import java.util.Objects;
7
import net.sf.jasperreports.engine.JREmptyDataSource;
8
import net.sf.jasperreports.engine.JRException;
9
import net.sf.jasperreports.engine.JRField;
10
import net.sf.jasperreports.engine.JRRewindableDataSource;
11
import net.sf.jasperreports.engine.JasperReportsContext;
12
import static net.sf.jasperreports.engine.data.JRTableModelDataSource.EXCEPTION_MESSAGE_KEY_UNKNOWN_COLUMN_NAME;
13
import net.sf.jasperreports.engine.data.JsonData;
14
import org.apache.commons.lang3.StringUtils;
15
import org.gvsig.expressionevaluator.Expression;
16
import org.gvsig.expressionevaluator.ExpressionUtils;
17
import org.gvsig.fmap.dal.StoresRepository;
18
import org.gvsig.fmap.dal.feature.Feature;
19
import org.gvsig.fmap.dal.feature.FeatureStore;
20
import org.gvsig.tools.ToolsLocator;
21
import org.gvsig.tools.dataTypes.CoercionException;
22
import org.gvsig.tools.dataTypes.DataType;
23
import org.gvsig.tools.dataTypes.DataTypesManager;
24
import org.gvsig.tools.dataTypes.Coercion;
25
import org.gvsig.tools.dataTypes.CoercionContext;
26
import org.gvsig.tools.util.GetItem;
27
import org.gvsig.tools.util.GetItem64;
28
import org.gvsig.tools.util.Size;
29
import org.gvsig.tools.util.Size64;
30
import org.gvsig.tools.util.UnmodifiableBasicList64;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

  
34
/**
35
 *
36
 * @author jjdelcerro
37
 */
38
@SuppressWarnings("UseSpecificCatch")
39
public class JRFeatureStoreDataSource
40
        implements JRRewindableDataSource, JsonData, Size64, Size, GetItem<Feature>, GetItem64<Feature> {
41

  
42
    protected static final Logger LOGGER = LoggerFactory.getLogger(JRFeatureStoreDataSource.class);
43

  
44
    private UnmodifiableBasicList64<Feature> features;
45
    private long index;
46
    private final StoresRepository storesRepository;
47
    private final JasperReportsContext context;
48
    protected String name;
49
    private Map<String, Coercion> coercions;
50

  
51
    public JRFeatureStoreDataSource(JasperReportsContext context, UnmodifiableBasicList64<Feature> features, StoresRepository storesRepository) {
52
        this.context = context;
53
        this.features = features;
54
        this.storesRepository = storesRepository;
55
        this.index = -1;
56
        this.name = "<unknown>";
57
        this.coercions = new HashMap<>();
58

  
59
        LOGGER.info("DataSource(" + this.name + ")");
60
    }
61

  
62
    public JRFeatureStoreDataSource(JasperReportsContext context, FeatureStore store, Expression filter) {
63
        this(
64
                context,
65
                (UnmodifiableBasicList64<Feature>) store.getFeatures(filter),
66
                store.getStoresRepository()
67
        );
68
        this.name = store.getName();
69
//        System.out.println("DataSurce("+this.name+")");
70
    }
71

  
72
    @Override
73
    public boolean next() throws JRException {
74
        this.index++;
75
        boolean n = this.index < this.features.size64();
76
//        System.out.println("DataSurce("+this.name+") ["+this.index+"] next() return "+n+".");
77
        return n;
78
    }
79

  
80
    @Override
81
    public Object getFieldValue(JRField jrField) throws JRException {
82
        String fieldName = jrField.getName();
83
//        System.out.println("DataSurce("+this.name+") ["+this.index+"] getFieldValue("+fieldName+").");
84
        try {
85
            Feature feature = this.features.get64(index);
86
            Object value;
87
            if (fieldName.startsWith("COLUMN_")) {
88
                value = feature.get(Integer.parseInt(fieldName.substring(7)));
89
            } else if (fieldName.endsWith("@label")) {
90
                fieldName = StringUtils.removeEnd(fieldName, "@label");
91
                value = feature.getLabelOfValue(fieldName);
92
            } else {
93
                value = feature.get(fieldName);
94
            }
95
            if (jrField.getValueClass() != null && !jrField.getValueClass().isInstance(value)) {
96
                Coercion coercion = this.coercions.get(fieldName);
97
                if (coercion == null) {
98
                    DataTypesManager dataTypesManager = ToolsLocator.getDataTypesManager();
99
                    DataType dataType = dataTypesManager.getDataType(jrField.getValueClass());
100
                    if (dataType == null) {
101
                        coercion = new DummyCoercion();
102
                    } else {
103
                        coercion = dataType.getCoercion();
104
                    }
105
                    this.coercions.put(fieldName, coercion);
106
                }
107
                try {
108
                    value = coercion.coerce(value);
109
                } catch (CoercionException ex) {
110
                }
111
            }
112
            return value;
113
        } catch (Exception ex) {
114
            if (CustomExpression.class.isAssignableFrom(jrField.getValueClass())) {
115
                return null;
116
            }
117
            throw new JRException(
118
                    EXCEPTION_MESSAGE_KEY_UNKNOWN_COLUMN_NAME,
119
                    new Object[]{fieldName},
120
                    ex
121
            );
122
        }
123
    }
124

  
125
    @Override
126
    public void moveFirst() throws JRException {
127
        this.index = -1;
128
//        System.out.println("DataSurce("+this.name+") ["+this.index+"] moveFirst().");
129
    }
130

  
131
    @Override
132
    public long size64() {
133
        return this.features.size64();
134
    }
135

  
136
    @Override
137
    public int size() {
138
        long sz = this.features.size64();
139
        if (sz > Integer.MAX_VALUE) {
140
            return Integer.MAX_VALUE;
141
        }
142
        return (int) sz;
143
    }
144

  
145
    @Override
146
    public Feature get(int position) {
147
        return this.features.get64(position);
148
    }
149

  
150
    @Override
151
    public Feature get64(long position) {
152
        return this.features.get64(position);
153
    }
154

  
155
    @Override
156
    public JsonData subDataSource() throws JRException {
157
        return new JRFeatureStoreDataSource(this.context, this.features, this.storesRepository);
158
    }
159

  
160
    @Override
161
    public JsonData subDataSource(String selectExpression) throws JRException {
162
        LOGGER.info("DataSurce(" + this.name + ").subDataSource(" + Objects.toString(selectExpression, "null") + ").");
163
        if (StringUtils.isBlank(selectExpression)) {
164
            return new JREmptyJSonData(1, this.storesRepository);
165
        }
166
        String storeName;
167
        Expression filter = null;
168

  
169
        selectExpression = selectExpression.trim();
170
        if (selectExpression.toUpperCase().startsWith("SELECT ")) {
171
            selectExpression = selectExpression.substring(7).trim();
172
            if (selectExpression.startsWith("* ")) {
173
                selectExpression = selectExpression.substring(2).trim();
174
            }
175
            if (selectExpression.toUpperCase().startsWith("FROM ")) {
176
                selectExpression = selectExpression.substring(5).trim();
177
            }
178
        }
179
        int n = selectExpression.indexOf(" WHERE ");
180
        if (n < 0) {
181
            storeName = selectExpression.trim();
182
        } else {
183
            storeName = selectExpression.substring(0, n).trim();
184
            filter = ExpressionUtils.createExpression(selectExpression.substring(n + 6).trim());
185
        }
186
        if (this.storesRepository.get(storeName) == null) {
187
            return new JREmptyJSonData(1, this.storesRepository);
188
        }
189
        JRFeatureStoreDataSource x = new JRFeatureStoreDataSource(
190
                this.context,
191
                (FeatureStore) this.storesRepository.getStore(storeName),
192
                filter
193
        );
194
        return x;
195
    }
196

  
197
    private class JREmptyJSonData extends JREmptyDataSource implements JsonData {
198

  
199
        JREmptyJSonData(int rows, StoresRepository storesRepository) {
200
            super(rows);
201
        }
202

  
203
        @Override
204
        public JsonData subDataSource() throws JRException {
205
            return JRFeatureStoreDataSource.this.subDataSource();
206
        }
207

  
208
        @Override
209
        public JsonData subDataSource(String selectExpression) throws JRException {
210
            LOGGER.info("DataSurce(<Empty>) subDataSource(" + Objects.toString(selectExpression, "null") + ")");
211
            return JRFeatureStoreDataSource.this.subDataSource(selectExpression);
212
        }
213
    }
214

  
215
    private static class DummyCoercion implements Coercion {
216

  
217
        @Override
218
        public Object coerce(Object o) throws CoercionException {
219
            return o;
220
        }
221

  
222
        @Override
223
        public Object coerce(Object value, CoercionContext context) throws CoercionException {
224
            return value;
225
        }
226

  
227
    }
228
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/DefaultReport.java
1
package org.gvsig.report.lib.impl;
2

  
3
import ar.com.fdvs.dj.core.DynamicJasperHelper;
4
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
5
import ar.com.fdvs.dj.core.layout.ExtendedListLayoutManager;
6
import ar.com.fdvs.dj.core.layout.LayoutManager;
7
import ar.com.fdvs.dj.core.layout.ListLayoutManager;
8
import ar.com.fdvs.dj.domain.DynamicReport;
9
import java.io.File;
10
import java.io.InputStream;
11
import java.util.ArrayList;
12
import java.util.Collections;
13
import java.util.HashMap;
14
import java.util.List;
15
import java.util.Map;
16
import net.sf.jasperreports.engine.JRException;
17
import net.sf.jasperreports.engine.JasperExportManager;
18
import net.sf.jasperreports.engine.JasperPrint;
19
import net.sf.jasperreports.engine.JasperReport;
20
import net.sf.jasperreports.engine.SimpleJasperReportsContext;
21
import net.sf.jasperreports.engine.fill.FillListener;
22
import net.sf.jasperreports.engine.fill.JRFiller;
23
import net.sf.jasperreports.engine.fill.ReportFiller;
24
import net.sf.jasperreports.engine.util.JRLoader;
25
import net.sf.jasperreports.repo.FileRepositoryPersistenceServiceFactory;
26
import net.sf.jasperreports.repo.PersistenceServiceFactory;
27
import net.sf.jasperreports.repo.RepositoryService;
28
import org.apache.commons.io.IOUtils;
29
import org.apache.commons.lang3.StringUtils;
30
import org.apache.commons.lang3.tuple.ImmutablePair;
31
import org.apache.commons.lang3.tuple.Pair;
32
import org.gvsig.expressionevaluator.Expression;
33
import org.gvsig.expressionevaluator.ExpressionBuilder;
34
import org.gvsig.expressionevaluator.ExpressionUtils;
35
import org.gvsig.fmap.dal.feature.Feature;
36
import org.gvsig.fmap.dal.feature.FeatureStore;
37
import org.gvsig.report.lib.api.Report;
38
import static org.gvsig.report.lib.api.ReportBuilder.LAYOUT_CLASSIC;
39
import static org.gvsig.report.lib.api.ReportBuilder.LAYOUT_EXTENDEDLIST;
40
import static org.gvsig.report.lib.api.ReportBuilder.LAYOUT_LIST;
41
import org.gvsig.report.lib.api.ReportConfig;
42
import org.gvsig.tools.task.SimpleTaskStatus;
43
import org.gvsig.tools.util.UnmodifiableBasicList64;
44
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
46

  
47
/**
48
 *
49
 * @author jjdelcerro
50
 */
51
@SuppressWarnings("UseSpecificCatch")
52
public class DefaultReport implements Report {
53

  
54
    private static final Logger LOG = LoggerFactory.getLogger(DefaultReport.class);
55

  
56
    private final ReportConfig config;
57
    private DynamicReport dynamicReport;
58
    private SimpleJasperReportsContext jasperContext;
59

  
60
    public DefaultReport(ReportConfig config) {
61
        this.config = config;
62
        this.dynamicReport = null;
63
        this.jasperContext = null;
64
    }
65

  
66
    public DefaultReport(ReportConfig config, DynamicReport dynamicReport) {
67
        this(config);
68
        this.dynamicReport = dynamicReport;
69
    }
70

  
71
    @Override
72
    public ReportConfig getConfig() {
73
        return this.config;
74
    }
75

  
76
    protected LayoutManager getLayoutManager() {
77
        switch (this.config.getLayoutManager()) {
78
            case LAYOUT_LIST:
79
                return new ListLayoutManager();
80
            case LAYOUT_EXTENDEDLIST:
81
                return new ExtendedListLayoutManager();
82
            case LAYOUT_CLASSIC:
83
            default:
84
                return new ClassicLayoutManager();
85
        }
86

  
87
    }
88

  
89
    @Override
90
    public String getName() {
91
        return this.config.getName();
92
    }
93

  
94
    private SimpleJasperReportsContext getJasperContext() {
95
        if (this.jasperContext == null) {
96
            this.jasperContext = new SimpleJasperReportsContext();
97
        }
98
        return this.jasperContext;
99
    }
100

  
101
    private JasperReport loadJasperReport(InputStream is) {
102
        JasperReport jasper = null;
103
        try {
104
            SimpleJasperReportsContext context = this.getJasperContext();
105
            ResourcesRepositoryService resourcesRepository = new ResourcesRepositoryService(
106
                    this.config.getResources()
107
            );
108
            context.setExtensions(
109
                    RepositoryService.class,
110
                    Collections.singletonList(resourcesRepository)
111
            );
112
            context.setExtensions(
113
                    PersistenceServiceFactory.class,
114
                    Collections.singletonList(
115
                            FileRepositoryPersistenceServiceFactory.getInstance()
116
                    )
117
            );
118
            jasper = (JasperReport) JRLoader.loadObject(is);
119

  
120
        } catch (IllegalStateException ex) {
121
            throw ex;
122
        } catch (Exception ex) {
123
            LOG.warn("Can't load report from config '" + config.toString() + "'.", ex);
124
        }
125

  
126
        return jasper; //this.dynamicReport; //TODO
127
    }
128

  
129
    @Override
130
    public Expression getPreparedFilter(Expression filter) {
131
        String prefix = this.config.getFilterFieldPrefix();
132
        if (StringUtils.isBlank(prefix)) {
133
            return filter;
134
        }
135
        final ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
136
        final List<Pair<ExpressionBuilder.Value, ExpressionBuilder.Value>> replaces = new ArrayList<>();
137

  
138
        ExpressionBuilder.Value filterValue = filter.getCode().toValue();
139
        filterValue.accept(new ExpressionBuilder.Visitor() {
140
            @Override
141
            public void visit(ExpressionBuilder.Visitable value0) {
142
                ExpressionBuilder.Variable value = (ExpressionBuilder.Variable) value0;
143
                ExpressionBuilder.Variable newvalue = builder.variable(prefix + value.name());
144
                replaces.add(new ImmutablePair(value, newvalue));
145
            }
146
        }, new ExpressionBuilder.ClassVisitorFilter(ExpressionBuilder.Variable.class));
147

  
148
        for (Pair<ExpressionBuilder.Value, ExpressionBuilder.Value> replace : replaces) {
149
            filterValue.replace(replace.getLeft(), replace.getRight());
150
        }
151
        return ExpressionUtils.createExpression(filterValue.toString());
152
    }
153

  
154
    @Override
155
    public synchronized Object generateReport(final SimpleTaskStatus status, Expression filter) {
156
        FeatureStore store = this.config.getDataSet().getStore();
157
        filter = this.getPreparedFilter(filter);
158
        UnmodifiableBasicList64<Feature> features = (UnmodifiableBasicList64<Feature>) store.getFeatures(filter);
159
        return this.generateReport(status, features);
160
    }
161

  
162
    @Override
163
    public synchronized Object generateReport(final SimpleTaskStatus status, UnmodifiableBasicList64<Feature> features) {
164
        InputStream is = null;
165
        try {
166
            Map parameters = new HashMap();
167

  
168
            status.message("Preparing data");
169
            FeatureStore store = this.config.getDataSet().getStore();
170
            SimpleJasperReportsContext context = this.getJasperContext();
171
            JRFeatureStoreDataSource dataSource = new JRFeatureStoreDataSource(
172
                    context,
173
                    features,
174
                    store.getStoresRepository()
175
            );
176
            final long records = dataSource.size64();
177

  
178
            status.message("Loading template");
179
            JasperReport jr; // = this.dynamicReport;
180
            if (dynamicReport == null) {
181
                is = this.config.getReportTemplateAsStream();
182
                if (is == null) {
183
                    throw new RuntimeException("Can't access to the input stream associated to the repor (" + this.config.toString() + ").");
184
                }
185
                jr = this.loadJasperReport(is);
186
            } else {
187
                jr = DynamicJasperHelper.generateJasperReport(
188
                        dynamicReport,
189
                        this.getLayoutManager(),
190
                        parameters);
191
            }
192
            ReportFiller filler = JRFiller.createReportFiller(context, jr);
193
            filler.addFillListener(new FillListener() {
194
                @Override
195
                public void pageGenerated(JasperPrint jasperPrint, int pageIndex) {
196
//                    LOG.info("Pagina generada " + pageIndex);
197
                    status.message("Created page " + pageIndex + " (records " + records + ")");
198
                    if (pageIndex > 100000) {
199
                        throw new RuntimeException("Too many pages in report.");
200
                    }
201
                }
202

  
203
                @Override
204
                public void pageUpdated(JasperPrint jasperPrint, int pageIndex) {
205
//                    LOG.info("Pagina actualizada " + pageIndex);
206
                }
207
            });
208
            status.message("Filling template");
209
            JasperPrint jasperPrint = filler.fill(
210
                    parameters,
211
                    dataSource
212
            );
213

  
214
            return jasperPrint;
215

  
216
        } catch (IllegalStateException ex) {
217
            throw ex;
218

  
219
        } catch (Exception ex) {
220
            throw new RuntimeException("Can't generate report.", ex);
221

  
222
        } finally {
223
            IOUtils.closeQuietly(is);
224
        }
225
    }
226

  
227
    @Override
228
    public File generatePDF(SimpleTaskStatus status, Expression filter, File pdf) {
229

  
230
        try {
231
            JasperPrint jasperPrint = (JasperPrint) this.generateReport(status, filter);
232
            JasperExportManager.exportReportToPdfFile(jasperPrint, pdf.getAbsolutePath());
233
            return pdf;
234
        } catch (JRException ex) {
235
            throw new RuntimeException("Can't export to PDF.", ex);
236
        }
237
    }
238

  
239
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/GetDataset.java
1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.report.lib.impl.commands;
7

  
8
import org.gvsig.report.lib.api.commands.AbstractCommand;
9
import org.apache.commons.lang3.BooleanUtils;
10
import org.apache.commons.lang3.math.NumberUtils;
11
import org.apache.commons.lang3.mutable.MutableBoolean;
12
import org.apache.commons.lang3.mutable.MutableInt;
13
import org.gvsig.fmap.dal.DataTypes;
14
import org.gvsig.fmap.dal.feature.Feature;
15
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
16
import org.gvsig.fmap.dal.feature.FeatureType;
17
import org.gvsig.tools.exception.BaseException;
18
import org.gvsig.tools.visitor.VisitCanceledException;
19
import org.gvsig.tools.visitor.Visitor;
20
import org.json.JSONArray;
21
import org.json.JSONObject;
22
import org.gvsig.report.lib.api.ReportDataSet;
23
import org.gvsig.report.lib.api.ReportServer;
24
import org.gvsig.report.lib.api.commands.CommandFactory;
25

  
26
/**
27
 *
28
 * @author jjdelcerro
29
 */
30
public class GetDataset extends AbstractCommand {
31
    
32
    public GetDataset(CommandFactory factory, ReportServer server) {
33
        super(factory,server);
34
    }
35

  
36
    @Override
37
    public Object call(int argc, String[] args) {
38
        final MutableBoolean withGeom = new MutableBoolean(false);
39
        final MutableInt limit = new MutableInt(-1);
40
        String filter = null;
41
        boolean ascending = true;
42
        String orderFields = null;
43
        
44
        int n = 1;
45
        String datasetName = args[n++];
46
        while( n<args.length ) {
47
            String option = args[n++].toLowerCase();
48
            switch(option) {
49
                case "withgeom":
50
                    withGeom.setTrue();
51
                    break;
52
                case "limit":
53
                    limit.setValue(NumberUtils.toInt(args[n++], -1));
54
                    break;
55
                case "filter":
56
                    filter = args[n++];
57
                    break;
58
                case "order":
59
                    orderFields = args[n++];
60
                    ascending = BooleanUtils.toBoolean(args[n++].toLowerCase(), "asc", "desc");
61
                    break;
62
                default:
63
                    throw new IllegalArgumentException("Option '"+option+"' not supported.");
64
            }
65
        }
66
        
67
        ReportDataSet dataset = this.getConfig().getDataset(datasetName);
68
        if (dataset == null) {
69
            throw new IllegalArgumentException("Dataset '" + datasetName + "' not exists.");
70
        }
71
        final MutableInt count = new MutableInt(0);
72
        final JSONArray json = new JSONArray();
73
        
74
        dataset.accept(new Visitor() {
75
            @Override
76
            public void visit(Object o) throws VisitCanceledException, BaseException {
77
                Feature f = (Feature) o;
78
                JSONObject fjson = new JSONObject();
79
                FeatureType ft = f.getType();
80
                for (FeatureAttributeDescriptor desc : ft) {
81
                    if (desc.isComputed()) {
82
                        continue;
83
                    }
84
                    if (desc.getType() == DataTypes.GEOMETRY) {
85
                        if ( withGeom.isTrue() ) {
86
                            fjson.put(desc.getName(), f.getGeometry(desc.getIndex()).convertToWKT());
87
                        }
88
                    } else {
89
                        switch(desc.getType()) {
90
                            case DataTypes.BOOLEAN:
91
                                fjson.put(desc.getName(), f.getBoolean(desc.getIndex()));
92
                                break;
93
                            case DataTypes.BYTE:
94
                                fjson.put(desc.getName(), f.getByte(desc.getIndex()));
95
                                break;
96
                            case DataTypes.INT:
97
                                fjson.put(desc.getName(), f.getInt(desc.getIndex()));
98
                                break;
99
                            case DataTypes.LONG:
100
                                fjson.put(desc.getName(), f.getLong(desc.getIndex()));
101
                                break;
102
                            case DataTypes.DOUBLE:
103
                                fjson.put(desc.getName(), f.getDouble(desc.getIndex()));
104
                                break;
105
                            case DataTypes.FLOAT:
106
                                fjson.put(desc.getName(), f.getFloat(desc.getIndex()));
107
                                break;
108
                            case DataTypes.DATE:
109
                                fjson.put(desc.getName(), f.getDate(desc.getIndex()));
110
                                break;
111
                            default:
112
                                fjson.put(desc.getName(), f.get(desc.getIndex()));
113
                        }
114
                    }
115
                    if( desc.getAvailableValues()!=null ) {
116
                        fjson.put(desc.getName()+"@label", f.getLabelOfValue(desc.getName()));
117
                    }
118
                }
119
                json.put(fjson);
120
                
121
                count.increment();
122
                if( limit.intValue()>0 &&  count.intValue()>=limit.intValue() ) {
123
                    throw new VisitCanceledException();
124
                }
125
            }
126
        }, filter, orderFields, ascending);
127
        return json.toString();
128
    }
129
    
130
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/CaptureViewFactory.java
1

  
2
package org.gvsig.report.lib.impl.commands;
3

  
4
import org.apache.commons.lang3.Range;
5
import org.gvsig.report.lib.api.ReportServer;
6
import org.gvsig.report.lib.api.commands.AbstractCommandFactory;
7
import org.gvsig.report.lib.api.commands.Command;
8

  
9
/**
10
 *
11
 * @author jjdelcerro
12
 */
13
public class CaptureViewFactory extends AbstractCommandFactory {
14

  
15
    public CaptureViewFactory() {
16
        super(
17
            "captureview", 
18
            Range.between(1, 100), 
19
            "image/png",
20
            "captureview/<viename>\n\n" +
21
                "Options:\n" +
22
                "  zoom/<datasetname>/<filterexpression>\n" +    
23
                "  center/<datasetname>/<filterexpression>\n" +    
24
                "  select/<datasetname>/<filterexpression>\n" +    
25
                "  deselect/<datasetname>\n" +    
26
                "  margins/<integer>\n" +    
27
                "  width/<integer>\n" +    
28
                "  height/<integer>\n\n" +    
29
                "Retrieve the image of specified view with <viewname> as a png.\n" +
30
                "select and deselect options can be specified more than once.\n" 
31
        );        
32
    }
33
    
34
    @Override
35
    public Command create(ReportServer server) {
36
        return new CaptureView(this, server);
37
    }
38
    
39
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/Help.java
1

  
2
package org.gvsig.report.lib.impl.commands;
3

  
4
import org.gvsig.report.lib.api.commands.Command;
5
import org.gvsig.report.lib.api.commands.AbstractCommand;
6
import java.util.Map;
7
import org.apache.commons.lang3.StringUtils;
8
import org.gvsig.htmlbuilder.HTMLBuilder;
9
import org.gvsig.htmlbuilder.HTMLBuilder.HTMLComplexElement;
10
import org.gvsig.report.lib.api.ReportServer;
11
import org.gvsig.report.lib.api.commands.CommandFactory;
12
import org.gvsig.tools.util.ToolsUtilLocator;
13
import org.json.JSONArray;
14
import org.json.JSONObject;
15

  
16
/**
17
 *
18
 * @author jjdelcerro
19
 */
20
public class Help extends AbstractCommand {
21

  
22
    public Help(CommandFactory factory,  ReportServer server) {
23
        super(factory,server);
24
    }
25

  
26
    
27
    @Override
28
    public Object call(int argc, String[] args) {
29
        Map<String, Command> commands = this.getServer().getCommands();
30
        if( argc>0 && StringUtils.equalsIgnoreCase("asjson", args[1]) ) {
31
            JSONArray json = new JSONArray();
32
            for (Command command : commands.values()) {
33
                json.put(this.getCommandDescription(command));
34
            }
35
            return json.toString();
36
        } else {
37
            HTMLBuilder builder = ToolsUtilLocator.getToolsUtilManager().createHTMLBuilder();
38
            HTMLComplexElement table = builder.table(
39
                0,1,4,
40
                builder.thead(
41
                    builder.tr(
42
                            builder.th("Return type"),
43
                            builder.th("Name"),
44
                            builder.th("Description")
45
                    )
46
                )
47
            );
48
            
49
            for (Command command : commands.values()) {
50
                HTMLComplexElement tr = builder.tr(HTMLBuilder.valign_top).contents(
51
                        builder.td(command.getMimeType()),
52
                        builder.td(command.getName()),
53
                        builder.td(
54
                                builder.plainWithNl(command.getDescription()+"\n\n")
55
                        )
56
                );
57
                table.contents(tr);
58
            }
59
            return table.toHTML();
60
        }
61
    }
62
    
63
    public JSONObject getCommandDescription(Command command) {
64
        JSONObject json = new JSONObject();
65
        json.put("Name", command.getName());
66
        json.put("NumArgs", command.getNumArgs().toString());
67
        json.put("MimeType", StringUtils.defaultString(command.getMimeType()));
68
        json.put("Description", StringUtils.defaultString(command.getDescription()));
69
        return json;
70
    }
71
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/ListViews.java
1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.report.lib.impl.commands;
7

  
8
import org.gvsig.report.lib.api.commands.AbstractCommand;
9
import org.gvsig.report.lib.api.ReportServer;
10
import org.json.JSONArray;
11
import org.gvsig.report.lib.api.commands.CommandFactory;
12

  
13
/**
14
 *
15
 * @author jjdelcerro
16
 */
17
public class ListViews extends AbstractCommand {
18
    
19
    public ListViews(CommandFactory factory, ReportServer server) {
20
        super(factory, server);
21
    }
22

  
23
    @Override
24
    public Object call(int argc, String[] args) {
25
        JSONArray json = new JSONArray();
26
        
27
        for (String viewName : this.getServices().getViewNames() ) {
28
            json.put(viewName);
29
        }
30
        return json.toString();
31
    }
32
    
33
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/GetImageFactory.java
1

  
2
package org.gvsig.report.lib.impl.commands;
3

  
4
import org.apache.commons.lang3.Range;
5
import org.gvsig.report.lib.api.ReportServer;
6
import org.gvsig.report.lib.api.commands.AbstractCommandFactory;
7
import org.gvsig.report.lib.api.commands.Command;
8

  
9
/**
10
 *
11
 * @author jjdelcerro
12
 */
13
public class GetImageFactory extends AbstractCommandFactory {
14

  
15
    private static GetImageFactory INSTANCE = null;
16
    
17
    public static GetImageFactory getInstance() {
18
      if( INSTANCE==null ) {
19
        INSTANCE = new GetImageFactory();
20
      }
21
      return INSTANCE;
22
    } 
23
    
24
    public GetImageFactory() {
25
        super(
26
            "image", 
27
            Range.between(1, 8),
28
            "image/png",
29
            "image/<datasetname>/column/<columnname>\n" + 
30
                "image/<datasetname>/filter/<expression>\n" + 
31
                "image/<datasetname>/order/<fields>\n\n" + 
32
                "Retrieve the value of column as a image.\n" + 
33
                "If an order is specified, it accepts two more parameters. The first\n" +
34
                "is the list of fields by which to sort separated by commas."
35
        );
36
    }
37
        
38
    @Override
39
    public Command create(ReportServer server) {
40
        return new GetImage(this, server);
41
    }
42
    
43
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/ListDatasetsFactory.java
1

  
2
package org.gvsig.report.lib.impl.commands;
3

  
4
import org.apache.commons.lang3.Range;
5
import org.gvsig.report.lib.api.ReportServer;
6
import org.gvsig.report.lib.api.commands.AbstractCommandFactory;
7
import org.gvsig.report.lib.api.commands.Command;
8

  
9
/**
10
 *
11
 * @author jjdelcerro
12
 */
13
public class ListDatasetsFactory extends AbstractCommandFactory {
14

  
15
    public ListDatasetsFactory() {
16
        super(
17
            "datasets", 
18
            Range.is(0),
19
            "application/json",
20
            "datasets\n\nList the datasets exposeds by the application.\n\n" + 
21
                "${host}/datasets"
22
        );        
23
    }
24
    
25
    @Override
26
    public Command create(ReportServer server) {
27
        return new ListDatasets(this, server);
28
    }
29
    
30
}
org.gvsig.report/tags/org.gvsig.report-1.0.38/org.gvsig.report.lib/org.gvsig.report.lib.impl/src/main/java/org/gvsig/report/lib/impl/commands/GetDatasetFactory.java
1

  
2
package org.gvsig.report.lib.impl.commands;
3

  
4
import org.apache.commons.lang3.Range;
5
import org.gvsig.report.lib.api.ReportServer;
6
import org.gvsig.report.lib.api.commands.AbstractCommandFactory;
7
import org.gvsig.report.lib.api.commands.Command;
8

  
9
/**
10
 *
11
 * @author jjdelcerro
12
 */
13
public class GetDatasetFactory extends AbstractCommandFactory {
14

  
15
    public GetDatasetFactory() {
16
        super(
17
            "dataset", 
18
            Range.between(1, 8),
19
            "application/json",
20
            "dataset/<datasetname>\n" +
21
                "dataset/<datasetname>/withgeom\n" + 
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff