/*
 * $Header: /home/cvspublic/jakarta-slide/src/stores/org/apache/slide/store/txfile/TxFileContentStore.java,v 1.10 2004/07/28 09:33:57 ib Exp $
 * $Revision: 1.10 $
 * $Date: 2004/07/28 09:33:57 $
 *
 * ====================================================================
 *
 * Copyright 1999-2002 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.apache.slide.store.txfile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.transaction.file.ResourceManagerException;
import org.apache.slide.common.ServiceAccessException;
import org.apache.slide.common.Uri;
import org.apache.slide.content.NodeRevisionContent;
import org.apache.slide.content.NodeRevisionDescriptor;
import org.apache.slide.content.RevisionAlreadyExistException;
import org.apache.slide.content.RevisionNotFoundException;
import org.apache.slide.store.ContentStore;

import org.apache.slide.store.util.*;

/**
 * Transactional content file store. 
 * 
 */
public class TxFileContentStore extends AbstractTxFileStoreService implements ContentStore {

    protected static final String LOG_CHANNEL = "file-content-store";
    
    public NodeRevisionContent retrieveRevisionContent(Uri uri, NodeRevisionDescriptor revisionDescriptor)
        throws ServiceAccessException, RevisionNotFoundException {

        String revisionUri = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();

        try {
            Object txId = getActiveTxId();
            InputStream is;
            if (txId != null) {
                is = rm.readResource(txId, revisionUri);
            } else {
                is = rm.readResource(revisionUri);
            }
            NodeRevisionContent result = new NodeRevisionContent();
            result.setContent(is);
            return result;
        } catch (ResourceManagerException e) {
            if (e.getStatus() == ResourceManagerException.ERR_NO_SUCH_RESOURCE) {
                throw new RevisionNotFoundException(uri.toString(), revisionDescriptor.getRevisionNumber());
            } else {
                throwInternalError(e, uri.toString());
                return null; // XXX fake (is never called)
            }
        }
    }

    public void createRevisionContent(
        Uri uri,
        NodeRevisionDescriptor revisionDescriptor,
        NodeRevisionContent revisionContent)
        throws ServiceAccessException, RevisionAlreadyExistException {
        String revisionUri = revisionUri = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();

        try {
            rm.createResource(getActiveTxId(), revisionUri, false);
            storeRevisionContent(uri, revisionDescriptor, revisionContent);
        } catch (RevisionNotFoundException e) {
            // Can not be, as we just created it. If it unexpectedly is, this is fatal 
            throwInternalError(e, uri.toString());
        } catch (ResourceManagerException e) {
            if (e.getStatus() == ResourceManagerException.ERR_RESOURCE_EXISTS) {
                throw new RevisionAlreadyExistException(uri.toString(), revisionDescriptor.getRevisionNumber());
            } else {
                throwInternalError(e, uri.toString());
            }
        }
    }

    public void storeRevisionContent(
        Uri uri,
        NodeRevisionDescriptor revisionDescriptor,
        NodeRevisionContent revisionContent)
        throws ServiceAccessException, RevisionNotFoundException {
        String revisionUri = revisionUri = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();

        OutputStream os = null;
        InputStream is = null;
        try {
            os = rm.writeResource(getActiveTxId(), revisionUri);
            is = revisionContent.streamContent();

            if (is != null) {
                long contentBytes = FileHelper.copy(is, os);
                long contentLength = revisionDescriptor.getContentLength();
                revisionDescriptor.setContentLength(contentBytes);

                if (contentLength != -1 && contentBytes != contentLength) {
                    rm.deleteResource(getActiveTxId(), revisionUri);
                    throwInternalError("Content length does not match expected");
                }
            }
        } catch (IOException e) {
            throwInternalError(e, uri.toString());
        } catch (ResourceManagerException e) {
            if (e.getStatus() == ResourceManagerException.ERR_NO_SUCH_RESOURCE) {
                throw new RevisionNotFoundException(uri.toString(), revisionDescriptor.getRevisionNumber());
            } else {
                throwInternalError(e, uri.toString());
            }
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
            }
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
            }
        }
    }

    public void removeRevisionContent(Uri uri, NodeRevisionDescriptor revisionDescriptor)
        throws ServiceAccessException {
        String revisionUri = uri.toString() + "_" + revisionDescriptor.getRevisionNumber();
        try {
            rm.deleteResource(getActiveTxId(), revisionUri);
        } catch (ResourceManagerException e) {
            throwInternalError(e, uri.toString());
        }
    }

    public String toString() {
        return "TxContentFileStore at " + storeDir + "  working on " + workDir;
    }

    protected String getLogChannel() {
        return LOG_CHANNEL;
    }
}
