[Ds-java-dev] svn commit r18347 - trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin

sumedha at wso2.com sumedha at wso2.com
Wed Jun 11 23:52:12 PDT 2008


Author: sumedha
Date: Wed Jun 11 23:52:12 2008
New Revision: 18347
URL: http://wso2.org/svn/browse/wso2?view=rev&revision=18347

Log:
adding missing admin classes from revision 17405

Added:
   trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/
   trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DBServerData.java
   trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceAdmin.java
   trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceInfo.java

Added: trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DBServerData.java
URL: http://wso2.org/svn/browse/wso2/trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DBServerData.java?pathrev=18347
==============================================================================
--- (empty file)
+++ trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DBServerData.java	Wed Jun 11 23:52:12 2008
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.ws.dataservice.admin;
+
+/*
+* 
+*/
+public class DBServerData {
+    private String serverId;
+    private String jdbcUrl;
+    private String driverClass;
+    private String protocol;
+
+    public String getDriverClass() {
+        return driverClass;
+    }
+
+    public void setDriverClass(String driverClass) {
+        this.driverClass = driverClass;
+    }
+
+    public String getJdbcUrl() {
+        return jdbcUrl;
+    }
+
+    public void setJdbcUrl(String jdbcUrl) {
+        this.jdbcUrl = jdbcUrl;
+    }
+
+    public String getServerId() {
+        return serverId;
+    }
+
+    public void setServerId(String serverId) {
+        this.serverId = serverId;
+    }
+
+    public String getProtocol() {
+        return protocol;
+    }
+
+    public void setProtocol(String protocol) {
+        this.protocol = protocol;
+    }
+}

Added: trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceAdmin.java
URL: http://wso2.org/svn/browse/wso2/trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceAdmin.java?pathrev=18347
==============================================================================
--- (empty file)
+++ trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceAdmin.java	Wed Jun 11 23:52:12 2008
@@ -0,0 +1,423 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.ws.dataservice.admin;
+
+import au.com.bytecode.opencsv.CSVReader;
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMAttribute;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.util.StAXUtils;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.AbstractAdmin;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.ws.dataservice.DBConstants;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.*;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.*;
+
+/*
+* 
+*/
+public class DataServiceAdmin extends AbstractAdmin {
+    private static final Log log = LogFactory.getLog(DataServiceAdmin.class);
+
+    public DataServiceAdmin() {
+    }
+
+    /**
+     * This method will give the setup for DS. if arg init is null or "", it will consider as
+     * a call for a new DS. If new, configuration would only allow for non url repositories.
+     *
+     * @param init initial arg
+     * @return DataServiceInfo; Instance of DataServiceInfo
+     * @throws org.apache.axis2.AxisFault will be thrown
+     */
+    public DataServiceInfo getDSMetaData(String init) throws AxisFault {
+        if (init == null || init.length() == 0) {
+            //Call for new one DS.
+            String axis2Repo = System.getProperty("carbon.home");
+            if (CarbonUtils.isURL(axis2Repo)) {
+                throw new AxisFault("WSAS is running from a URL repository " + axis2Repo +
+                                    ". Cannot create Data Services for URL repositories");
+            } else {
+                OMFactory fac = OMAbstractFactory.getOMFactory();
+                OMElement dwEle = fac.createOMElement(new QName(null, "dataWrapper"));
+                OMElement dataEle = fac.createOMElement(new QName(null, "data"));
+                OMElement configEle = fac.createOMElement(new QName(null, "config"));
+                dataEle.addChild(configEle);
+                dwEle.addChild(dataEle);
+                DataServiceInfo dataServiceInfo = new DataServiceInfo();
+                dataServiceInfo.setDataWrapper(dwEle);
+                try {
+                    dataServiceInfo.setDbServerData(getDatabaseUrlDriverList());
+                } catch (XMLStreamException e) {
+                    throw AxisFault.makeFault(e);
+                }
+                return dataServiceInfo;
+            }
+
+        } else {
+            //call for the existing
+            DataServiceInfo dataServiceInfo = new DataServiceInfo();
+            OMElement dataEle = getDataServiceContents(init);
+            dataEle.build();
+            dataEle.detach();
+            OMFactory fac = OMAbstractFactory.getOMFactory();
+            OMElement dwEle = fac.createOMElement(new QName(null, "dataWrapper"));
+            dwEle.addChild(dataEle);
+            dataServiceInfo.setDataWrapper(dwEle);
+            try {
+                dataServiceInfo.setDbServerData(getDatabaseUrlDriverList());
+            } catch (XMLStreamException e) {
+                throw AxisFault.makeFault(e);
+            }
+            return dataServiceInfo;
+        }
+    }
+
+    /**
+     * This method will expose the .dbs for a given data service.
+     *
+     * @param serviceId service name
+     * @return OMElement
+     * @throws AxisFault will be thrown
+     */
+    public OMElement getDataServiceContents(String serviceId) throws AxisFault {
+        AxisService axisService = getAxisConfig().getService(serviceId);
+        String fileParth =
+                (String) axisService.getParameter(DBConstants.DB_SERVICE_CONFIG_FILE).getValue();
+        StringBuffer fileContents = new StringBuffer();
+        try {
+            BufferedReader in = new BufferedReader(new FileReader(fileParth));
+            String str;
+            while ((str = in.readLine()) != null) {
+                fileContents.append(str);
+            }
+            in.close();
+        } catch (IOException e) {
+            throw new AxisFault(
+                    "Error while reading the contents from the service config file for service "
+                    + serviceId, e);
+        }
+
+        OMElement returnEle;
+        try {
+            XMLStreamReader xmlSR =
+                    StAXUtils.createXMLStreamReader(
+                            new ByteArrayInputStream(fileContents.toString().getBytes()));
+
+            returnEle = new StAXOMBuilder(xmlSR).getDocumentElement();
+            // new BufferedReader(new InputStreamReader(
+        } catch (Exception e) {
+            throw new AxisFault(
+                    "Error while converting the contents of the configuration file into and OMElement for service "
+                    + serviceId, e);
+        }
+        return returnEle;
+    }
+
+    /**
+     * Saves a modified <data/> DS configuration
+     *
+     * @param dataWrapper wrapps the <data/> element
+     * @throws AxisFault will be thrown
+     */
+    public void saveDataServiceContents(OMElement dataWrapper) throws AxisFault {
+        String serviceId;
+        OMElement configEle = dataWrapper.getFirstChildWithName(new QName("data"));
+        if (configEle == null) {
+            throw new AxisFault("Data Service configuration start element <data/> is not found");
+        }
+        OMAttribute attribute = configEle.getAttribute(new QName("name"));
+        serviceId = attribute.getAttributeValue();
+        if (serviceId == null) {
+            throw new AxisFault(
+                    "Data Service configuration cannot be continued due to missing Data Service name");
+        }
+
+        for (Iterator queries = configEle.getChildrenWithName(new QName("query"));
+             queries.hasNext();) {
+            OMElement query = (OMElement) queries.next();
+
+            for (Iterator results = query.getChildrenWithName(new QName("result"));
+                 results.hasNext();) {
+                OMElement result = (OMElement) results.next();
+                // Only selected if the all simple version is returned from the
+                // client.
+                OMAttribute rowNameAttribute = result.getAttribute(new QName("rowname"));
+                if (rowNameAttribute != null) {
+                    String attValue = rowNameAttribute.getAttributeValue();
+                    result.removeAttribute(rowNameAttribute);
+                    result.addAttribute(OMAbstractFactory.getOMFactory().createOMAttribute(
+                            "rowName", OMAbstractFactory.getOMFactory().createOMNamespace("", ""),
+                            attValue));
+                }
+            }
+
+            for (Iterator params = query.getChildrenWithName(new QName("param"));
+                 params.hasNext();) {
+                OMElement param = (OMElement) params.next();
+                // Only selected if the all simple version is returned from the
+                // client.
+                OMAttribute sqlTypeAttribute = param.getAttribute(new QName("sqltype"));
+                if (sqlTypeAttribute != null) {
+                    String attValue = sqlTypeAttribute.getAttributeValue();
+                    param.removeAttribute(sqlTypeAttribute);
+                    param.addAttribute(OMAbstractFactory.getOMFactory().createOMAttribute(
+                            "sqlType", OMAbstractFactory.getOMFactory().createOMNamespace("", ""),
+                            attValue));
+                }
+            }
+        }
+
+        String dataServiceFilePath;
+        AxisService axisService = getAxisConfig().getService(serviceId);
+        if (axisService == null) {
+            // New service
+            String axis2RepoDirectory = getAxisConfig().getRepository().getPath();
+            ConfigurationContext configCtx = getConfigContext();
+            String repoDirectory = (String) configCtx.getProperty(DBConstants.DB_SERVICE_REPO);
+            String fileExtension =
+                    (String) configCtx.getProperty(DBConstants.DB_SERVICE_EXTENSION);
+
+            String dataServiceDirectory = axis2RepoDirectory + File.separator + repoDirectory;
+            dataServiceFilePath = dataServiceDirectory + File.separator
+                                  + serviceId + "." + fileExtension;
+
+            //create the directory, if it does not exist
+            File directory = new File(dataServiceDirectory);
+            directory.mkdirs();
+
+            File file = new File(dataServiceFilePath);
+            try {
+                file.createNewFile();
+            } catch (IOException e) {
+                throw new AxisFault(
+                        "Error while creating the file for the new service config file for the new service "
+                        + serviceId, e);
+            }
+
+        } else {
+            dataServiceFilePath =
+                    (String) axisService.getParameter(DBConstants.DB_SERVICE_CONFIG_FILE)
+                            .getValue();
+        }
+
+        try {
+            BufferedWriter out = new BufferedWriter(new FileWriter(dataServiceFilePath));
+            configEle.serialize(out);
+            // out.write(configContents);
+            out.close();
+        } catch (IOException e) {
+            throw new AxisFault(
+                    "Error while writing the contents for the service config file for the new service "
+                    + serviceId, e);
+        } catch (XMLStreamException e) {
+
+            throw new AxisFault("Error while serializing the config OMElement for the service "
+                                + serviceId, e);
+
+        }
+
+    }
+
+    /**
+     * Returns list of known database server jdbc urls and driver class names from server.xml
+     * TODO: Sumedha fix this, so the drivers can be obtained from a configuration file, rather
+     * TODO: server.xml. As core is a component, this shoulbe taken from either WSO2 regisrty etc.
+     *
+     * @return DBServerData array
+     */
+    public DBServerData[] getDatabaseUrlDriverList() throws XMLStreamException {
+        ArrayList databaseServers = new ArrayList();
+        DBServerData databaseServerData;
+        InputStream stream =
+                getClass().getResourceAsStream("/org/wso2/ws/dataservice/admin/database.xml");
+        StAXOMBuilder builder = new StAXOMBuilder(stream);
+        OMElement documentElement = builder.getDocumentElement();
+        Iterator serverElementIterator =
+                documentElement.getChildrenWithName(new QName("Server"));
+
+        for (; serverElementIterator.hasNext();) {
+            OMElement serverElement = (OMElement) serverElementIterator.next();
+            OMElement serverIdElement = serverElement.getFirstChildWithName(new QName("Id"));
+            OMElement jdbcUrlElement = serverElement.getFirstChildWithName(new QName("JdbcURL"));
+            OMElement driverClassElement =
+                    serverElement.getFirstChildWithName(new QName("DriverClass"));
+
+            databaseServerData = new DBServerData();
+            databaseServerData.setServerId(serverIdElement.getText());
+            String text = jdbcUrlElement.getText();
+            databaseServerData.setJdbcUrl(text);
+            databaseServerData.setDriverClass(driverClassElement.getText());
+            //set the protocol
+            int index = text.indexOf("jdbc:");
+            if (index > -1) {
+                String tmp1 = text.substring(index + 5);
+                index = tmp1.indexOf(":");
+                String protocol = tmp1.substring(0, index);
+                databaseServerData.setProtocol(protocol);
+            } else {
+                databaseServerData.setProtocol("generic");
+            }
+            databaseServers.add(databaseServerData);
+
+        }
+        DBServerData[] databaseServerList = new DBServerData[databaseServers.size()];
+        databaseServers.toArray(databaseServerList);
+        return databaseServerList;
+    }
+
+
+    /**
+     * Loads first line of CSV file as the column header & returns an String array of column names
+     * TODO : implement for Excel
+     *
+     * @param resourcePath   resourcePath
+     * @param hasHeaders     hasHeaders
+     * @param dataSourceType dataSourceType
+     * @return String array
+     */
+    public String[] getHeaderColumnNames(String resourcePath, String hasHeaders,
+                                         String dataSourceType) {
+        log.debug("getHeaderColumnNames() called with params :"
+                  + resourcePath + " : " + hasHeaders + " : " + dataSourceType);
+        CSVReader reader = null;
+        String[] columnHeader = null;
+        if (DBConstants.Query.CSV.equals(dataSourceType)) {
+            InputStreamReader inputStreamReader = null;
+            try {
+                if (resourcePath.startsWith("http://")) {
+                    URL url = new URL(resourcePath);
+                    inputStreamReader = new InputStreamReader(url.openStream());
+                    reader = new CSVReader(inputStreamReader);
+                } else {
+                    reader = new CSVReader(new FileReader(resourcePath));
+                }
+
+                if (reader != null) {
+                    //read the first line, which contains column header
+                    String[] firstLine = reader.readNext();
+                    if (Boolean.valueOf(hasHeaders).booleanValue()) {
+                        //if hasHeader is set to true, first line contains column names
+                        columnHeader = firstLine;
+                    } else {
+                        //create a dummy column header with number of columns
+                        columnHeader = new String[firstLine.length];
+                        for (int a = 0; a < firstLine.length; a++) {
+                            columnHeader[a] = String.valueOf(a + 1);
+                        }
+                    }
+                }
+            } catch (MalformedURLException e) {
+                log.error("Incorrect " + dataSourceType + " URL : " + resourcePath, e);
+            } catch (IOException e) {
+                log.error("Error reading file : " + resourcePath, e);
+                e.printStackTrace();
+            }
+        }
+        return columnHeader;
+    }
+
+    /**
+     * This will test a connection to a given database. If connection can be made this method will
+     * return the status as String, if not, faliour String will be return.
+     *
+     * @param driverClass Driver class
+     * @param jdbcURL     JDBC URL
+     * @param username    User name
+     * @param password    Pass word
+     * @return String; state
+     */
+    public String testJDBCConnection(String driverClass,
+                                     String jdbcURL,
+                                     String username,
+                                     String password) {
+        if (driverClass == null || driverClass.length() == 0) {
+            String message = "Driver class is missing";
+            log.debug(message);
+            return message;
+        }
+        if (jdbcURL == null || jdbcURL.length() == 0) {
+            String message = "Driver connection URL is missing";
+            log.debug(message);
+            return message;
+        }
+        Connection connection = null;
+        try {
+            Class.forName(driverClass.trim());
+            connection = DriverManager.getConnection(jdbcURL, username, password);
+            String message = "Database connection is successfull with driver class" + driverClass +
+                             " , jdbc url " + jdbcURL + " and user name " + username;
+            log.debug(message);
+            return message;
+        } catch (SQLException e) {
+            String message =
+                    "Could not connect to database " + jdbcURL + " with username " + username;
+            log.debug(message, e);
+            return message;
+        } catch (ClassNotFoundException e) {
+            String message = "Drive class " + driverClass + " can not be loaded";
+            log.debug(message);
+            return message;
+        } finally {
+            if (connection != null) {
+                try {
+                    connection.close();
+                } catch (SQLException ignored) {
+                }
+            }
+        }
+    }
+
+    /**
+     * Return data services
+     *
+     * @return names of the data services
+     * @throws AxisFault AxisFault
+     */
+    public String[] getAvailableDS() throws AxisFault {
+        List<String> serviceList = new ArrayList<String>();
+        HashMap map = getAxisConfig().getServices();
+        Set set = map.keySet();
+        for (Object service : set) {
+            String serviceName = (String) service;
+            AxisService axisService = getAxisConfig().getService(serviceName);
+            Parameter parameter = axisService.getParameter("serviceType");
+            if (parameter != null) {
+                if ("data_service".equals(parameter.getValue().toString())) {
+                    serviceList.add(serviceName);
+                }
+            }
+        }
+        return serviceList.toArray(new String[serviceList.size()]);
+    }
+}

Added: trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceInfo.java
URL: http://wso2.org/svn/browse/wso2/trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceInfo.java?pathrev=18347
==============================================================================
--- (empty file)
+++ trunk/solutions/data-services/java/modules/core/src/main/java/org/wso2/ws/dataservice/admin/DataServiceInfo.java	Wed Jun 11 23:52:12 2008
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.ws.dataservice.admin;
+
+import org.apache.axiom.om.OMElement;
+
+/*
+* 
+*/
+public class DataServiceInfo {
+    private OMElement dataWrapper;
+    private DBServerData[] dbServerData;
+
+    public OMElement getDataWrapper() {
+        return dataWrapper;
+    }
+
+    public void setDataWrapper(OMElement dataWrapper) {
+        this.dataWrapper = dataWrapper;
+    }
+
+    public DBServerData[] getDbServerData() {
+        return dbServerData;
+    }
+
+    public void setDbServerData(DBServerData[] dbServerData) {
+        this.dbServerData = dbServerData;
+    }
+}



More information about the Ds-java-dev mailing list