001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 *
012 * $Id$
013 */
014package org.nuxeo.ecm.core.management.storage;
015
016import org.nuxeo.ecm.core.api.CoreSession;
017import org.nuxeo.ecm.core.api.NuxeoException;
018import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
019import org.nuxeo.ecm.core.management.api.StorageError;
020import org.nuxeo.runtime.api.Framework;
021
022/**
023 * Runner dedicated to mgmt doc operations
024 *
025 * @author "Stephane Lacoin [aka matic] <slacoin at nuxeo.com>"
026 */
027public abstract class DocumentStoreSessionRunner extends UnrestrictedSessionRunner {
028
029    protected static String repositoryName;
030
031    /**
032     * Should be Invoked at startup
033     */
034    public static void setRepositoryName(String name) {
035        repositoryName = name;
036    }
037
038    public DocumentStoreSessionRunner() {
039        super(repositoryName);
040    }
041
042    public DocumentStoreSessionRunner(CoreSession session) {
043        super(session);
044        if (!repositoryName.equals(session.getRepositoryName())) {
045            throw new IllegalArgumentException("Session is not attached to " + repositoryName);
046        }
047    }
048
049    /**
050     * Run with the nuxeo class loader, wrap client exception into errors
051     */
052    public void runSafe() {
053        ClassLoader jarCL = Thread.currentThread().getContextClassLoader();
054        ClassLoader bundleCL = Framework.class.getClassLoader();
055        try {
056            Thread.currentThread().setContextClassLoader(bundleCL);
057            runUnrestricted();
058        } catch (NuxeoException e) {
059            throw new StorageError("Storage error :  " + errorMessage(), e);
060        } finally {
061            Thread.currentThread().setContextClassLoader(jarCL);
062        }
063    }
064
065    protected String errorMessage() {
066        return String.format("%s:%s", getClass().getCanonicalName(), this.toString());
067    }
068
069}