try {
                if (refactorOperation.canExecute()) {
                    progressService.run(true, true, refactorOperation);
                }
            } catch (final InvocationTargetException | InterruptedException e) {
                BonitaStudioLog.error("Failed to remove contract input.", e);
                openErrorDialog(e);
            }

package org.bonitasoft.studio.contract.ui.property.input;

import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newHashSet;
import static org.bonitasoft.studio.common.emf.tools.ModelHelper.getAllElementOfTypeIn;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import org.bonitasoft.studio.common.NamingUtils;
import org.bonitasoft.studio.common.emf.tools.ModelHelper;
import org.bonitasoft.studio.common.jface.BonitaErrorDialog;
import org.bonitasoft.studio.common.jface.FileActionDialog;
import org.bonitasoft.studio.common.jface.databinding.CustomEMFEditObservables;
import org.bonitasoft.studio.common.log.BonitaStudioLog;
import org.bonitasoft.studio.contract.core.refactoring.RefactorContractInputOperation;
import org.bonitasoft.studio.contract.i18n.Messages;
import org.bonitasoft.studio.contract.ui.property.IViewerController;
import org.bonitasoft.studio.model.process.Contract;
import org.bonitasoft.studio.model.process.ContractConstraint;
import org.bonitasoft.studio.model.process.ContractContainer;
import org.bonitasoft.studio.model.process.ContractInput;
import org.bonitasoft.studio.model.process.ContractInputType;
import org.bonitasoft.studio.model.process.ProcessFactory;
import org.bonitasoft.studio.model.process.ProcessPackage;
import org.bonitasoft.studio.refactoring.core.RefactoringOperationType;
import org.bonitasoft.studio.refactoring.core.script.GroovyScriptRefactoringOperationFactory;
import org.bonitasoft.studio.refactoring.core.script.IScriptRefactoringOperationFactory;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.edit.command.DeleteCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.progress.IProgressService;
import com.google.common.base.Function;
import com.google.common.base.Predicate;

/**
 * @author Romain Bioteau
 */
public class ContractInputController implements IViewerController {

    private static final int NAME_COLUMN_INDEX = 0;

    private final IProgressService progressService;

    class EditNameRunnable implements Runnable {

        private final ColumnViewer viewer;

        private final ContractInput input;

        public EditNameRunnable(final ColumnViewer viewer, final ContractInput input) {
            this.viewer = viewer;
            this.input = input;
        }

        /*
         * (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            if (viewer != null && viewer.getControl() != null && !viewer.getControl().isDisposed()) {
                viewer.setSelection(new StructuredSelection(input), false);
                final Widget item = viewer.testFindItem(input);
                if (item != null && !item.isDisposed()) {
                    viewer.reveal(input);
                    viewer.editElement(input, NAME_COLUMN_INDEX);
                }
            }
        }
    }

    public ContractInputController(final IProgressService progressService) {
        this.progressService = progressService;
    }

    @Override
    public ContractInput add(final ColumnViewer viewer) {
        final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        final IObservableValue contractObservable = (IObservableValue) viewer.getInput();
        final ContractInput parentInput = (ContractInput) selection.getFirstElement();
        final Contract contract = (Contract) contractObservable.getValue();
        final ContractInput defaultInput = createDefaultInput(contract);
        final EObject targetContainer = targetContainer(parentInput, contract);
        CustomEMFEditObservables.observeList(targetContainer, inputContainerFeature(targetContainer)).add(defaultInput);
        viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));
        return defaultInput;
    }

    private EObject targetContainer(final ContractInput parentInput, final Contract contract) {
        return parentInput != null ? parentInput.eContainer() : contract;
    }

    public ContractInput addChildInput(final ColumnViewer viewer) {
        final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        if (selection.isEmpty()) {
            return null;
        }
        final ContractInput parentInput = (ContractInput) selection.getFirstElement();
        final ContractInput defaultInput = createDefaultInput(ModelHelper.getFirstContainerOfType(parentInput, Contract.class));
        CustomEMFEditObservables.observeList(parentInput, ProcessPackage.Literals.CONTRACT_INPUT__INPUTS).add(defaultInput);
        viewer.getControl().getDisplay().asyncExec(new EditNameRunnable(viewer, defaultInput));
        return defaultInput;
    }

    private ContractInput createDefaultInput(final Contract contract) {
        final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput();
        contractInput.setName(defaultContractInputName(contract));
        contractInput.setType(ContractInputType.TEXT);
        contractInput.setMapping(ProcessFactory.eINSTANCE.createContractInputMapping());
        return contractInput;
    }

    private String defaultContractInputName(final Contract contract) {
        return NamingUtils.generateNewName(newHashSet(transform(getAllElementOfTypeIn(contract, ContractInput.class), toInputName())), "input", 1);
    }

    private Function<ContractInput, String> toInputName() {
        return new Function<ContractInput, String>() {

            @Override
            public String apply(final ContractInput input) {
                return input.getName();
            }
        };
    }

    @Override
    public void remove(final ColumnViewer viewer) {
        final IObservableValue contractObservable = (IObservableValue) viewer.getInput();
        final IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
        final List<?> selectedInput = selection.toList();
        Contract contract = (Contract) contractObservable.getValue();
        if (openConfirmation(selectedInput)) {
            final RefactorContractInputOperation refactorOperation = newRefactorOperation(contract);
            final TransactionalEditingDomain editingDomain = editingDomain(contract);
            refactorOperation.setEditingDomain(editingDomain);
            refactorOperation.setAskConfirmation(shouldAskConfirmation());
            final CompoundCommand compoundCommand = refactorOperation.getCompoundCommand();
            for (final Object input : selectedInput) {
                final ContractInput contractInput = (ContractInput) input;
                contract = ModelHelper.getFirstContainerOfType(contractInput, Contract.class);
                // Parent input has been removed in current selection
                if (contract == null) {
                    continue;
                }
                refactorOperation.addItemToRefactor(null, contractInput);
                compoundCommand.append(DeleteCommand.create(editingDomain, contractInput));
                final Collection<ContractConstraint> constraintsReferencingInput = constraintsReferencingSingleInput(contract, contractInput);
                if (!constraintsReferencingInput.isEmpty()) {
                    compoundCommand.append(DeleteCommand.create(editingDomain, constraintsReferencingInput));
                }
            }

        }
    }

    protected boolean shouldAskConfirmation() {
        return true;
    }

    private Collection<ContractConstraint> constraintsReferencingSingleInput(final Contract contract, final ContractInput contractInput) {
        return newHashSet(filter(contract.getConstraints(), havingInputReference(contractInput.getName())));
    }

    private Predicate<ContractConstraint> havingInputReference(final String inputName) {
        return new Predicate<ContractConstraint>() {

            @Override
            public boolean apply(final ContractConstraint constraint) {
                return constraint.getInputNames().contains(inputName) && constraint.getInputNames().size() == 1;
            }
        };
    }

    protected TransactionalEditingDomain editingDomain(final Contract contract) {
        return TransactionUtil.getEditingDomain(contract);
    }

    protected RefactorContractInputOperation newRefactorOperation(final Contract contract) {
        return new RefactorContractInputOperation(ModelHelper.getFirstContainerOfType(contract, ContractContainer.class), scriptRefactoringOperationFactory(), RefactoringOperationType.REMOVE);
    }

    protected IScriptRefactoringOperationFactory scriptRefactoringOperationFactory() {
        return new GroovyScriptRefactoringOperationFactory();
    }

    private EReference inputContainerFeature(final EObject eContainer) {
        return eContainer instanceof ContractInput ? ProcessPackage.Literals.CONTRACT_INPUT__INPUTS : ProcessPackage.Literals.CONTRACT__INPUTS;
    }

    protected void openErrorDialog(final Throwable e) {
        if (!FileActionDialog.getDisablePopup()) {
            new BonitaErrorDialog(Display.getDefault().getActiveShell(), Messages.removeInputErrorTitle, Messages.removeInputErrorMsg, e).open();
        }
    }

    protected boolean openConfirmation(final List<?> selectedInput) {
        final StringBuilder message = new StringBuilder(Messages.removeInputConfirmationMessagePart1);
        for (final Object input : selectedInput) {
            message.append(SWT.CR);
            message.append("- " + ((ContractInput) input).getName());
            message.append(SWT.CR);
            message.append(Messages.removeInputConfirmationMessagesPart2);
        }
        return FileActionDialog.getDisablePopup() ? true : MessageDialog.openConfirm(Display.getDefault().getActiveShell(), Messages.removeInputConfirmationTitle, message.toString());
    }

    @Override
    public void moveUp(final ColumnViewer viewer) {
        throw new UnsupportedOperationException("Not implemented yet.");
    }

    @Override
    public void moveDown(final ColumnViewer viewer) {
        throw new UnsupportedOperationException("Not implemented yet.");
    }
}


@After
    public void tearDown() throws Exception

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

{
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {

        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);

        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


rt.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Asse

        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }

                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());
        try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }
    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");

                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


try {
            mblob.getLocalBlob().getInputStream();
            Assert.fail("Expected IOException since locator is not handled correctly");
        } catch (IOException io) {
            // expected
        } finally {
            sm.delete(mblob);
        }

/*
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 *
 * ***** END LICENSE BLOCK *****
 */
package com.zimbra.cs.store.external;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.MockProvisioning;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.MailboxTestUtil;
import com.zimbra.cs.store.Blob;
import com.zimbra.cs.store.BlobBuilder;
import com.zimbra.cs.store.IncomingBlob;
import com.zimbra.cs.store.MailboxBlob;
import com.zimbra.cs.store.StagedBlob;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.qa.unittest.TestUtil;

public class StoreManagerNegativeTest {

    static StoreManager originalStoreManager;

    @BeforeClass
    public static void init() throws Exception {
        MailboxTestUtil.initServer();
        MailboxTestUtil.initProvisioning();
        Provisioning.getInstance().createAccount("example@nnthink.com", "secret", new HashMap<String, Object>());
    }

    @Before
    public void setUp() throws Exception {
        originalStoreManager = StoreManager.getInstance();
        StoreManager.setInstance(getStoreManager());
        StoreManager.getInstance().startup();
    }

    @After
    public void tearDown() throws Exception {
        StoreManager.getInstance().shutdown();
        StoreManager.setInstance(originalStoreManager);
    }

    protected StoreManager getStoreManager() {
        return new BrokenStreamingStoreManager();
    }

    @Test
    public void nullLocator() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        Blob blob = incoming.getBlob();
        Assert.assertEquals("blob size = incoming written", bytes.length, blob.getRawSize());
        Assert.assertTrue("blob content = mime content", TestUtil.bytesEqual(bytes, blob.getInputStream()));
        StagedBlob staged = sm.stage(blob, mbox);
        Assert.assertEquals("staged size = blob size", blob.getRawSize(), staged.getSize());
        MailboxBlob mblob = sm.link(staged, mbox, 0, 0);
        Assert.assertEquals("link size = staged size", staged.getSize(), mblob.getSize());

    }

    @Test
    public void incorrectRemoteSize() throws Exception {
        Random rand = new Random();
        byte[] bytes = new byte[10000];
        rand.nextBytes(bytes);
        StoreManager sm = StoreManager.getInstance();
        IncomingBlob incoming = sm.newIncomingBlob("foo", null);
        OutputStream out = incoming.getAppendingOutputStream();
        out.write(bytes);
        try {
            incoming.getCurrentSize();
            Assert.fail("Expected exception since remote size is incorrect");
        } catch (IOException ioe) {
            // expected
        }
    }

    private class BrokenStreamingStoreManager extends SimpleStreamingStoreManager implements ExternalResumableUpload {

        @Override
        public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
            return null;
        }

        @Override
        public String writeStreamToStore(InputStream in, long actualSize, Mailbox mbox) throws IOException {
            super.writeStreamToStore(in, actualSize, mbox);
            return null;
        }

        @Override
        public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
            return null;
        }

        @Override
        public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException {
            return false;
        }

        @Override
        public ExternalResumableIncomingBlob newIncomingBlob(String id, Object ctxt) throws IOException, ServiceException {
            return new SimpleStreamingIncomingBlob(id, getBlobBuilder(), ctxt);
        }

        private class SimpleStreamingIncomingBlob extends ExternalResumableIncomingBlob {

            private final File file;

            public SimpleStreamingIncomingBlob(String id, BlobBuilder blobBuilder, Object ctx) throws ServiceException, IOException {
                super(id, blobBuilder, ctx);
                String baseName = uploadDirectory + "/upload-" + id;
                String name = baseName;
                synchronized (this) {
                    int count = 1;
                    File upFile = new File(name + ".upl");
                    while (upFile.exists()) {
                        name = baseName + "_" + count++;
                        upFile = new File(name + ".upl");
                    }
                    if (upFile.createNewFile()) {
                        ZimbraLog.store.debug("writing to new file %s", upFile.getName());
                        file = upFile;
                    } else {
                        throw new IOException("unable to create new file");
                    }
                }
            }

            @Override
            protected ExternalResumableOutputStream getAppendingOutputStream(BlobBuilder blobBuilder) throws IOException {
                return new SimpleStreamingOutputStream(blobBuilder, file);
            }

            @Override
            protected long getRemoteSize() throws IOException {
                // size returned wrong to test getCurrentSize() mismatches
                return file.length() - 1;
            }

            @Override
            public Blob getBlob() throws IOException, ServiceException {
                return new ExternalUploadedBlob(blobBuilder.finish(), file.getCanonicalPath());
            }
        }

        private class SimpleStreamingOutputStream extends ExternalResumableOutputStream {

            private final FileOutputStream fos;

            public SimpleStreamingOutputStream(BlobBuilder blobBuilder, File file) throws IOException {
                super(blobBuilder);
                this.fos = new FileOutputStream(file);
            }

            @Override
            protected void writeToExternal(byte[] b, int off, int len) throws IOException {
                fos.write(b, off, len);
            }
        }
    }
}


/*
 * JBoss, Home of Professional Open Source
 * as indicated by the @author tags.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * @author JBoss Inc.
 */
// Newcastle upon Tyne,
// Tyne and Wear,
package org.jboss.jbossts.qa.RawResources02Clients2;

/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
/*
 * Try to get around the differences between Ansi CPP and
 * K&R cpp with concatenation.
 */
/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CosTransactions.HeuristicHazard;
import org.omg.CosTransactions.HeuristicMixed;

public class Client095 {

{
        try {
            ORBInterface.initORB(args, null);
            OAInterface.initOA();
            String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);
            Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
            String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);
            Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
            ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
            resourceBehaviors1[0] = new ResourceBehavior();
            resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;
            resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
            resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
            resourceBehaviors2[0] = new ResourceBehavior();
            resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
            resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;
            resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            boolean correct = true;
            OTS.current().begin();
            service1.oper(resourceBehaviors1, OTS.current().get_control());
            service2.oper(resourceBehaviors2, OTS.current().get_control());
            try {
                OTS.current().commit(true);
                System.err.println("Commit succeeded when it shouldn't");
                correct = false;
            } catch (HeuristicMixed heuristicMixed) {
            } catch (HeuristicHazard heuristicHazard) {
            }
            correct = correct && service1.is_correct() && service2.is_correct();
            if (!correct) {
                System.err.println("service1.is_correct() or service2.is_correct() returned false");
            }
            ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
            ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
            correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);
            correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));
            if (correct) {
                System.out.println("Passed");
            } else {
                System.out.println("Failed");
            }
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
            System.out.println("Failed");
        }
        try {
            OAInterface.shutdownOA();
            ORBInterface.shutdownORB();
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
        }
    }
}


        try {
            ORBInterface.initORB(args, null);
            OAInterface.initOA();
            String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);
            Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
            String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);
            Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
            ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
            resourceBehaviors1[0] = new ResourceBehavior();
            resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;
            resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
            resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
            resourceBehaviors2[0] = new ResourceBehavior();
            resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
            resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;
            resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            boolean correct = true;
            OTS.current().begin();
            service1.oper(resourceBehaviors1, OTS.current().get_control());
            service2.oper(resourceBehaviors2, OTS.current().get_control());
            try {
                OTS.current().commit(true);
                System.err.println("Commit succeeded when it shouldn't");
                correct = false;
            } catch (HeuristicMixed heuristicMixed) {
            } catch (HeuristicHazard heuristicHazard) {
            }
            correct = correct && service1.is_correct() && service2.is_correct();
            if (!correct) {
                System.err.println("service1.is_correct() or service2.is_correct() returned false");
            }
            ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
            ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
            correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);
            correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));
            if (correct) {
                System.out.println("Passed");
            } else {
                System.out.println("Failed");
            }
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
            System.out.println("Failed");
        }

/*
 * JBoss, Home of Professional Open Source
 * as indicated by the @author tags.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * @author JBoss Inc.
 */
// Newcastle upon Tyne,
// Tyne and Wear,
package org.jboss.jbossts.qa.RawResources02Clients2;

/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
/*
 * Try to get around the differences between Ansi CPP and
 * K&R cpp with concatenation.
 */
/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CosTransactions.HeuristicHazard;
import org.omg.CosTransactions.HeuristicMixed;

public class Client095 {

    public static void main(String[] args) {

        try {
            OAInterface.shutdownOA();
            ORBInterface.shutdownORB();
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
        }
    }
}


try {
            OAInterface.shutdownOA();
            ORBInterface.shutdownORB();
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
        }

/*
 * JBoss, Home of Professional Open Source
 * as indicated by the @author tags.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * @author JBoss Inc.
 */
// Newcastle upon Tyne,
// Tyne and Wear,
package org.jboss.jbossts.qa.RawResources02Clients2;

/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
/*
 * Try to get around the differences between Ansi CPP and
 * K&R cpp with concatenation.
 */
/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CosTransactions.HeuristicHazard;
import org.omg.CosTransactions.HeuristicMixed;

public class Client095 {

    public static void main(String[] args) {
        try {
            ORBInterface.initORB(args, null);
            OAInterface.initOA();
            String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);
            Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
            String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);
            Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
            ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
            resourceBehaviors1[0] = new ResourceBehavior();
            resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;
            resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
            resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
            resourceBehaviors2[0] = new ResourceBehavior();
            resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
            resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;
            resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            boolean correct = true;
            OTS.current().begin();
            service1.oper(resourceBehaviors1, OTS.current().get_control());
            service2.oper(resourceBehaviors2, OTS.current().get_control());
            try {
                OTS.current().commit(true);
                System.err.println("Commit succeeded when it shouldn't");
                correct = false;
            } catch (HeuristicMixed heuristicMixed) {
            } catch (HeuristicHazard heuristicHazard) {
            }
            correct = correct && service1.is_correct() && service2.is_correct();
            if (!correct) {
                System.err.println("service1.is_correct() or service2.is_correct() returned false");
            }
            ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
            ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
            correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);
            correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));
            if (correct) {
                System.out.println("Passed");
            } else {
                System.out.println("Failed");
            }
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
            System.out.println("Failed");
        }


/*
 * JBoss, Home of Professional Open Source
 * as indicated by the @author tags.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * @author JBoss Inc.
 */
// Newcastle upon Tyne,
// Tyne and Wear,
package org.jboss.jbossts.qa.RawResources02Clients2;

/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
/*
 * Try to get around the differences between Ansi CPP and
 * K&R cpp with concatenation.
 */
/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CosTransactions.HeuristicHazard;
import org.omg.CosTransactions.HeuristicMixed;

public class Client095 {

    public static void main(String[] args) {
        try {
            ORBInterface.initORB(args, null);
            OAInterface.initOA();
            String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);
            Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
            String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);
            Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
            ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
            resourceBehaviors1[0] = new ResourceBehavior();
            resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;
            resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
            resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
            resourceBehaviors2[0] = new ResourceBehavior();
            resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
            resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;
            resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            boolean correct = true;
            OTS.current().begin();
            service1.oper(resourceBehaviors1, OTS.current().get_control());
            service2.oper(resourceBehaviors2, OTS.current().get_control());
            try {
                OTS.current().commit(true);
                System.err.println("Commit succeeded when it shouldn't");
                correct = false;
            } catch (HeuristicMixed heuristicMixed) {
            } catch (HeuristicHazard heuristicHazard) {
            }
            correct = correct && service1.is_correct() && service2.is_correct();
            if (!correct) {
                System.err.println("service1.is_correct() or service2.is_correct() returned false");
            }
            ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
            ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
            correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);
            correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));
            if (correct) {
                System.out.println("Passed");
            } else {
                System.out.println("Failed");
            }
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
            System.out.println("Failed");
        }
        try {
            OAInterface.shutdownOA();
            ORBInterface.shutdownORB();
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
        }


if (correct) {
                System.out.println("Passed");
            } else {
                System.out.println("Failed");
            }

/*
 * JBoss, Home of Professional Open Source
 * as indicated by the @author tags.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * @author JBoss Inc.
 */
// Newcastle upon Tyne,
// Tyne and Wear,
package org.jboss.jbossts.qa.RawResources02Clients2;

/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
/*
 * Try to get around the differences between Ansi CPP and
 * K&R cpp with concatenation.
 */
/*
 *
 * HP Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: Client095.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $
 */
import org.jboss.jbossts.qa.RawResources02.*;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.OTS;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
import org.omg.CosTransactions.HeuristicHazard;
import org.omg.CosTransactions.HeuristicMixed;

public class Client095 {

    public static void main(String[] args) {
        try {
            ORBInterface.initORB(args, null);
            OAInterface.initOA();
            String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]);
            Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1));
            String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]);
            Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2));
            ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1];
            resourceBehaviors1[0] = new ResourceBehavior();
            resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorRaiseHeuristicMixed;
            resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn;
            resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1];
            resourceBehaviors2[0] = new ResourceBehavior();
            resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteCommit;
            resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorRaiseHeuristicMixed;
            resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn;
            resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn;
            boolean correct = true;
            OTS.current().begin();
            service1.oper(resourceBehaviors1, OTS.current().get_control());
            service2.oper(resourceBehaviors2, OTS.current().get_control());
            try {
                OTS.current().commit(true);
                System.err.println("Commit succeeded when it shouldn't");
                correct = false;
            } catch (HeuristicMixed heuristicMixed) {
            } catch (HeuristicHazard heuristicHazard) {
            }
            correct = correct && service1.is_correct() && service2.is_correct();
            if (!correct) {
                System.err.println("service1.is_correct() or service2.is_correct() returned false");
            }
            ResourceTrace resourceTrace1 = service1.get_resource_trace(0);
            ResourceTrace resourceTrace2 = service2.get_resource_trace(0);
            correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareForget);
            correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepareRollbackForget) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback));

        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
            System.out.println("Failed");
        }
        try {
            OAInterface.shutdownOA();
            ORBInterface.shutdownORB();
        } catch (Exception exception) {
            System.err.println("Client095.main: " + exception);
            exception.printStackTrace(System.err);
        }
    }
}


@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)

import servlet.HttpServlet;
import servlet.HttpServletRequest;
import servlet.HttpServletResponse;
import servlet.HttpSession;
import java.io.PrintWriter;

/**
 * @author WangZhiJun
 */
public class User extends HttpServlet {

{
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        PrintWriter out = response.getWriter();
        String jsession = request.getJsessionid();
        if (jsession != null) {
            out.print("HTTP/1.1 200 OK\r\nSet-Cookie: JSESSIONID=" + jsession + "\r\n\r\n");
        } else {
            out.print("HTTP/1.1 200 OK\r\n\r\n");
        }
        out.print("");
        out.print("");
        out.print("welcome! " + username + "\r\n\r\n");
        out.print("sessionId:" + jsession);
        out.print("");
        out.print("");
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request, response);
    }
}


{
        doPost(request, response);
    }

import servlet.HttpServlet;
import servlet.HttpServletRequest;
import servlet.HttpServletResponse;
import servlet.HttpSession;
import java.io.PrintWriter;

/**
 * @author WangZhiJun
 */
public class User extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        PrintWriter out = response.getWriter();
        String jsession = request.getJsessionid();
        if (jsession != null) {
            out.print("HTTP/1.1 200 OK\r\nSet-Cookie: JSESSIONID=" + jsession + "\r\n\r\n");
        } else {
            out.print("HTTP/1.1 200 OK\r\n\r\n");
        }
        out.print("");
        out.print("");
        out.print("welcome! " + username + "\r\n\r\n");
        out.print("sessionId:" + jsession);
        out.print("");
        out.print("");
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)