podd.resources.services.DeleteDataStreamService.java Source code

Java tutorial

Introduction

Here is the source code for podd.resources.services.DeleteDataStreamService.java

Source

/*
 * Copyright (c) 2009 - 2010. School of Information Technology and Electrical
 * Engineering, The University of Queensland.  This software is being developed
 * for the "Phenomics Ontoogy Driven Data Management Project (PODD)" project.
 * PODD is a National e-Research Architecture Taskforce (NeAT) project
 * co-funded by ANDS and ARCS.
 *
 * PODD 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 3 of the License, or
 * (at your option) any later version.
 *
 * PODD 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 PODD.  If not, see <http://www.gnu.org/licenses/>.
 */

package podd.resources.services;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.ResourceException;
import podd.dataaccess.PoddObjectDAO;
import podd.exception.DataAccessException;
import podd.model.data.DataItem;
import podd.model.entity.PoddObject;
import podd.resources.AccessControlledResource;
import podd.resources.services.util.JsonHelper;
import podd.resources.util.error.SerivceErrorHandler;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.restlet.data.Status.CLIENT_ERROR_BAD_REQUEST;
import static org.restlet.data.Status.CLIENT_ERROR_FORBIDDEN;
import static org.restlet.data.Status.CLIENT_ERROR_UNAUTHORIZED;
import static org.restlet.data.Status.SERVER_ERROR_INTERNAL;
import static org.restlet.data.Status.SUCCESS_OK;
import static podd.model.audit.AuditLog.ERROR;
import static podd.model.audit.AuditLog.INSUFFICIENT_ACCESS;
import static podd.resources.services.ObjectService.GENERAL_MESSAGE_ID;
import static podd.server.authz.UserAction.DELETE;

/**
 * @author Faith Davies
 * @version $Id$
 */
public class DeleteDataStreamService extends AccessControlledResource {

    private PoddObjectDAO objectDAO;
    private JsonHelper jsonHelper;
    private SerivceErrorHandler errorHandler;

    private Map<String, Map<String, List<String>>> errorMap;
    private PoddObject poddObject;
    private URI objectURI;
    private String filename;

    public void setObjectDAO(PoddObjectDAO objectDAO) {
        this.objectDAO = objectDAO;
    }

    public void setJsonHelper(JsonHelper jsonHelper) {
        this.jsonHelper = jsonHelper;
    }

    public void setErrorHandler(SerivceErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Override
    protected Representation doAuthenticatedPost(Representation entity, Variant variant) throws ResourceException {
        Representation representation = null;
        try {
            poddObject.removeDataItem(filename);
            objectDAO.saveOrUpdate(poddObject);
            getResponse().setStatus(SUCCESS_OK);
            LOGGER.info("Action: " + authenticatedUser.getUserName() + " deleted data stream: " + objectURI + " : "
                    + filename);
        } catch (DataAccessException e) {
            getResponse().setStatus(SERVER_ERROR_INTERNAL);
            final String msg = "Error saving the object after the data stream was deleted. ";
            errorHandler.handleException(poddObject.getPid(), "Delete Data Stream Error", msg, e);
            auditLogHelper.auditAction(ERROR, authenticatedUser, "Delete Datastream Service: " + msg, e.toString());
        }

        if (!errorMap.isEmpty()) {
            representation = new JsonRepresentation(jsonHelper.convertErrorMap(errorMap));
        }
        return representation;
    }

    @Override
    protected void preGetAuthorisation() {
    }

    @Override
    protected Representation doAuthenticatedGet(Variant variant) throws ResourceException {
        auditLogHelper.auditAction(INSUFFICIENT_ACCESS, authenticatedUser,
                this.getRequest().getResourceRef().toString(), "");
        return redirectErrorStatus(CLIENT_ERROR_FORBIDDEN);
    }

    @Override
    protected Representation doUnauthenticatedGet(Variant variant) throws ResourceException {
        if (null == authenticatedUser) {
            getResponse().setStatus(CLIENT_ERROR_UNAUTHORIZED);
            errorHandler.handleError(GENERAL_MESSAGE_ID, "errorMessage",
                    "User must be authenticated to delete data streams");
        }
        if (!errorMap.isEmpty()) {
            return new JsonRepresentation(jsonHelper.convertErrorMap(errorMap));
        } else {
            return redirectErrorStatus(CLIENT_ERROR_UNAUTHORIZED);
        }
    }

    @Override
    protected boolean authoriseGet() {
        if (null != authenticatedUser && errorMap.isEmpty() && null != poddObject) {
            return manager.decide(authenticatedUser, poddObject, DELETE);
        }
        return false;
    }

    @Override
    protected void prePostAuthorisation(Representation entity) {
        LOGGER.debug("Delete Data Stream Service");
        errorMap = new HashMap<String, Map<String, List<String>>>();
        errorHandler.setAllObjectsErrorMap(errorMap);
        poddObject = null;
        filename = null;
        loadFormData(entity);

        if (null != objectURI && null != filename) {
            try {
                poddObject = objectDAO.load(objectURI.getFragment());
                if (null == poddObject) {
                    getResponse().setStatus(CLIENT_ERROR_BAD_REQUEST);
                    errorHandler.handleError(GENERAL_MESSAGE_ID, "Invalid URI",
                            "No object can be found with the given URI: " + objectURI);
                } else {
                    DataItem dataItem = poddObject.getDataItems().get(filename);
                    if (null == dataItem) {
                        getResponse().setStatus(CLIENT_ERROR_BAD_REQUEST);
                        errorHandler.handleError(GENERAL_MESSAGE_ID, "Invalid filename",
                                "No data stream can be found" + " for the given URI and filename combination: "
                                        + objectURI + " : " + filename);
                    }
                }
            } catch (DataAccessException e) {
                getResponse().setStatus(SERVER_ERROR_INTERNAL);
                final String msg = "Error loading object with URI: " + objectURI + ". ";
                errorHandler.handleException(GENERAL_MESSAGE_ID, "Invalid URI", msg, e);
                auditLogHelper.auditAction(ERROR, authenticatedUser, "Delete Datastream Service: " + msg,
                        e.toString());
            }
        } else {
            getResponse().setStatus(CLIENT_ERROR_BAD_REQUEST);
            errorHandler.handleError(GENERAL_MESSAGE_ID, "Invalid Parameters",
                    "The filename and object's URI must be sent in request with the keys: filename and URI");
        }
    }

    private void loadFormData(Representation entity) {
        objectURI = null;
        RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
        try {
            List<FileItem> list = upload.parseRepresentation(entity);
            for (FileItem item : list) {
                if (item.getFieldName().equals("URI") && item.isFormField()) {
                    objectURI = URI.create(item.getString().trim());
                }
                if (item.getFieldName().equals("filename") && item.isFormField()) {
                    filename = item.getString().trim();
                }
            }
        } catch (FileUploadException e) {
            getResponse().setStatus(SERVER_ERROR_INTERNAL);
            final String msg = "Error reading form data. ";
            errorHandler.handleException(GENERAL_MESSAGE_ID, "File Intialisation Error", msg, e);
            auditLogHelper.auditAction(ERROR, authenticatedUser, "Delete Datastream Service: " + msg, e.toString());
        }
    }
}