001/*
002 * Copyright (c) 2003-2010 The Regents of the University of California.
003 * All rights reserved.
004 *
005 * '$Author: welker $'
006 * '$Date: 2010-05-06 05:21:26 +0000 (Thu, 06 May 2010) $' 
007 * '$Revision: 24234 $'
008 * 
009 * Permission is hereby granted, without written agreement and without
010 * license or royalty fees, to use, copy, modify, and distribute this
011 * software and its documentation for any purpose, provided that the above
012 * copyright notice and the following two paragraphs appear in all copies
013 * of this software.
014 *
015 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
016 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
017 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
018 * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
019 * SUCH DAMAGE.
020 *
021 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
022 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
023 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
024 * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
025 * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
026 * ENHANCEMENTS, OR MODIFICATIONS.
027 *
028 */
029
030package org.ecoinformatics.seek.datasource;
031
032import java.io.BufferedWriter;
033import java.io.FileWriter;
034import java.io.IOException;
035
036import org.apache.commons.logging.Log;
037import org.apache.commons.logging.LogFactory;
038import org.ecoinformatics.ecogrid.authenticatedqueryservice.AuthenticatedQueryServiceClient;
039import org.ecoinformatics.ecogrid.queryservice.QueryServiceClient;
040import org.ecoinformatics.ecogrid.queryservice.query.QueryType;
041import org.ecoinformatics.ecogrid.queryservice.resultset.ResultsetType;
042import org.ecoinformatics.ecogrid.queryservice.resultset.ResultsetTypeRecord;
043import org.ecoinformatics.ecogrid.queryservice.util.EcogridResultsetParser;
044import org.ecoinformatics.ecogrid.queryservice.util.EcogridResultsetTransformer;
045import org.ecoinformatics.seek.ecogrid.EcoGridService;
046import org.ecoinformatics.seek.ecogrid.EcoGridServicesController;
047import org.kepler.objectmanager.cache.CacheManager;
048import org.kepler.objectmanager.cache.DataCacheObject;
049
050/**
051 * This class is not as generic as the name may indicate. It is designed to get
052 * the metadata to determine where the data is stored and then does a Ecogrid
053 * "get" to the data.
054 */
055public class EcogridQueryDataCacheItem extends DataCacheObject {
056        private static Log log;
057        static {
058                log = LogFactory
059                                .getLog("org.ecoinformatics.seek.datasource.EcogridQueryDataCacheItem");
060        }
061
062        private QueryType _query = null;
063        private ResultsetType _resultset = null;
064
065        /**
066     * 
067     *
068     */
069        public EcogridQueryDataCacheItem() {
070                super();
071        }
072
073        /*
074         * (non-Javadoc)
075         * 
076         * @see org.ecoinformatics.seek.datasource.DataCacheItem#doWork()
077         */
078        public int doWork() {
079                log.debug("EcogridQueryDataCacheItem - doing Work mStatus "
080                                + getStatus());
081                try {
082
083                        // check the serviceType based on endpoint
084                        EcoGridService service = EcoGridServicesController.getInstance()
085                                        .getService(getResourceName());
086                        // authenticate if needed
087                        if (service != null
088                                        && service
089                                                        .getServiceType()
090                                                        .equals(
091                                                                        EcoGridServicesController.AUTHENTICATEDQUERYSERVICETYPE)) {
092                                String sessionId = EcoGridServicesController.getInstance()
093                                                .authenticateForService(service);
094                                AuthenticatedQueryServiceClient authQueryClient = new AuthenticatedQueryServiceClient(
095                                                getResourceName());
096                                _resultset = authQueryClient.query(_query, sessionId);
097                        } else {
098                                // just use the normal, non-authenticated service
099                                QueryServiceClient ecogridClient = new QueryServiceClient(
100                                                getResourceName());
101                                _resultset = ecogridClient.query(_query);
102                        }
103
104                } catch (InterruptedException ie) {
105                        log.debug("Interrupted");
106                        _resultset = null;
107                        cleanUpCache();
108                        return CACHE_EMPTY;
109                } catch (Exception ee) {
110                        log.error("The exception in query is ", ee);
111                        _resultset = null;
112                        cleanUpCache();
113                        return CACHE_ERROR;
114                }
115                if (_resultset == null) {
116                        log.debug("*** Resultset was NULL!");
117                        return CACHE_COMPLETE;
118                }
119                ResultsetTypeRecord[] records = _resultset.getRecord();
120                if (records == null) {
121                        log.debug("*** Resultset records array was NULL!");
122                        return CACHE_COMPLETE;
123                }
124                String rsStr = null;
125                try {
126                        rsStr = EcogridResultsetTransformer.toXMLString(_resultset);
127                } catch (java.io.IOException ioe) {
128                        rsStr = new String();
129                }
130                if (rsStr.length() == 0) {
131                        log.debug("*** Resultset string was empty.");
132                        return CACHE_COMPLETE;
133                }
134                try {
135                        BufferedWriter bos = new BufferedWriter(new FileWriter(getFile()));
136                        bos.write(rsStr);
137                        bos.flush();
138                        bos.close();
139                        return CACHE_COMPLETE;
140                } catch (IOException ioe) {
141                        log.error("*** Unable to write file.");
142                        cleanUpCache();
143                        return CACHE_ERROR;
144                }
145
146        }
147
148        /**
149         * @param aQuery
150         *            the UqeryType object
151         */
152        public void setQuery(QueryType aQuery) {
153                _query = aQuery;
154        }
155
156        /**
157         * Returns the data cached as a resultset object
158         * 
159         *       */
160        public ResultsetType getResultset() {
161                if (isReady() && _resultset == null) {
162                        try {
163                                _resultset = EcogridResultsetParser
164                                                .parseXMLFile(getAbsoluteFileName());
165                        } catch (org.xml.sax.SAXException e) {
166                                _resultset = null;
167                        }
168                }
169                return _resultset;
170        }
171
172        /*
173         * Cleanup the cache object if some error happens during the search.
174         */
175        private void cleanUpCache() {
176
177                // clean up the cache object
178                try {
179                        // log.warn("close the input stream and delete existed file");
180                        // bos.close();
181                        // getFile().delete();
182                        if (this.getLSID() != null) {
183                                CacheManager.getInstance().removeObject(this.getLSID());
184                        }
185
186                } catch (Exception e) {
187                        log.error("Couldn't close the output stream to cache file "
188                                        + e.getMessage());
189                }
190
191        }
192}