de.decidr.model.webservice.helper.DBAccess.java Source code

Java tutorial

Introduction

Here is the source code for de.decidr.model.webservice.helper.DBAccess.java

Source

/*
 * The DecidR+ Development Team licenses this file to you 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 de.decidr.model.webservice.helper;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import de.decidr.model.XmlTools;
import de.decidr.model.entities.DeployedWorkflowModel;
import de.decidr.model.entities.File;
import de.decidr.model.entities.ServerLoadView;
import de.decidr.model.enums.ServerTypeEnum;
import de.decidr.model.schema.dwdl.TWorkflow;
import de.decidr.model.schema.wsdl.TDefinitions;
import de.decidr.model.webservice.helper.model.DbDataBean;

/**
 * @author Oliver Sonnauer
 * @author David Bamberger
 * @author Peter Berger
 */
public class DBAccess {

    private String FILE_ID = "fileID";
    private String SERVER_TYPE = "serverType";
    private String DWFW_ID = "dwfmID";
    private String QUERY_DeployedWorkflowModel = "select w from DeployedWorkflowModel w where w.id = :" + DWFW_ID;
    private String QUERY_ServerLoadView = "select s from ServerLoadView s where s.serverType = :" + SERVER_TYPE;
    private String QUERY_File = "select f from File f where f.id = :" + FILE_ID;

    /**
     * @param dwfmID
     * @param invokeNodeId
     * @return gets the relevatn DWDL and the relevant WSDL file for the proxy-service from the Database
     */
    public DbDataBean getDBData(long dwfmID, long invokeNodeId) {

        DbDataBean dataBean = new DbDataBean();

        SessionFactory sf = new Configuration().configure().buildSessionFactory();

        // actial session
        Session se = sf.getCurrentSession();

        try {
            // save transaction to avoid NullPointerException on error handling.
            Transaction tr = null;

            try {
                // initialize new transaction
                tr = se.beginTransaction();

                execDeployedWorkflowModelQuery(dwfmID, dataBean, se);
                execFileQuery(getFileIDFromDwdl(dataBean, invokeNodeId), dataBean, se);
                execServerLoadViewQuery(ServerTypeEnum.Ode.toString(), dataBean, se);

                se.getTransaction().commit();

            } catch (Throwable e) {
                // if no transaction has been initialized try rollback

                if (tr != null) {
                    tr.rollback();
                    e.printStackTrace();
                }
            }
        } finally {
            // try to close session if this does not work 
            // at least try to close the transaction.
            try {
                if (se.isOpen()) {
                    se.close();
                }
                if (!sf.isClosed()) {
                    sf.close();
                }
            } catch (Throwable e) {
                se.disconnect();
            }
        }

        return dataBean;
    }

    /**
     * @param dataBean
     * @param invokeNodeId
     * @return the file ID extracted from the corresponding parameter in the invoke node inside the DWDL file
     */
    private long getFileIDFromDwdl(DbDataBean dataBean, long invokeNodeId) {
        long result = 0;

        InvokeNodeExtractor inx = new InvokeNodeExtractor(dataBean.getDwdl(), invokeNodeId);
        String fileId = inx.getWSDLFileID();
        if (fileId != null) {
            result = Long.parseLong(fileId);
        }
        return result;
    }

    /**
     * 
     * @param fileID
     *            must be >0
     * @param dataBean the Object to save the Data in
     * @param se
     * 
     * Gets a File Representing the WSDL of an new WebService to invoke from the Database
     */
    private void execFileQuery(long fileID, DbDataBean dataBean, Session se) {
        TDefinitions wsdl = null;

        if (fileID != 0) {
            File result = (File) se.createQuery(QUERY_File).setLong(FILE_ID, fileID).uniqueResult();

            if (result != null) {
                // make extra sure the data is retrieved from the db before
                // lazy
                // loading becomes unavailable.
                wsdl = XmlTools.unmarshalJaxbEntity(result.getData(),
                        de.decidr.model.schema.wsdl.TDefinitions.class);
                // Insert right calls to marshal the WSDL

            }
        }

        dataBean.setWsdl(wsdl);
    }

    /**
     * @param dwfmID
     * @param dataBean object to fill with data
     * @param se the actual session
     */
    private void execDeployedWorkflowModelQuery(Long dwfmID, DbDataBean dataBean, Session se) {
        DeployedWorkflowModel result = (DeployedWorkflowModel) se.createQuery(QUERY_DeployedWorkflowModel)
                .setLong(DWFW_ID, dwfmID).uniqueResult();

        dataBean.setWorkflowModelId(result.getOriginalWorkflowModel().getId());

        if (result != null) {
            // make extra sure the data is retrieved from the db before
            // lazy
            // loading becomes unavailable.
            dataBean.setDwdl(XmlTools.unmarshalJaxbEntity(result.getDwdl(), TWorkflow.class));
        }
    }

    @SuppressWarnings("unchecked")
    private void execServerLoadViewQuery(String serverType, DbDataBean dataBean, Session se) {
        List<ServerLoadView> serverStatistics = se.createQuery(QUERY_ServerLoadView)
                .setString(SERVER_TYPE, serverType).list();

        dataBean.setServerLocation(selectServer(serverStatistics).getLocation());
    }

    /**
     * Selects a server from the list of servers according to the selection
     * strategy "server is not locked and has the lowest load".
     * 
     * @param serverStatistics
     * @return Server that is not locked and has the lowest load.
     */
    private ServerLoadView selectServer(List<ServerLoadView> serverStatistics) {
        ServerLoadView candidate = null;
        for (ServerLoadView server : serverStatistics) {
            if (!server.isLocked()) {
                if (candidate == null || server.getLoad() < candidate.getLoad()) {
                    candidate = server;
                }
            }
        }
        return candidate;
    }

}