Project

General

Profile

1
/*
2
 * Copyright 2013 gathanas.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package eu.dnetlib.espas.util;
17

    
18
import java.io.ByteArrayOutputStream;
19
import java.io.IOException;
20
import java.sql.Connection;
21
import java.sql.DriverManager;
22
import java.sql.ResultSet;
23
import java.sql.SQLException;
24
import java.sql.Statement;
25
import java.util.HashMap;
26
import java.util.Map;
27
import java.util.logging.Level;
28
import org.apache.log4j.Logger;
29
import org.apache.log4j.Priority;
30
import org.apache.xml.serialize.DOMSerializer;
31
import org.apache.xml.serialize.XMLSerializer;
32
import org.geotoolkit.factory.AuthorityFactoryFinder;
33
import org.geotoolkit.factory.Hints;
34
import org.geotoolkit.referencing.CRS;
35
import org.geotoolkit.referencing.factory.web.WebCRSFactory;
36
import org.geotoolkit.referencing.factory.wkt.DirectPostgisFactory;
37
import org.geotoolkit.xml.MarshallerPool;
38
import org.opengis.referencing.crs.CRSAuthorityFactory;
39
import org.opengis.referencing.crs.CoordinateReferenceSystem;
40
import org.w3c.dom.Element;
41
import org.w3c.dom.Node;
42

    
43

    
44

    
45
/**
46
 *
47
 * @author gathanas
48
 */
49
public class MetadataHandler {
50
   
51
    private static final Logger _logger = Logger.getLogger(MetadataHandler.class);
52
    
53
    protected static final String GMD_NAMESPACE = "http://www.isotc211.org/2005/gmd";
54
    protected static final String GCO_NAMESPACE = "http://www.isotc211.org/2005/gco";
55
    protected static final String GML32_NAMESPACE = "http://www.opengis.net/gml/3.2";
56
    protected static final String XLINK1999_NAMESPACE = "http://www.w3.org/1999/xlink";
57

    
58
    protected static final boolean USE_EWKT = false;
59
    /** This connection to an associated postgis db instance is used for retrieving the Coordinate System reference codes
60
     * defined in the spatial_ref_sys table. If codes defined in this table are expected to be used for the instantiation of
61
     * coordinate systems and related transformations then this connection should be initialized.
62
     */
63
    //          initializing the jdbc connection to the postgis db instnace
64
    protected static String connectionURL = "jdbc:postgresql://dl121.madgik.di.uoa.gr/dnet_espas_v2";
65
    protected static String userName="dnet";
66
    protected static String passwrd="dnetPwd";
67
    protected static MarshallerPool metadataMarshPool;
68
    protected static Connection postgisDBConnection;
69
    private static Map<String, CRSMapping> supportedCRSMappings;
70

    
71
    protected static CRSAuthorityFactory authorityFactory;
72

    
73
    private static boolean inited=false;
74
    
75
    /** Statically initialize the MetadataHandler with a set of default properties.
76
     */
77
    static {
78
        try {
79
            Class.forName("org.postgresql.Driver");
80
            initializeDBConnection(null,null,null);
81
        } catch (ClassNotFoundException ex) {
82
            _logger.log(Priority.ERROR, "Postgress driver is not available", ex);
83
        } catch (SQLException ex) {
84
            _logger.log(Priority.ERROR, "Could not establish a connection to postgis db instnace. Connection url is:" + connectionURL, ex);
85
        }
86

    
87
    }
88

    
89
    private static void initializeDBConnection(String dbURL, String user, String pass) throws SQLException{
90
        if (dbURL!=null)
91
            connectionURL=dbURL;
92
        if(user!=null)
93
            userName= user;
94
        if(pass!=null)
95
            passwrd = pass;
96
            
97
        postgisDBConnection = DriverManager.getConnection(connectionURL, userName, passwrd);
98
        loadCRSToSRIDMappings();
99
    }
100
    
101
    /** Used for initializing the MetadataHandler with a set of specified properties.
102
     */
103
   public static void initHandler(String connectionURL,String dbName, String userName, String passWord) {
104
      try {
105
         if (!inited || postgisDBConnection == null || postgisDBConnection.isClosed()) {
106
             initializeDBConnection(connectionURL+"/"+dbName, userName, passWord);
107
             inited=true;
108
         }
109
      }
110
      catch (SQLException ex) {
111
         _logger.log(Priority.ERROR, "Could not establish a connection to postgis db instnace. Connection url is:" + connectionURL, ex);
112
      }
113

    
114
   }
115
    
116
    //////////////////////////////////////////////////////////////////////////
117
    /** Loads CRS mappings from the postgis database. Information is extracted from the values of the crs_spatial_ref_sys table
118
     */
119
    protected static void loadCRSToSRIDMappings() throws SQLException {
120
        initCRSAuthorityFactory();
121
        String retrieveCRSMappingsQuery = "select crs, srid,  sridName, inverse_x_y_order, z_scale_factor from crs_spatial_ref_sys";
122

    
123
        ResultSet queryResults = postgisDBConnection.createStatement().executeQuery(retrieveCRSMappingsQuery);
124
        if (queryResults != null) {
125
            supportedCRSMappings = new HashMap<String, CRSMapping>();
126
            while (queryResults.next()) {
127
                CRSMapping mapping = new CRSMapping(queryResults.getString("crs"), queryResults.getInt("srid"), queryResults.getString("sridname"), queryResults.getBoolean("inverse_x_y_order"), queryResults.getDouble("z_scale_factor"));
128
                supportedCRSMappings.put(mapping.getEspasCRS(), mapping);
129
            }
130
            queryResults.close();
131
        }
132
        _logger.debug("CRS to ESPAS SRS mappings have been initialized");
133
    }
134

    
135
    /** Serializes the provided node elements to string representations that are latter on used for logging purposes.
136
     */
137
    protected static String serializeNode(Node extentContent) throws IOException {
138
        XMLSerializer xmlSerializer = new XMLSerializer();
139
        ByteArrayOutputStream btArrStream = new ByteArrayOutputStream();
140
        xmlSerializer.setOutputByteStream(btArrStream);
141
        xmlSerializer.setNamespaces(true);
142
        DOMSerializer dmSerializer = xmlSerializer.asDOMSerializer();
143
        _logger.info("DM serializer is :"+(dmSerializer==null)+" extent is :"+(extentContent==null));
144
        String strCont="";
145
        if(dmSerializer!=null && extentContent!=null){
146
            dmSerializer.serialize((Element) extentContent);
147
            strCont = new String(btArrStream.toByteArray());
148
        }
149
        return strCont;
150
    }
151

    
152
    /** Internal method used for retrieving an appropriate CRS out of a WTK factory that is
153
     */
154
    static CoordinateReferenceSystem getCRSForSRSName(String srsCode) {
155
        try{
156
         initCRSAuthorityFactory();
157

    
158
         _logger.info("SRS Code is :"+srsCode+" is in the list :"+supportedCRSMappings.containsKey(srsCode));
159
        CoordinateReferenceSystem result = null;
160
        if (srsCode.equals("http://ontology.espas-fp7.eu/crs/GEI") || srsCode.equals("http://ontology.espas-fp7.eu/crs/J2000spherical"))
161
            result = authorityFactory.createCoordinateReferenceSystem("EPSG:4326");
162
        else if (supportedCRSMappings.containsKey(srsCode))
163
            result = authorityFactory.createCoordinateReferenceSystem(supportedCRSMappings.get(srsCode).getSridCode());
164
        return result;
165
    }
166
        catch(Exception ex){
167
                _logger.error("Retrieval of Coordinate reference system failed! \n", ex);
168
                return null;
169
        }
170
    }
171

    
172
   public static void initCRSAuthorityFactory() {
173
      //        Initialize either the Postgis factory if the connection is online or otherwise the WebFactory.
174
      Hints hintsforAuthorityFactory = new Hints();
175
      if (postgisDBConnection != null)
176
         try {
177
             if(postgisDBConnection.isClosed())
178
                 initializeDBConnection(null,null,null);
179
            _logger.info("Initilizing PostgisFactory for CRS codes ");
180
            authorityFactory = new DirectPostgisFactory(hintsforAuthorityFactory, postgisDBConnection);
181
            _logger.info("PostgisFactory for CRS codes has been initialized");
182
         } catch (Exception ex) {
183
            _logger.info("Postgis CRSFactory could not be initialized", ex);
184
            authorityFactory = new WebCRSFactory(hintsforAuthorityFactory);
185
         }
186
      else
187
         authorityFactory = new WebCRSFactory(hintsforAuthorityFactory);
188
      
189
      AuthorityFactoryFinder.addAuthorityFactory(authorityFactory);
190
   }
191
    
192
   
193
   public static String getComputationKind(String computationType){
194
      String result = "Software";
195
      try{
196
         if(computationType.equalsIgnoreCase("http://ontology.espas-fp7.eu/computationType/Model"))
197
            result = "Model";
198
         else
199
            if(computationType.equalsIgnoreCase("http://ontology.espas-fp7.eu/computationType/Software"))
200
               result="Software";
201
         else
202
            if (postgisDBConnection != null){
203
               Statement queryStatement = postgisDBConnection.createStatement();
204
               String query="with recursive computationtype_tree(child, parent) as (" +
205
                            " select ch.id, pr.parent from computationtype as ch, computationtype as pr" +
206
                            " where ch.parent = pr.id and pr.parent!='NULL')" +
207
                            " select parent from computationtype_tree where child='"+computationType+"'";
208
               ResultSet rs = queryStatement.executeQuery(query);
209
               if(rs.next()){
210
                  result = rs.getString(1).replaceAll("http://ontology.espas-fp7.eu/computationType/", "");
211
                  result = (result!="-1")?result:"Software";
212
                  }
213
               }
214
      }
215
      catch(Exception exc){
216
         _logger.info(null, exc);
217
      }
218
      finally{
219
         return result;
220
              }
221
   }
222
   
223
   
224
   public static CRSMapping getSupportedCRSMapping(String espasCRSName){
225
       try {
226
          loadCRSToSRIDMappings();
227
       }
228
       catch (SQLException ex) {
229
          _logger.debug(null,ex);
230
       }
231
       
232
       return supportedCRSMappings.get(espasCRSName);
233
      
234
   }
235
}
236

    
237

    
238

    
239

    
240

    
241

    
242
/** Class used for holding mappings of ESPAS CRS to standard ones used in postgis.
243
 */
244
class CRSMapping {
245
    private String espasCRS;
246
    private String sridCode;
247
    private int srid;
248
    private boolean invertedXY;
249
    private double zScaleFactor;
250

    
251
    public CRSMapping(String espasCRS, int srid, String sridCode, boolean invertedXY, double zScaleFactor) {
252
        this.espasCRS = espasCRS;
253
        this.srid = srid;
254
        this.sridCode = sridCode;
255
        this.invertedXY = invertedXY;
256
        this.zScaleFactor = zScaleFactor;
257
    }
258

    
259
    public String getEspasCRS() {
260
        return espasCRS;
261
    }
262

    
263
    public int getSrid() {
264
        return srid;
265
    }
266
    
267
    public String getSridCode() {
268
        return sridCode;
269
    }
270

    
271
    public boolean isInvertedXY() {
272
        return invertedXY;
273
    }
274

    
275
    public double getzScaleFactor() {
276
        return zScaleFactor;
277
    }
278
}
(7-7/9)