Source Code Cross Referenced for GetCapabilitiesResponseValidator.java in  » GIS » deegree » org » deegree » security » owsrequestvalidator » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » GIS » deegree » org.deegree.security.owsrequestvalidator 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        //$HeadURL: https://svn.wald.intevation.org/svn/deegree/base/trunk/src/org/deegree/security/owsrequestvalidator/GetCapabilitiesResponseValidator.java $
002:        /*----------------    FILE HEADER  ------------------------------------------
003:
004:         This file is part of deegree.
005:         Copyright (C) 2001-2008 by:
006:         EXSE, Department of Geography, University of Bonn
007:         http://www.giub.uni-bonn.de/deegree/
008:         lat/lon GmbH
009:         http://www.lat-lon.de
010:
011:         This library is free software; you can redistribute it and/or
012:         modify it under the terms of the GNU Lesser General Public
013:         License as published by the Free Software Foundation; either
014:         version 2.1 of the License, or (at your option) any later version.
015:
016:         This library is distributed in the hope that it will be useful,
017:         but WITHOUT ANY WARRANTY; without even the implied warranty of
018:         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
019:         Lesser General Public License for more details.
020:
021:         You should have received a copy of the GNU Lesser General Public
022:         License along with this library; if not, write to the Free Software
023:         Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
024:
025:         Contact:
026:
027:         Andreas Poth
028:         lat/lon GmbH
029:         Aennchenstr. 19
030:         53177 Bonn
031:         Germany
032:         E-Mail: poth@lat-lon.de
033:
034:         Prof. Dr. Klaus Greve
035:         Department of Geography
036:         University of Bonn
037:         Meckenheimer Allee 166
038:         53115 Bonn
039:         Germany
040:         E-Mail: greve@giub.uni-bonn.de
041:
042:         ---------------------------------------------------------------------------*/
043:        package org.deegree.security.owsrequestvalidator;
044:
045:        import java.io.ByteArrayInputStream;
046:        import java.io.ByteArrayOutputStream;
047:        import java.io.IOException;
048:        import java.io.InputStreamReader;
049:        import java.io.PrintWriter;
050:        import java.io.StringReader;
051:        import java.net.MalformedURLException;
052:        import java.net.URL;
053:        import java.util.List;
054:        import java.util.Properties;
055:
056:        import javax.xml.transform.OutputKeys;
057:
058:        import org.deegree.framework.log.ILogger;
059:        import org.deegree.framework.log.LoggerFactory;
060:        import org.deegree.framework.util.MimeTypeMapper;
061:        import org.deegree.framework.util.StringTools;
062:        import org.deegree.framework.xml.XMLFragment;
063:        import org.deegree.framework.xml.XMLParsingException;
064:        import org.deegree.model.metadata.iso19115.Linkage;
065:        import org.deegree.model.metadata.iso19115.OnlineResource;
066:        import org.deegree.ogcwebservices.InvalidParameterValueException;
067:        import org.deegree.ogcwebservices.OGCWebServiceRequest;
068:        import org.deegree.ogcwebservices.csw.capabilities.CatalogueCapabilities;
069:        import org.deegree.ogcwebservices.csw.capabilities.CatalogueCapabilitiesDocument;
070:        import org.deegree.ogcwebservices.getcapabilities.InvalidCapabilitiesException;
071:        import org.deegree.ogcwebservices.wfs.capabilities.FeatureTypeList;
072:        import org.deegree.ogcwebservices.wfs.capabilities.WFSCapabilities;
073:        import org.deegree.ogcwebservices.wfs.capabilities.WFSCapabilitiesDocument;
074:        import org.deegree.ogcwebservices.wfs.capabilities.WFSFeatureType;
075:        import org.deegree.ogcwebservices.wms.XMLFactory;
076:        import org.deegree.ogcwebservices.wms.capabilities.Layer;
077:        import org.deegree.ogcwebservices.wms.capabilities.WMSCapabilities;
078:        import org.deegree.ogcwebservices.wms.capabilities.WMSCapabilitiesDocument;
079:        import org.deegree.ogcwebservices.wms.capabilities.WMSCapabilitiesDocumentFactory;
080:        import org.deegree.owscommon_new.DCP;
081:        import org.deegree.owscommon_new.HTTP;
082:        import org.deegree.owscommon_new.Operation;
083:        import org.deegree.security.GeneralSecurityException;
084:        import org.deegree.security.UnauthorizedException;
085:        import org.deegree.security.drm.SecurityAccess;
086:        import org.deegree.security.drm.SecurityAccessManager;
087:        import org.deegree.security.drm.model.RightType;
088:        import org.deegree.security.drm.model.SecuredObject;
089:        import org.deegree.security.drm.model.User;
090:        import org.deegree.security.owsproxy.Condition;
091:        import org.deegree.security.owsproxy.OperationParameter;
092:        import org.deegree.security.owsproxy.Request;
093:        import org.deegree.security.owsrequestvalidator.wms.GetMapRequestValidator;
094:        import org.w3c.dom.Document;
095:
096:        /**
097:         * 
098:         * @author <a href="mailto:poth@lat-lon.de">Andreas Poth </a>
099:         * @author last edited by: $Author: aschmitz $
100:         * 
101:         * @version $Revision: 10586 $, $Date: 2008-03-14 03:27:57 -0700 (Fri, 14 Mar 2008) $
102:         */
103:        public class GetCapabilitiesResponseValidator extends ResponseValidator {
104:
105:            private static final ILogger LOG = LoggerFactory
106:                    .getLogger(GetCapabilitiesResponseValidator.class);
107:
108:            private static final String INVALIDSERVICE = Messages
109:                    .getString("GetCapabilitiesResponseValidator.INVALIDSERVICE");
110:
111:            private String proxyURL = null;
112:
113:            /**
114:             * @param policy
115:             * @param proxyURL
116:             */
117:            public GetCapabilitiesResponseValidator(Policy policy,
118:                    String proxyURL) {
119:                super (policy);
120:                this .proxyURL = proxyURL;
121:            }
122:
123:            /**
124:             * validates the passed object as a response to a OWS request. The validity of the response may
125:             * is assigned to specific user rights. If the passed user is <>null this will be evaluated.
126:             * <br>
127:             * the reponse may contain three valid kinds of objects:
128:             * <ul>
129:             * <li>a serialized image
130:             * <li>a xml encoded exception
131:             * <li>a svg-encoded vector image
132:             * </ul>
133:             * Each of these types can be identified by the mime-type of the response that is also passed to
134:             * the method. <br>
135:             * If something basic went wrong it is possible that not further specified kind of object is
136:             * passed as response. In this case the method will throw an
137:             * <tt>InvalidParameterValueException</tt> to avoid sending bad responses to the client.
138:             * 
139:             * @param service
140:             *            service which produced the response (WMS, WFS ...)
141:             * @param response
142:             * @param mime
143:             *            mime-type of the response
144:             * @param user
145:             * @return the new response array
146:             * @throws InvalidParameterValueException
147:             * @throws UnauthorizedException
148:             * @see GetMapRequestValidator#validateRequest(OGCWebServiceRequest, User)
149:             */
150:            @Override
151:            public byte[] validateResponse(String service, byte[] response,
152:                    String mime, User user)
153:                    throws InvalidParameterValueException,
154:                    UnauthorizedException {
155:
156:                Request req = policy.getRequest(service, "GetCapabilities");
157:                if (req == null) {
158:                    throw new InvalidParameterValueException(INVALIDSERVICE
159:                            + service);
160:                }
161:                // request is valid because no restrictions are made
162:                if (req.isAny())
163:                    return response;
164:
165:                if (MimeTypeMapper.isKnownOGCType(mime)) {
166:                    // if the mime-type is a known OGC mime-type it must be an XML
167:                    // document. probably it is a capabilities document but it also
168:                    // could be an
169:                    response = validateXML(service, response, user);
170:                } else if (mime.equals("text/xml")) {
171:                    // if the mime-type isn't an image type but 'text/xml'
172:                    // it could be an exception
173:                    response = validateXML(service, response, user);
174:                } else {
175:                    throw new InvalidParameterValueException(UNKNOWNMIMETYPE
176:                            + mime);
177:                }
178:
179:                return response;
180:            }
181:
182:            /**
183:             * splits document string into 'core' capabilities document and xml header
184:             * 
185:             * @param xml
186:             * @return the splitted document
187:             * @throws InvalidParameterValueException
188:             */
189:            private String[] clearCapabilities(byte[] xml)
190:                    throws InvalidParameterValueException {
191:                InputStreamReader isr = new InputStreamReader(
192:                        new ByteArrayInputStream(xml));
193:                StringBuffer sb = new StringBuffer(50000);
194:                int c = 0;
195:                try {
196:                    while ((c = isr.read()) > -1) {
197:                        sb.append((char) c);
198:                    }
199:                    isr.close();
200:                } catch (IOException e) {
201:                    String s = Messages.format(
202:                            "GetCapabilitiesResponseValidator.CAPAREAD", e
203:                                    .getMessage());
204:                    throw new InvalidParameterValueException(s);
205:                }
206:                // WMS <= 1.1.1
207:                int pos = sb.indexOf("<WMT_MS_Capabilities");
208:                // WMS 1.3
209:                if (pos < 0) {
210:                    pos = sb.indexOf("WMS_Capabilities");
211:                }
212:                // WFS 1.1.0
213:                if (pos < 0) {
214:                    pos = sb.indexOf("WFS_Capabilities");
215:                }
216:                // CSW 2.0.0
217:                if (pos < 0) {
218:                    pos = sb.indexOf("Capabilities");
219:                }
220:                // WCS 1.0.0
221:                if (pos < 0) {
222:                    pos = sb.indexOf("WCS_Capabilities");
223:                }
224:
225:                // just if pos is > -1 it makes sense to find the starting
226:                // index of the root element
227:                if (pos > -1) {
228:                    pos = pos + 4;
229:                    char ch = '$';
230:                    // find starting index of the root element
231:                    while (ch != '<' && pos > 0) {
232:                        pos--;
233:                        ch = sb.charAt(pos);
234:                    }
235:                    // if the least char read does not equal '<' the parsed document
236:                    // is not an XML document
237:                    if (ch != '<') {
238:                        pos = -1;
239:                    }
240:                }
241:                String[] o = new String[2];
242:                if (pos > 0) {
243:                    // XML header / doctype
244:                    o[0] = sb.substring(0, pos);
245:                } else {
246:                    o[0] = "";
247:                }
248:                if (pos > -1) {
249:                    // xml document starting at the root element
250:                    o[1] = sb.substring(pos);
251:                } else {
252:                    // no XML document
253:                    o[0] = "ERROR";
254:                    o[1] = sb.toString();
255:                }
256:
257:                return o;
258:            }
259:
260:            /**
261:             * validates the passed xml to be valid against the policy
262:             * 
263:             * @param service
264:             *            service which produced the response (WMS, WFS ...)
265:             * @param xml
266:             * @param mime
267:             * @param user
268:             * @throws InvalidParameterValueException
269:             */
270:            private byte[] validateXML(String service, byte[] xml, User user)
271:                    throws InvalidParameterValueException,
272:                    UnauthorizedException {
273:
274:                String[] st = clearCapabilities(xml);
275:                if (st[0].equals("ERROR")) {
276:                    LOG.logError(st[1]);
277:                    String s = Messages
278:                            .format(
279:                                    "GetCapabilitiesResponseValidator.NOCAPADOC",
280:                                    st[1]);
281:                    throw new InvalidParameterValueException(s);
282:                }
283:                Document doc = null;
284:                try {
285:                    XMLFragment frag = new XMLFragment();
286:                    frag.load(new StringReader(st[1]), XMLFragment.DEFAULT_URL);
287:                    doc = frag.getRootElement().getOwnerDocument();
288:                } catch (Exception e) {
289:                    LOG.logError(e.getMessage(), e);
290:                    String s = Messages
291:                            .getString("GetCapabilitiesResponseValidator.ALLCAPAPARSE");
292:                    throw new InvalidParameterValueException(s);
293:                }
294:                String root = doc.getDocumentElement().getNodeName();
295:                if (root.equalsIgnoreCase("Exception")) {
296:                    // if the xml contains a exception the reponse is valid!
297:                } else if ("WMS".equals(service)) {
298:                    try {
299:                        xml = validateWMSCapabilities(doc, user);
300:                    } catch (XMLParsingException e) {
301:                        LOG.logError(e.getMessage(), e);
302:                        throw new InvalidParameterValueException(
303:                                "invalid WMS capabilities");
304:                    }
305:                } else if ("WFS".equals(service)) {
306:                    xml = validateWFSCapabilities(doc, user);
307:                } else if ("WCS".equals(service)) {
308:                    xml = validateWCSCapabilities(doc, user);
309:                } else if ("CSW".equals(service)) {
310:                    xml = validateCSWCapabilities(doc);
311:                }
312:
313:                StringBuffer sb = new StringBuffer(xml.length + st[0].length());
314:                sb.append(st[0]);
315:                String s = new String(xml);
316:                int p = s.indexOf("?>");
317:                if (p > -1) {
318:                    sb.append(s.substring(p + 2, s.length()));
319:                } else {
320:                    sb.append(s);
321:                }
322:                s = sb.toString();
323:                if (s.indexOf("<?xml version") > 1) {
324:                    s = StringTools.replace(s,
325:                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>",
326:                            "", false);
327:                    s = StringTools.replace(s,
328:                            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "",
329:                            false);
330:                }
331:
332:                // TODO
333:                // regular expression
334:                // s = sb.toString().replaceAll( "<?...?>", "" );
335:
336:                return s.getBytes();
337:            }
338:
339:            /**
340:             * 
341:             * @param doc
342:             * @param user
343:             * @return nothing, an exception is thrown
344:             */
345:            private byte[] validateWCSCapabilities(@SuppressWarnings("unused")
346:            Document doc, @SuppressWarnings("unused")
347:            User user) {
348:                // TODO
349:                // implement support for WCS
350:                throw new UnsupportedOperationException();
351:            }
352:
353:            /**
354:             * validates the passed xml to be valid against the policy
355:             * 
356:             * @param xml
357:             * @param user
358:             * @throws InvalidParameterValueException
359:             * @throws XMLParsingException
360:             */
361:            private byte[] validateWMSCapabilities(Document doc, User user)
362:                    throws InvalidParameterValueException,
363:                    UnauthorizedException, XMLParsingException {
364:
365:                WMSCapabilitiesDocument cdoc = WMSCapabilitiesDocumentFactory
366:                        .getWMSCapabilitiesDocument(doc.getDocumentElement());
367:                WMSCapabilities capa = null;
368:                try {
369:                    capa = (WMSCapabilities) cdoc.parseCapabilities();
370:                } catch (InvalidCapabilitiesException e) {
371:                    LOG.logError(e.getMessage(), e);
372:                    String s = Messages.format(
373:                            "GetCapabilitiesResponseValidator.WMSCAPAPARSE", e
374:                                    .getMessage());
375:                    throw new InvalidParameterValueException(s);
376:                }
377:                capa = filterWMSLayers(capa, user);
378:
379:                List<Operation> ops = capa.getOperationMetadata()
380:                        .getOperations();
381:                for (Operation operation : ops) {
382:                    setNewOnlineResource(operation);
383:                }
384:
385:                ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
386:                byte[] b;
387:                try {
388:                    cdoc = XMLFactory.export(capa);
389:                    // must be UTF-8 because the WMS Capabilities template uses
390:                    // UTF-8 encoding
391:                    Properties properties = new Properties();
392:                    properties.setProperty(OutputKeys.ENCODING, "UTF-8");
393:                    cdoc.write(bos, properties);
394:                    b = bos.toByteArray();
395:                    bos.close();
396:                } catch (Exception e) {
397:                    LOG.logError(e.getMessage(), e);
398:                    String s = Messages.format(
399:                            "GetCapabilitiesResponseValidator.WMSCAPAEXPORT", e
400:                                    .getMessage());
401:                    throw new InvalidParameterValueException(s);
402:                }
403:
404:                return b;
405:
406:            }
407:
408:            /**
409:             * 
410:             * @param op
411:             */
412:            private void setNewOnlineResource(Operation op) {
413:                if (op.getDCP() != null) {
414:                    List<DCP> dcps = op.getDCP();
415:                    for (DCP dcp : dcps) {
416:                        HTTP http = (HTTP) dcp;
417:                        List<OnlineResource> links = http.getLinks();
418:                        try {
419:                            int size = links.size();
420:                            links.clear();
421:                            OnlineResource proxy = new OnlineResource(
422:                                    new Linkage(new URL(proxyURL)));
423:                            for (int i = 0; i < size; ++i)
424:                                links.add(proxy);
425:                        } catch (MalformedURLException e1) {
426:                            LOG.logError(e1.getLocalizedMessage(), e1);
427:                        }
428:                    }
429:                }
430:            }
431:
432:            /**
433:             * Sets the proxy online resource in the old owscommon Operation class. To be removed soon!
434:             * 
435:             * @param op
436:             */
437:            private void setNewOnlineResourceInOldOperation(
438:                    org.deegree.ogcwebservices.getcapabilities.Operation op) {
439:                if (op.getDCPs() != null) {
440:                    for (int i = 0; i < op.getDCPs().length; i++) {
441:                        org.deegree.ogcwebservices.getcapabilities.HTTP http = (org.deegree.ogcwebservices.getcapabilities.HTTP) op
442:                                .getDCPs()[i].getProtocol();
443:                        try {
444:                            if (http.getGetOnlineResources().length > 0) {
445:                                URL urls[] = new URL[http
446:                                        .getGetOnlineResources().length];
447:                                for (int k = 0; k < http
448:                                        .getGetOnlineResources().length; ++k)
449:                                    urls[k] = new URL(proxyURL);
450:                                http.setGetOnlineResources(urls);
451:                            }
452:                            if (http.getPostOnlineResources().length > 0) {
453:                                URL urls[] = new URL[http
454:                                        .getPostOnlineResources().length];
455:                                for (int k = 0; k < http
456:                                        .getPostOnlineResources().length; ++k)
457:                                    urls[k] = new URL(proxyURL);
458:                                http.setPostOnlineResources(urls);
459:                            }
460:                        } catch (MalformedURLException e1) {
461:                            e1.printStackTrace();
462:                        }
463:                    }
464:                }
465:            }
466:
467:            /**
468:             * validates the passed xml to be valid against the policy
469:             * 
470:             * @param xml
471:             * @param user
472:             * @throws InvalidParameterValueException
473:             * @throws UnauthorizedException
474:             */
475:            private byte[] validateWFSCapabilities(Document doc, User user)
476:                    throws InvalidParameterValueException,
477:                    UnauthorizedException {
478:
479:                WFSCapabilities capa = null;
480:                try {
481:                    WFSCapabilitiesDocument capaDoc = new WFSCapabilitiesDocument();
482:                    capaDoc.setRootElement(doc.getDocumentElement());
483:                    capa = (WFSCapabilities) capaDoc.parseCapabilities();
484:                } catch (Exception e) {
485:                    LOG.logError(e.getMessage(), e);
486:                    String s = Messages.format(
487:                            "GetCapabilitiesResponseValidator.INVALIDWFSCAPA",
488:                            e.getMessage());
489:                    throw new InvalidParameterValueException(s);
490:                }
491:
492:                capa = filterWFSFeatureType(capa, user);
493:
494:                org.deegree.ogcwebservices.getcapabilities.Operation[] ops = capa
495:                        .getOperationsMetadata().getOperations();
496:                for (int i = 0; i < ops.length; i++) {
497:                    setNewOnlineResourceInOldOperation(ops[i]);
498:                }
499:
500:                WFSCapabilitiesDocument capaDoc = null;
501:                try {
502:                    capaDoc = org.deegree.ogcwebservices.wfs.XMLFactory
503:                            .export(capa);
504:                } catch (Exception e) {
505:                    throw new InvalidParameterValueException(e);
506:                }
507:                ByteArrayOutputStream bos = new ByteArrayOutputStream(20000);
508:                PrintWriter pr = new PrintWriter(bos);
509:                capaDoc.write(pr);
510:                return bos.toByteArray();
511:
512:            }
513:
514:            /**
515:             * validates the passed xml to be valid against the policy
516:             * 
517:             * @param doc
518:             * @return the new response
519:             * @throws InvalidParameterValueException
520:             */
521:            private byte[] validateCSWCapabilities(Document doc)
522:                    throws InvalidParameterValueException {
523:                CatalogueCapabilities capa = null;
524:                try {
525:                    CatalogueCapabilitiesDocument capaDoc = new CatalogueCapabilitiesDocument();
526:                    capaDoc.setRootElement(doc.getDocumentElement());
527:                    capa = (CatalogueCapabilities) capaDoc.parseCapabilities();
528:                } catch (Exception e) {
529:                    LOG.logError(e.getMessage(), e);
530:                    throw new InvalidParameterValueException(Messages.format(
531:                            "GetCapabilitiesResponseValidator.INVALIDWFSCAPA",
532:                            e.getMessage()));
533:                }
534:
535:                org.deegree.ogcwebservices.getcapabilities.Operation[] ops = capa
536:                        .getOperationsMetadata().getOperations();
537:                for (int i = 0; i < ops.length; i++) {
538:                    setNewOnlineResourceInOldOperation(ops[i]);
539:                }
540:
541:                CatalogueCapabilitiesDocument capaDoc = null;
542:                try {
543:                    capaDoc = org.deegree.ogcwebservices.csw.XMLFactory_2_0_0
544:                            .export(capa, null);
545:                } catch (Exception e) {
546:                    throw new InvalidParameterValueException(e);
547:                }
548:                ByteArrayOutputStream bos = new ByteArrayOutputStream(20000);
549:                PrintWriter pr = new PrintWriter(bos);
550:                capaDoc.write(pr);
551:                return bos.toByteArray();
552:            }
553:
554:            /**
555:             * filters the wms capabilities to rturn just the valid layers
556:             * 
557:             * @param capa
558:             * @param user
559:             * @throws InvalidParameterValueException
560:             */
561:            private WMSCapabilities filterWMSLayers(WMSCapabilities capa,
562:                    User user) throws UnauthorizedException {
563:
564:                Request req = policy.getRequest("WMS", "GetCapabilities");
565:                Condition con = req.getPostConditions();
566:                OperationParameter op = con.getOperationParameter("layers");
567:                if (op.isAny())
568:                    return capa;
569:
570:                Layer layer = capa.getLayer();
571:                if (op.isUserCoupled() && user != null) {
572:                    try {
573:                        SecurityAccessManager sam = SecurityAccessManager
574:                                .getInstance();
575:                        SecurityAccess access = sam.acquireAccess(user);
576:                        // call recursive method to remove all 'named' layers not
577:                        // included in the list from the capabilities
578:                        layer = removeWMSLayer(layer, user, access);
579:                    } catch (Exception e) {
580:                        LOG.logError(e.getMessage(), e);
581:                        throw new UnauthorizedException(Messages.format(
582:                                "GetCapabilitiesResponseValidator.INVALIDUSER",
583:                                user));
584:                    }
585:                } else {
586:                    // get list of valid wms layers
587:                    List<?> list = op.getValues();
588:                    // call recursive method to remove all 'named' layers not
589:                    // included in the list from the capabilities
590:                    layer = removeWMSLayer(layer, list);
591:                }
592:                capa.setLayer(layer);
593:                return capa;
594:
595:            }
596:
597:            /**
598:             * recursive method that removes all 'named' layers (layers that has a name in addtion to a
599:             * title) from the layer tree thats root node (layer) is passed to the method and that not
600:             * present in the passed <tt>List</tt>
601:             * 
602:             * @param layer
603:             * @param validLayers
604:             */
605:            private Layer removeWMSLayer(Layer layer, List<?> validLayers) {
606:                Layer[] layers = layer.getLayer();
607:                for (int i = 0; i < layers.length; i++) {
608:                    if (layers[i].getName() != null
609:                            && !validLayers.contains(layers[i].getName())) {
610:                        layer.removeLayer(layers[i].getName());
611:                    } else {
612:                        removeWMSLayer(layers[i], validLayers);
613:                        if (layers[i].getLayer().length == 0
614:                                && layers[i].getName() == null) {
615:                            layer.removeLayerByTitle(layers[i].getTitle());
616:                        }
617:                    }
618:                }
619:                return layer;
620:            }
621:
622:            /**
623:             * recursive method that removes all 'named' layers (layers that has a name in addition to a
624:             * title) from the layer tree thats root node (layer) is passed to the method and the passed
625:             * user doesn't have a GetMap right on.
626:             * 
627:             * @param layer
628:             *            layer to validate
629:             * @param user
630:             *            user whose rights are considered
631:             * @param access
632:             *            object to access DRM registry
633:             * 
634:             */
635:            private Layer removeWMSLayer(Layer layer, User user,
636:                    SecurityAccess access) throws GeneralSecurityException {
637:                Layer[] layers = layer.getLayer();
638:                for (int i = 0; i < layers.length; i++) {
639:                    if (layers[i].getName() != null) {
640:                        SecuredObject secObj = null;
641:                        try {
642:                            // must be in try-catch block because an exception will be thrown
643:                            // if no SecuredObject with the passed layer exists
644:                            secObj = access.getSecuredObjectByName(layers[i]
645:                                    .getName(), "Layer");
646:                        } catch (Exception e) {
647:                        }
648:                        if (secObj == null
649:                                || user.getRights(access, secObj).getRight(
650:                                        secObj, RightType.GETMAP) == null) {
651:                            // remove the layer from the capabilities if it's not known
652:                            // by the DRM registry or if the user doesn't have a GetMap
653:                            // right on it
654:                            layer.removeLayer(layers[i].getName());
655:                        }
656:                    } else {
657:                        removeWMSLayer(layers[i], user, access);
658:                        if (layers[i].getLayer().length == 0
659:                                && layers[i].getName() == null) {
660:                            layer.removeLayerByTitle(layers[i].getTitle());
661:                        }
662:                    }
663:                }
664:                return layer;
665:            }
666:
667:            /**
668:             * @param capa
669:             * @param user
670:             * @return the new capabilities
671:             * @throws InvalidParameterValueException
672:             * @throws UnauthorizedException
673:             */
674:            private WFSCapabilities filterWFSFeatureType(WFSCapabilities capa,
675:                    User user) throws UnauthorizedException {
676:
677:                Request req = policy.getRequest("WFS", "GetCapabilities");
678:                Condition con = req.getPostConditions();
679:                OperationParameter op = con
680:                        .getOperationParameter("featureTypes");
681:                if (op.isAny())
682:                    return capa;
683:
684:                if (op.isUserCoupled() && user != null) {
685:                    try {
686:                        SecurityAccessManager sam = SecurityAccessManager
687:                                .getInstance();
688:                        SecurityAccess access = sam.acquireAccess(user);
689:                        FeatureTypeList ftl = capa.getFeatureTypeList();
690:                        WFSFeatureType[] ft = ftl.getFeatureTypes();
691:                        StringBuffer sb = new StringBuffer(200);
692:                        for (int i = 0; i < ft.length; i++) {
693:                            SecuredObject secObj = null;
694:                            try {
695:                                // must be in try-catch block because an exception will be thrown
696:                                // if no SecuredObject with the passed layer exists
697:                                sb.delete(0, sb.length());
698:                                sb.append('{').append(
699:                                        ft[i].getName().getNamespace()
700:                                                .toASCIIString());
701:                                sb.append("}:").append(
702:                                        ft[i].getName().getLocalName());
703:                                secObj = access.getSecuredObjectByName(sb
704:                                        .toString(), "Featuretype");
705:                            } catch (Exception e) {
706:                            }
707:                            if (secObj == null
708:                                    || user.getRights(access, secObj).getRight(
709:                                            secObj, RightType.GETFEATURE) == null) {
710:                                ftl.removeFeatureType(ft[i]);
711:                            }
712:                        }
713:                    } catch (Exception e) {
714:                        LOG.logError(e.getMessage(), e);
715:                        throw new UnauthorizedException(Messages.format(
716:                                "GetCapabilitiesResponseValidator.INVALIDUSER",
717:                                user));
718:                    }
719:                } else {
720:                    // get list of valid wms layers
721:                    List<String> list = op.getValues();
722:                    FeatureTypeList ftl = capa.getFeatureTypeList();
723:                    WFSFeatureType[] ft = ftl.getFeatureTypes();
724:                    StringBuffer sb = new StringBuffer(200);
725:                    for (int i = 0; i < ft.length; i++) {
726:                        sb.delete(0, sb.length());
727:                        sb.append('{').append(
728:                                ft[i].getName().getNamespace().toASCIIString());
729:                        sb.append("}:").append(ft[i].getName().getLocalName());
730:                        if (!list.contains(sb.toString())) {
731:                            ftl.removeFeatureType(ft[i]);
732:                        }
733:                    }
734:                }
735:
736:                return capa;
737:            }
738:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.