it.geosdi.era.server.service.implementation.ServerService.java Source code

Java tutorial

Introduction

Here is the source code for it.geosdi.era.server.service.implementation.ServerService.java

Source

/*
 *  GeoSDI ERA - The new era of webGIS
 *  http://code.google.com/p/geosdiera/
 * ====================================================================
 *
 * Copyright (C) 2008-2009 GeoSDI Group (CNR IMAA).
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. 
 *
 * ====================================================================
 *
 * This software consists of voluntary contributions made by developers
 * of GeoSDI Group.  For more information on GeoSDI, please see
 * <http://www.geosdi.org/>.
 *
 */

package it.geosdi.era.server.service.implementation;

import it.geosdi.era.client.Costanti;
import it.geosdi.era.client.model.Server;
import it.geosdi.era.client.model.ServerWMS_GWT;
import it.geosdi.era.client.nodistringa.NodoStringaLayerOWS;
import it.geosdi.era.client.nodistringa.StringNodeTemporalLayer;
import it.geosdi.era.exception.AliasException;
import it.geosdi.era.exception.DAOException;
import it.geosdi.era.exception.ServerException;
import it.geosdi.era.server.dao.IDAOServer;
import it.geosdi.era.server.service.IServerService;
import it.geosdi.era.server.service.utility.ServerUtility;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.ows.CRSEnvelope;
import org.geotools.data.ows.Layer;
import org.geotools.data.ows.WMSCapabilities;
import org.geotools.data.wms.WebMapServer;
import org.geotools.ows.ServiceException;
import org.hibernate.HibernateException;
import org.xml.sax.SAXException;

public class ServerService implements IServerService {

    /** LOGGER **/
    private static Log logger = LogFactory.getLog(ServerService.class);

    private IDAOServer daoServer;
    private WebMapServer wms;

    public IDAOServer getDaoServer() {
        return daoServer;
    }

    public void setDaoServer(IDAOServer daoServer) {
        this.daoServer = daoServer;
    }

    public List<Server> findAll() {
        return daoServer.findAll();
    }

    public List<NodoStringaLayerOWS> caricaLayer(String urlServer) {
        List<NodoStringaLayerOWS> listaNodiStringaLayerOws = new ArrayList<NodoStringaLayerOWS>();
        URL url = this.costruisciURL(urlServer);
        List<Layer> layers = this.costruisciLayers(url);
        for (Layer layer : layers) {

            NodoStringaLayerOWS nodoStringaLayer = new NodoStringaLayerOWS(
                    layer.getTitle() != null && layer.getTitle().length() > 0 ? layer.getTitle() : layer.getName());
            nodoStringaLayer.setNomeLayer(layer.getName());
            if (layer.getBoundingBoxes().values().size() != 0)
                for (Object SRSID : layer.getBoundingBoxes().keySet()) {
                    nodoStringaLayer.setBbox(this.createBoundBox(layer.getBoundingBoxes().get(SRSID)),
                            (String) SRSID);
                    nodoStringaLayer.setSRSID((String) SRSID);
                }
            listaNodiStringaLayerOws.add(nodoStringaLayer);

            if (layer.getChildren() != null && layer.getChildren().length > 0) {
                nodoStringaLayer.setChildren(addChidlrenToNode(layer.getChildren()));
            }
        }

        return listaNodiStringaLayerOws;
    }

    /**
     * 
     * @return
     */
    private List<NodoStringaLayerOWS> addChidlrenToNode(Layer[] layers) {
        List<NodoStringaLayerOWS> children = new ArrayList<NodoStringaLayerOWS>();

        for (int i = 0; i < layers.length; i++) {
            NodoStringaLayerOWS nodoStringa = new NodoStringaLayerOWS(
                    layers[i].getTitle() != null && layers[i].getTitle().length() > 0 ? layers[i].getTitle()
                            : layers[i].getName());

            nodoStringa.setNomeLayer(layers[i].getName());
            if (layers[i].getBoundingBoxes().values().size() != 0) {
                for (Object SRSID : layers[i].getBoundingBoxes().keySet()) {
                    nodoStringa.setBbox(this.createBoundBox(layers[i].getBoundingBoxes().get(SRSID)),
                            (String) SRSID);
                    nodoStringa.setSRSID((String) SRSID);
                }
            }

            if (layers[i].getChildren() != null && layers[i].getChildren().length > 0) {
                nodoStringa.setChildren(addChidlrenToNode(layers[i].getChildren()));
            }

            children.add(nodoStringa);
        }

        return children;
    }

    private String[] createBoundBox(CRSEnvelope envelope) {
        String[] bbox = new String[] { String.valueOf(envelope.getMinX()), String.valueOf(envelope.getMinY()),
                String.valueOf(envelope.getMaxX()), String.valueOf(envelope.getMaxY()) };
        return bbox;
    }

    private List<Layer> costruisciLayers(URL url) throws ServerException {
        wms = null;
        List<Layer> layers = null;
        try {
            wms = new WebMapServer(url);
            WMSCapabilities capabilities = wms.getCapabilities();
            Layer root = capabilities.getLayer();
            if (root != null && root.getChildren() != null) {
                layers = new ArrayList<Layer>();
                for (Layer layer : root.getChildren()) {
                    if (layer.getName() != null && layer.getName().length() > 0) {
                        layers.add(layer);
                    } else if (layer.getTitle() != null && layer.getTitle().length() > 0) {
                        layer.setName(layer.getTitle());
                        layers.add(layer);
                    }
                }
            }
        } catch (IOException e) {
            throw new ServerException("Il Server non  raggiungibile.");
        } catch (ServiceException e) {
            throw new ServerException("The server returned a ServiceException (unusual in this case)");
            // The server returned a ServiceException (unusual in this case)
        } catch (SAXException e) {
            // Unable to parse the response from the server
            // For example, the capabilities it returned was not valid
            throw new ServerException("Unable to parse the response from the server");
        }
        return layers;
    }

    private URL costruisciURL(String urlServer) throws ServerException {
        URL url = null;
        try {
            url = new URL(urlServer);
        } catch (MalformedURLException e) {
            // will not happen
            throw new ServerException("L' Url inserito non e' valido");
        }
        return url;
    }

    public ServerWMS_GWT salvaServer(Server server) throws DAOException {
        try {

            // Check if server is already present in DB
            Server check = daoServer.findByUrl(server.getUrlServer());

            if (check != null) {
                throw new ServerException("The server with url " + server.getUrlServer() + " was already inserted");
            }

            List<NodoStringaLayerOWS> listaNodiStringaLayerOws = caricaLayer(server.getUrlServer());
            server.setNomeServer(this.wms.getCapabilities().getService().getTitle());
            daoServer.makePersistent(server);
            server.setNumeroStrati(listaNodiStringaLayerOws.size());
            ServerWMS_GWT serverWMS_GWT = new ServerWMS_GWT(server, listaNodiStringaLayerOws);
            return serverWMS_GWT;
        } catch (HibernateException e) {
            logger.error(Costanti.EXCEPTION_ERROR + e.getMessage());
            throw new DAOException(e.getMessage());
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * it.geosdi.era.server.service.IServerService#removeServer(it.geosdi.era
     * .client.model.Server)
     */
    public void removeServer(Server server) throws DAOException {
        try {
            daoServer.makeTransient(server);
        } catch (HibernateException e) {
            logger.error(Costanti.EXCEPTION_ERROR + e.getMessage());
            throw new DAOException(e.getMessage());
        }
    }

    public void setAliasServer(Server server, List<Server> serversList, String initialValue, String newValue) {
        if (ServerUtility.searchAlias(serversList, newValue))
            throw new AliasException(initialValue);
        server.setAlias(newValue);
        daoServer.makePersistent(server);
    }

    public StringNodeTemporalLayer refreshTemporalLayer(StringNodeTemporalLayer temporalLayer) {
        URL serverURL;

        try {
            serverURL = new URL(temporalLayer.getURLSERVERCAPABILITIES() + temporalLayer.getNameSpace());
            WebMapServer wms = new WebMapServer(serverURL);
            WMSCapabilities capabilities = wms.getCapabilities();
            DateFormat df = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
            df.setLenient(false);

            List<StringNodeTemporalLayer> temporals = new ArrayList<StringNodeTemporalLayer>();

            for (int i = 1; i < capabilities.getLayerList().size(); i++) {
                Layer layer = capabilities.getLayerList().get(i);
                StringNodeTemporalLayer temp = new StringNodeTemporalLayer(temporalLayer.getNameSpace());
                temp.setNomeLayer(layer.getName());
                temp.setNameSpace(temporalLayer.getNameSpace());
                temp.setURLSERVER(temporalLayer.getURLSERVER());
                temp.setURLSERVERCAPABILITIES(temporalLayer.getURLSERVERCAPABILITIES());
                Date dataLayer = df.parse(layer.getTitle().substring(0, 16));
                temp.setDate(dataLayer);

                if (layer.getBoundingBoxes().values().size() != 0) {
                    for (Object SRSID : layer.getBoundingBoxes().keySet()) {
                        temp.setBB(this.createBoundBox(layer.getBoundingBoxes().get(SRSID)), (String) SRSID);
                        temp.setSRSID((String) SRSID);
                    }
                }
                temporals.add(temp);
            }

            Collections.sort(temporals);

            return temporals.get(0);

        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
            throw new DAOException(e.getMessage());
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            throw new DAOException(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new DAOException(e.getMessage());
        } catch (ParseException e) {
            logger.error(e.getMessage());
            throw new DAOException(e.getMessage());
        }
    }
}