de.zib.gndms.GORFX.context.service.globus.resource.ExtTaskResourceHome.java Source code

Java tutorial

Introduction

Here is the source code for de.zib.gndms.GORFX.context.service.globus.resource.ExtTaskResourceHome.java

Source

package de.zib.gndms.GORFX.context.service.globus.resource;

/*
 * Copyright 2008-2011 Zuse Institute Berlin (ZIB)
 *
 * 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.
 */

import de.zib.gndms.GORFX.context.stubs.types.TaskReference;
import de.zib.gndms.GORFX.service.globus.resource.ExtGORFXResourceHome;
import de.zib.gndms.infra.GNDMSTools;
import de.zib.gndms.infra.GridConfig;
import de.zib.gndms.infra.service.GNDMPersistentServiceHome;
import de.zib.gndms.infra.system.GNDMSystem;
import de.zib.gndms.model.gorfx.Task;
import org.apache.axis.message.addressing.AttributedURI;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.impl.SimpleResourceKey;
import org.globus.wsrf.utils.AddressingUtils;
import org.jetbrains.annotations.NotNull;

import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.List;

/**
 * This class overrides the ResourceHome that is automatically generated by introduce for Globus
 * Toolkit. In GNDMS this is mainly necessary to provide RDBMS/JPA-based resource persistence.
 * In order to use the extended resource home they have to be configured in jndi-config.xml.
 * If this has been done properly, you should see an info-level log message during the start up
 * of the web service container that notifies succesfull initialization of the extended resource
 * home.
 *
 * @author  try ste fan pla nti kow zib
 * @version $Id$
 *
 *          User: stepn Date: 16.07.2008 Time: 12:35:27
 */
public final class ExtTaskResourceHome extends TaskResourceHome implements GNDMPersistentServiceHome<Task> {

    // logger can be an instance field since resource home classes are instantiated at most once
    @NotNull
    @SuppressWarnings({ "FieldNameHidesFieldInSuperclass" })
    private final Log logger = LogFactory.getLog(ExtTaskResourceHome.class);

    @NotNull
    private GNDMSystem system;

    @NotNull
    private AttributedURI serviceAddress;

    private boolean initialized = false;

    @Override
    public synchronized void initialize() throws Exception {
        if (!initialized) {
            logger.info("Extended Task home initializing");
            try {
                try {
                    final GridConfig gridConfig = ExtGORFXResourceHome.getGridConfig();
                    logger.debug("Config: " + gridConfig.asString());
                    system = gridConfig.retrieveSystemReference();
                    serviceAddress = GNDMSTools.getServiceAddressFromContext();

                    initialized = true;
                    super.initialize(); // Overridden method
                    resumeTasks();
                } catch (NamingException e) {
                    throw new RuntimeException(e);
                }
            } catch (RuntimeException e) {
                initialized = false;
                logger.error("Initialization failed", e);
                e.printStackTrace(System.err);
                throw e;
            }
        }
    }

    private void resumeTasks() throws Exception {

        logger.debug("Checking for aborted tasks.");
        EntityManager em = null;
        List<String> rs = null;
        try {
            em = system.getEntityManagerFactory().createEntityManager();
            Query q = em.createNamedQuery("unfinishedTaskIds");
            rs = q.getResultList();
            if (rs.size() == 0) {
                logger.debug("No tasks found :-)");
                return;
            }
        } finally {
            if (em != null && em.isOpen())
                em.close();
        }

        logger.debug("Try to resume " + rs.size() + " tasks");
        for (String id : rs) {
            logger.debug("Resuming " + id);
            Resource k = find(getKeyForId(id));
        }
    }

    private void ensureInitialized() {
        try {
            initialize();
        } catch (Exception e) {
            logger.error("Unexpected initialization error", e);
            throw new RuntimeException(e);
        }
    }

    @NotNull
    public Query getListAllQuery(@NotNull EntityManager em) {
        return em.createNamedQuery("listAllTaskIds");
    }

    public void refresh(@NotNull Task resourceModel) throws ResourceException {

        ResourceKey key = getKeyForResourceModel(resourceModel);
        TaskResource tres = (TaskResource) find(key);

        tres.loadFromModel(resourceModel);
    }

    @NotNull
    public String getNickName() {
        return "task";
    }

    @NotNull
    public Class<Task> getModelClass() {
        return Task.class;
    }

    public ResourceKey getKeyForResourceModel(@NotNull final Task model) {
        return getKeyForId(model.getId());
    }

    public ResourceKey getKeyForId(@NotNull String id) {
        return new SimpleResourceKey(getKeyTypeName(), id);
    }

    @NotNull
    public URI getServiceAddress() {
        ensureInitialized();
        return serviceAddress;
    }

    @NotNull
    public EntityManagerFactory getEntityManagerFactory() {
        return getSystem().getEntityManagerFactory();
    }

    @NotNull
    public GNDMSystem getSystem() throws IllegalStateException {
        ensureInitialized();
        return system;
    }

    public void setSystem(@NotNull GNDMSystem system) throws IllegalStateException {
        throw new UnsupportedOperationException("System is read-only");
    }

    @Override
    protected Resource createNewInstance() throws ResourceException {
        final Resource resource = super.createNewInstance();
        ((TaskResource) resource).setResourceHome(this);
        return resource; // Overridden method
    }

    public Log getLog() {
        return logger;
    }

    @Override
    public TaskReference getResourceReference(final @NotNull ResourceKey key) throws Exception {
        EndpointReferenceType epr = AddressingUtils.createEndpointReference(serviceAddress.toString(), key);
        TaskReference ref = new TaskReference();
        ref.setEndpointReference(epr);
        return ref;
    }
}