text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.jcr;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.security.AccessControlList;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import javax.jcr.version.Version;
import org.junit.Test;
import org.modeshape.common.FixFor;
import org.modeshape.common.junit.SkipLongRunning;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.api.Binary;
import org.modeshape.jcr.api.JcrTools;
import org.modeshape.jcr.api.Workspace;
import org.modeshape.jcr.security.SimplePrincipal;
import org.modeshape.jcr.value.Name;
import org.modeshape.jcr.value.Path;

/**
 * Tests of round-trip importing/exporting of repository content.
 */
public class ImportExportTest extends SingleUseAbstractTest {

    private enum ExportType {
        SYSTEM,
        DOCUMENT
    }

    private static final String BAD_CHARACTER_STRING = "Test & <Test>*";

    private String expectedIdentifier = "e41075cb-a09a-4910-87b1-90ce8b4ca9dd";

    private void testImportExport( String sourcePath,
                                   String targetPath,
                                   ExportType useSystemView,
                                   boolean skipBinary,
                                   boolean noRecurse,
                                   boolean useWorkspace ) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (useSystemView == ExportType.SYSTEM) {
            session.exportSystemView(sourcePath, baos, skipBinary, noRecurse);
        } else {
            session.exportDocumentView(sourcePath, baos, skipBinary, noRecurse);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        if (useWorkspace) {
            // import via workspace ...
            session.getWorkspace().importXML(targetPath, bais, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        } else {
            // import via session ...
            session.importXML(targetPath, bais, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        }
    }

    @Test
    public void shouldImportExportEscapedXmlCharactersInSystemViewUsingSession() throws Exception {
        String testName = "importExportEscapedXmlCharacters";
        Node rootNode = session.getRootNode();
        Node sourceNode = rootNode.addNode(testName + "Source", "nt:unstructured");
        Node targetNode = rootNode.addNode(testName + "Target", "nt:unstructured");

        // Test data
        sourceNode.setProperty("badcharacters", BAD_CHARACTER_STRING);
        assertThat(sourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
        sourceNode.addNode(BAD_CHARACTER_STRING);

        testImportExport(sourceNode.getPath(), targetNode.getPath(), ExportType.SYSTEM, false, false, false);
        Node newSourceNode = targetNode.getNode(testName + "Source");
        newSourceNode.getNode(BAD_CHARACTER_STRING);
        assertThat(newSourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
    }

    @Test
    public void shouldImportExportEscapedXmlCharactersInSystemViewUsingWorkspace() throws Exception {
        String testName = "importExportEscapedXmlCharacters";
        Node rootNode = session.getRootNode();
        Node sourceNode = rootNode.addNode(testName + "Source", "nt:unstructured");
        Node targetNode = rootNode.addNode(testName + "Target", "nt:unstructured");

        // Test data
        sourceNode.setProperty("badcharacters", BAD_CHARACTER_STRING);
        assertThat(sourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
        sourceNode.addNode(BAD_CHARACTER_STRING);
        session.save();

        testImportExport(sourceNode.getPath(), targetNode.getPath(), ExportType.SYSTEM, false, false, true);
        Node newSourceNode = targetNode.getNode(testName + "Source");
        newSourceNode.getNode(BAD_CHARACTER_STRING);
        assertThat(newSourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
    }

    @FixFor("MODE-1405")
    @Test
    public void shouldImportProtectedContentUsingWorkpace() throws Exception {
        String testName = "importExportEscapedXmlCharacters";
        Node rootNode = session.getRootNode();
        Node sourceNode = rootNode.addNode(testName + "Source", "nt:unstructured");
        Node targetNode = rootNode.addNode(testName + "Target", "nt:unstructured");

        // Test data
        Node child = sourceNode.addNode("child");
        child.addMixin("mix:created");
        session.save();

        // Verify there are 'jcr:createdBy' and 'jcr:created' properties ...
        assertThat(child.getProperty("jcr:createdBy").getString(), is(notNullValue()));
        assertThat(child.getProperty("jcr:created").getString(), is(notNullValue()));

        testImportExport(sourceNode.getPath(), targetNode.getPath(), ExportType.SYSTEM, false, false, true);
        Node newSourceNode = targetNode.getNode(testName + "Source");
        Node newChild = newSourceNode.getNode("child");
        // Verify there are 'jcr:createdBy' and 'jcr:created' properties ...
        assertThat(newChild.getProperty("jcr:createdBy").getString(), is(notNullValue()));
        assertThat(newChild.getProperty("jcr:created").getString(), is(notNullValue()));

    }

    @Test
    public void shouldImportExportEscapedXmlCharactersInDocumentViewUsingSession() throws Exception {
        String testName = "importExportEscapedXmlCharacters";
        Node rootNode = session.getRootNode();
        Node sourceNode = rootNode.addNode(testName + "Source", "nt:unstructured");
        Node targetNode = rootNode.addNode(testName + "Target", "nt:unstructured");

        // Test data
        sourceNode.setProperty("badcharacters", BAD_CHARACTER_STRING);
        assertThat(sourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
        sourceNode.addNode(BAD_CHARACTER_STRING);

        testImportExport(sourceNode.getPath(), targetNode.getPath(), ExportType.DOCUMENT, false, false, false);
        Node newSourceNode = targetNode.getNode(testName + "Source");
        newSourceNode.getNode(BAD_CHARACTER_STRING);
        assertThat(newSourceNode.getProperty("badcharacters").getString(), is(BAD_CHARACTER_STRING));
    }

    @Test
    public void shouldImportSystemViewWithUuidsAfterNodesWithSameUuidsAreDeletedInSessionAndSaved() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Create the node under which the content will be imported ...
        session.getRootNode().addNode("/someNode");
        session.save();

        // Import the car content ...
        importFile("/someNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();
        // tools.printSubgraph(assertNode("/"));

        // Now delete the '/someNode/Cars' node (which is everything that was imported) ...
        Node cars = assertNode("/someNode/Cars");
        assertThat(cars.getIdentifier(), is(expectedIdentifier));
        assertNoNode("/someNode/Cars[2]");
        assertNoNode("/someNode[2]");
        cars.remove();
        session.save();

        // Now import again ...
        importFile("/someNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();

        // Verify the same Cars node exists ...
        cars = assertNode("/someNode/Cars");
        assertThat(cars.getIdentifier(), is(expectedIdentifier));
        assertNoNode("/someNode/Cars[2]");
        assertNoNode("/someNode[2]");
    }

    @Test
    public void shouldImportSystemViewWithUuidsAfterNodesWithSameUuidsAreDeletedInSessionButNotSaved() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Create the node under which the content will be imported ...
        session.getRootNode().addNode("/someNode");
        session.save();

        // Import the car content ...
        importFile("/someNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();

        // Now delete the '/someNode/Cars' node (which is everything that was imported) ...
        Node cars = assertNode("/someNode/Cars");

        assertThat(cars.getIdentifier(), is(expectedIdentifier));
        assertNoNode("/someNode/Cars[2]");
        assertNoNode("/someNode[2]");
        cars.remove();
        assertNoNode("/someNode/Cars");
        // session.save(); // DO NOT SAVE

        // Now import again ...
        importFile("/someNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();

        // Verify the same Cars node exists ...
        cars = assertNode("/someNode/Cars");
        assertThat(cars.getIdentifier(), is(expectedIdentifier));
        assertNoNode("/someNode/Cars[2]");
        assertNoNode("/someNode[2]");
    }

    @Test
    public void shouldImportSystemViewWithUuidsIntoDifferentSpotAfterNodesWithSameUuidsAreDeletedInSessionButNotSaved()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Create the node under which the content will be imported ...
        Node someNode = session.getRootNode().addNode("/someNode");
        session.getRootNode().addNode("/otherNode");
        session.save();

        // Import the car content ...
        importFile("/someNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();

        // Now delete the '/someNode/Cars' node (which is everything that was imported) ...
        Node cars = assertNode("/someNode/Cars");

        assertThat(cars.getIdentifier(), is(expectedIdentifier));
        assertNoNode("/someNode/Cars[2]");
        assertNoNode("/someNode[2]");
        cars.remove();

        // Now create a node at the same spot as cars, but with a different UUID ...
        Node newCars = someNode.addNode("Cars");
        assertThat(newCars.getIdentifier(), is(not(expectedIdentifier)));

        // session.save(); // DO NOT SAVE

        // Now import again ...
        importFile("/otherNode", "io/cars-system-view-with-uuids.xml", ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
        session.save();

        // Verify the same Cars node exists ...
        cars = assertNode("/otherNode/Cars");
        assertThat(cars.getIdentifier(), is(expectedIdentifier));

        // Make sure some duplicate nodes didn't show up ...
        assertNoNode("/sameNode/Cars[2]");
        assertNoNode("/sameNode[2]");
        assertNoNode("/otherNode/Cars[2]");
        assertNoNode("/otherNode[2]");
    }

    @FixFor("MODE-1137")
    @Test
    public void shouldExportContentWithUnicodeCharactersAsDocumentView() throws Exception {
        Node unicode = session.getRootNode().addNode("unicodeContent");
        Node desc = unicode.addNode("descriptionNode");
        desc.setProperty("ex1", "étudiant (student)");
        desc.setProperty("ex2", "où (where)");
        desc.setProperty("ex3", "forêt (forest)");
        desc.setProperty("ex4", "naïve (naïve)");
        desc.setProperty("ex5", "garçon (boy)");
        desc.setProperty("ex6", "multi\nline\nvalue");
        desc.setProperty("ex7", "prop \"value\" with quotes");
        desc.setProperty("ex7", "values with \r various \t\n : characters");
        session.save();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportDocumentView("/unicodeContent", baos, false, false);
        baos.close();

        predefineWorkspace("workspace2");

        InputStream istream = new ByteArrayInputStream(baos.toByteArray());
        Session session2 = repository.login("workspace2");
        session2.getWorkspace().importXML("/", istream, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);

        Node desc2 = session2.getNode("/unicodeContent/descriptionNode");
        assertSameProperties(desc, desc2);
    }

    @FixFor("MODE-1137")
    @Test
    public void shouldExportContentWithUnicodeCharactersAsSystemView() throws Exception {
        Node unicode = session.getRootNode().addNode("unicodeContent");
        Node desc = unicode.addNode("descriptionNode");
        desc.setProperty("ex1", "étudiant (student)");
        desc.setProperty("ex2", "où (where)");
        desc.setProperty("ex3", "forêt (forest)");
        desc.setProperty("ex4", "naïve (naïve)");
        desc.setProperty("ex5", "garçon (boy)");
        desc.setProperty("ex6", "multi\nline\nvalue");
        desc.setProperty("ex7", "prop \"value\" with quotes");
        desc.setProperty("ex7", "values with \n various \t\n : characters");
        session.save();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportSystemView("/unicodeContent", baos, false, false);
        baos.close();

        predefineWorkspace("workspace2");

        InputStream istream = new ByteArrayInputStream(baos.toByteArray());
        Session session2 = repository.login("workspace2");
        session2.getWorkspace().importXML("/", istream, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);

        Node desc2 = session2.getNode("/unicodeContent/descriptionNode");
        assertSameProperties(desc, desc2);
    }

    @Test
    public void shouldImportCarsSystemViewWithCreateNewBehaviorWhenImportedContentDoesNotContainJcrRoot() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertThat(session, is(notNullValue()));
        assertCarsImported();
    }

    @Test
    public void shouldImportCarsSystemViewWithRemoveExistingBehaviorWhenImportedContentDoesNotContainJcrRoot() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.REMOVE_EXISTING);
        assertThat(session, is(notNullValue()));
        assertCarsImported();
    }

    @Test
    public void shouldImportCarsSystemViewWithReplaceExistingBehaviorWhenImportedContentDoesNotContainJcrRoot() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.REPLACE_EXISTING);
        assertThat(session, is(notNullValue()));
        assertCarsImported();
    }

    @Test
    public void shouldImportCarsSystemViewWithRemoveExistingBehaviorWhenImportedContentDoesNotContainJcrRootOrAnyUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // Now import again to create a second copy ...
        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.REMOVE_EXISTING);
        assertThat(session, is(notNullValue()));
        assertNode("/a/b/Cars");
        assertNode("/a/b/Cars/Hybrid");
        assertNode("/a/b/Cars/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars/Sports/Infiniti G37");
        assertNode("/a/b/Cars/Utility/Land Rover LR3");
        assertNode("/a/b/Cars[2]");
        assertNode("/a/b/Cars[2]/Hybrid");
        assertNode("/a/b/Cars[2]/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars[2]/Sports/Infiniti G37");
        assertNode("/a/b/Cars[2]/Utility/Land Rover LR3");
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Import System View with NO 'jcr:root' node but WITH uuids
    // ----------------------------------------------------------------------------------------------------------------

    @Test
    public void shouldImportCarsSystemViewWithCreateNewBehaviorWhenImportedContentDoesNotContainJcrRootButDoesContainUnusedUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.REPLACE_EXISTING);
        print();

        // Verify that the original content has been left untouched ...
        assertThat(session, is(notNullValue()));
        assertNode("/a/b/Cars");
        assertNode("/a/b/Cars/Hybrid");
        assertNode("/a/b/Cars/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars/Sports/Infiniti G37");
        assertNode("/a/b/Cars/Utility/Land Rover LR3");
        assertNode("/a/b/Cars[2]");
        assertNode("/a/b/Cars[2]/Hybrid");
        assertNode("/a/b/Cars[2]/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars[2]/Sports");
    }

    @Test
    public void shouldImportCarsSystemViewWithCreateNewBehaviorWhenImportedContentDoesNotContainJcrRootButDoesContainAlreadyUsedUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.CREATE_NEW);
        print();

        // Verify that the original content has been left untouched ...
        assertThat(session, is(notNullValue()));
        assertNode("/a/b/Cars");
        assertNode("/a/b/Cars/Hybrid");
        assertNode("/a/b/Cars/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars/Sports/Infiniti G37");
        assertNode("/a/b/Cars/Utility/Land Rover LR3");
        assertNode("/a/b/Cars[2]");
        assertNode("/a/b/Cars[2]/Hybrid");
        assertNode("/a/b/Cars[2]/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars[2]/Sports");
    }

    @Test
    public void shouldImportCarsSystemViewOverExistingContentWhenImportedContentDoesNotContainJcrRootButDoesContainAlreadyUsedUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.REMOVE_EXISTING);
        print();

        // Verify that the original content has been replaced (since the SystemView contained UUIDs) and there is no copy ...
        assertThat(session, is(notNullValue()));
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.REPLACE_EXISTING);
        print();

        // Verify that the original content has been replaced (since the SystemView contained UUIDs) and there is no copy ...
        assertThat(session, is(notNullValue()));
        assertCarsImported();
    }

    @Test
    public void shouldImportCarsSystemViewWhenImportedContentDoesNotContainJcrRootButDoesContainAlreadyUsedUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/c", ImportBehavior.REPLACE_EXISTING);
        print();

        // Verify that the original content has been replaced (since the SystemView contained UUIDs) and there is no copy ...
        assertThat(session, is(notNullValue()));
        assertNode("/a/b");
        assertNode("/a/c");
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/d", ImportBehavior.REMOVE_EXISTING);
        print();

        // Verify that the original content has been replaced (since the SystemView contained UUIDs) and there is no copy ...
        assertThat(session, is(notNullValue()));
        assertNode("/a/b");
        assertNode("/a/c");
        assertNode("/a/d/Cars");
        assertNode("/a/d/Cars/Hybrid");
        assertNode("/a/d/Cars/Hybrid/Toyota Prius");
        assertNode("/a/d/Cars/Sports/Infiniti G37");
        assertNode("/a/d/Cars/Utility/Land Rover LR3");
        assertNoNode("/a/b/Cars[2]");
        assertNoNode("/a/b/Cars/Hybrid[2]");
        assertNoNode("/a/b/Cars/Hybrid/Toyota Prius[2]");
        assertNoNode("/a/b/Cars/Sports[2]");
    }

    @Test(expected = ItemExistsException.class)
    public void shouldFailToImportCarsSystemViewWithThrowBehaviorWhenImportedContentDoesNotContainJcrRootButDoesContainAlreadyUsedUuids()
            throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository with existing content ...
        assertImport("io/cars-system-view-with-uuids.xml", "/a/b", ImportBehavior.CREATE_NEW);
        assertCarsImported();

        // And attempt to reimport the same content (with UUIDs) into the repository that already has that content ...
        // print = true;
        assertImport("io/cars-system-view-with-uuids.xml", "/a/c", ImportBehavior.THROW);
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Import System View WITH 'jcr:root' node and NO matching uuids
    // ----------------------------------------------------------------------------------------------------------------

    @Test
    public void shouldImportSystemViewOfEntireWorkspaceWithNoAlreadyUsedUuids() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-system-view-with-uuids.xml", "/", ImportBehavior.THROW); // no matching UUIDs expected
        assertCarsImported();
    }

    @Test
    public void shouldImportSystemViewOfEntireWorkspaceExportedFromJackrabbit() throws Exception {
        // Register the Cars node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-system-view.xml", "/", ImportBehavior.THROW); // no matching UUIDs expected
        assertNode("/page1");
    }

    @Test
    public void shouldImportFileExportedFromJackrabbitContainingBinaryData() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");
        tools.registerNodeTypes(session, "cnd/magnolia.cnd");
        assertThat(session.getWorkspace().getNodeTypeManager().getNodeType("mgnl:content"), is(notNullValue()));

        // Now import the file ...
        String filename = "io/system-export-with-binary-data-and-uuids.xml";
        assertImport(filename, "/a", ImportBehavior.THROW); // no matching UUIDs expected
    }

    @FixFor("MODE-1026")
    @Test
    public void shouldImportFileExportedFromJackrabbitContainingBinaryStringData() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");
        tools.registerNodeTypes(session, "cnd/magnolia.cnd");
        assertThat(session.getWorkspace().getNodeTypeManager().getNodeType("mgnl:content"), is(notNullValue()));

        // Now import the file ...
        String filename = "io/system-export-with-xsitype-data-and-uuids.xml";
        assertImport(filename, "/a", ImportBehavior.THROW); // no matching UUIDs expected
        // print = true;
        print("/a");
        Node imageNode = assertNode("/a/company/image");
        assertThat(imageNode.getProperty("extension").getValue().getString(), is("gif"));
    }

    @Test
    public void shouldDecodeBase64() throws Exception {
        String base64Str = "R0lGODlhEAAQAMZpAGxZMW1bNW9bMm9cNnJdNXJdNnNfN3tnPX5oQIBqQYJrO4FrQoVtQIZuQohxQopyRopzQYtzRo10Qo51SI12SJB3SZN5Q5N5RpV7TJZ8TJd9SJh+TpyAT52CUJ+FUaOGU6OHUaSIUqGKUqaJVaiKVaGMV6mLVqWOXqyOVayOWLCSWa2VWrSVW7aXXbSbXbqaXrqaX7uaX7ubXsCfYrigcMKgY8OhY8SiZMWjZMWjZcelZsimZsqnZ8unZ8uoaMypaM2pac6qacOtbc+ratCsatKta8uwbdGvctOvbtSvbNWwbciyhdaxbdm2dda7ddq5gd26fN28gNe/ed6+htvCeuHAhd3EfOLCidrDmd7GfuLEj9/HfubKlufLmOjLmOnMmOnNmujNne3UpuzUqe3Vp+7VqO/VqO/Wqe7YsP///////////////////////////////////////////////////////////////////////////////////////////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAH8ALAAAAAAQABAAAAeJgH+Cg4SFhoeIiYqLhSciiR40S1hoY0JZVE5GK4MOZWdmZGJhJVumW1aDFGBfXl1cWiRSp1sufxYXV1VQUVNPMSAYDwgHEINNTEpJSEcwKR0VCwWERURDQUA9LSYcEwkDhD8+PDs6OCwjGxEIAYQyOTc2NTMqHxkNBgCFChIaKC8hGBBgJIARo0AAOw==";
        boolean print = false;

        // // Try apache ...
        // byte[] apacheBytes = org.apache.util.Base64.decode(base64Str.getBytes("UTF-8"));
        // if (print) {
        // System.out.println("Apache:     " + toString(apacheBytes));
        // System.out.println("   length:  " + apacheBytes.length);
        // }

        // Try jboss ...
        byte[] jbossBytes = org.jboss.util.Base64.decode(base64Str);
        if (print) {
            System.out.println("JBoss:      " + toString(jbossBytes));
            System.out.println("   length:  " + jbossBytes.length);
        }

        // Try jackrabbit ...
        ByteArrayOutputStream jrOutput = new ByteArrayOutputStream();
        org.apache.jackrabbit.test.api.Base64.decode(base64Str, jrOutput);
        byte[] jrBytes = jrOutput.toByteArray();
        if (print) {
            System.out.println("Jackrabbit: " + toString(jrBytes));
            System.out.println("   length:  " + jrBytes.length);
        }

        // Try modeshape ...
        byte[] msBytes = org.modeshape.common.util.Base64.decode(base64Str);
        if (print) {
            System.out.println("ModeShape:  " + toString(msBytes));
            System.out.println("   length:  " + msBytes.length);
        }

        // assertThat(apacheBytes, is(jbossBytes)); // apache pads 3 0s at the end
        assertThat(jrBytes, is(jbossBytes));
        assertThat(msBytes, is(jbossBytes));
    }

    String toString( byte[] bytes ) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(b);
        }
        return sb.toString();
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Import Document and System View containing constraint violations
    // ----------------------------------------------------------------------------------------------------------------

    @FixFor("MODE-1139")
    @Test(expected = ConstraintViolationException.class)
    public void shouldThrowCorrectExceptionWhenImportingDocumentViewContainingPropertiesThatViolateConstraints() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-document-view-with-constraint-violation.xml", "/", ImportBehavior.THROW);
    }

    @FixFor("MODE-1139")
    @Test(expected = ConstraintViolationException.class)
    public void shouldThrowCorrectExceptionWhenImportingSystemViewContainingPropertiesThatViolateConstraints() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-system-view-with-constraint-violation.xml", "/", ImportBehavior.THROW);
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Import Document View WITH 'jcr:root' node and WITH uuids
    // ----------------------------------------------------------------------------------------------------------------

    @Test
    public void shouldImportDocumentViewWithUuids() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-document-view-with-uuids.xml", "/", ImportBehavior.THROW); // no matching UUIDs expected
        assertCarsImported();
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Import Document View WITH constraints
    // ----------------------------------------------------------------------------------------------------------------

    @Test
    public void shouldImportDocumentViewWithReferenceConstraints() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-document-view-with-uuids.xml", "/", ImportBehavior.THROW); // no matching UUIDs expected
        assertCarsImported();
    }

    @FixFor("MODE-1171")
    @Test
    public void shouldExportAndImportMultiValuedPropertyWithSingleValue() throws Exception {
        Node rootNode = session.getRootNode();
        Node nodeA = rootNode.addNode("a", "nt:unstructured");
        Node nodeB = nodeA.addNode("b", "nt:unstructured");

        Value v = session.getValueFactory().createValue("singleValue");
        javax.jcr.Property prop = nodeB.setProperty("multiValuedProp", new Value[] { v });
        assertTrue(prop.isMultiple());

        prop = nodeB.setProperty("singleValuedProp", v);
        assertTrue(!prop.isMultiple());

        session.save();

        File exportFile = exportSystemView("/a");
        try {

            nodeA.remove();
            session.save();

            assertImport(exportFile, "/", ImportBehavior.THROW);

            prop = session.getProperty("/a/b/multiValuedProp");

            assertTrue(prop.isMultiple());
            assertThat(prop.getValues().length, is(1));
            assertThat(prop.getValues()[0].getString(), is("singleValue"));

            prop = session.getProperty("/a/b/singleValuedProp");

            assertTrue(!prop.isMultiple());
            assertThat(prop.getString(), is("singleValue"));
        } finally {
            exportFile.delete();
        }

    }

    @Test
    public void shouldImportIntoWorkspaceTheDocumentViewOfTheContentUsedInTckTests() throws Exception {
        Session session3 = repository.login();

        session.nodeTypeManager().registerNodeTypes(resourceStream("tck/tck_test_types.cnd"), true);
        session.getWorkspace().importXML("/",
                                         resourceStream("tck/documentViewForTckTests.xml"),
                                         ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        assertThat(session.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session.getNode("/testroot/workarea"), is(notNullValue()));
        assertNode("/testroot/workarea");

        Session session1 = repository.login();
        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session1.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session1.getNode("/testroot/workarea"), is(notNullValue()));
        session1.logout();

        assertThat(session3.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session3.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session3.getNode("/testroot/workarea"), is(notNullValue()));
        session3.logout();
    }

    @Test
    public void shouldImportIntoWorkspaceTheSystemViewOfTheContentUsedInTckTests() throws Exception {
        Session session3 = repository.login();

        session.nodeTypeManager().registerNodeTypes(resourceStream("tck/tck_test_types.cnd"), true);
        session.getWorkspace().importXML("/",
                                         resourceStream("tck/systemViewForTckTests.xml"),
                                         ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        assertThat(session.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertNode("/testroot/workarea");

        Session session1 = repository.login();
        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session1.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session1.getNode("/testroot/workarea"), is(notNullValue()));
        session1.logout();

        assertThat(session3.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session3.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session3.getNode("/testroot/workarea"), is(notNullValue()));
        session3.logout();
    }

    @Test
    public void shouldImportIntoSessionTheDocumentViewOfTheContentUsedInTckTests() throws Exception {
        Session session3 = repository.login();

        session.nodeTypeManager().registerNodeTypes(resourceStream("tck/tck_test_types.cnd"), true);
        session.importXML("/",
                          resourceStream("tck/documentViewForTckTests.xml"),
                          ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        assertThat(session.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session.getNode("/testroot/workarea"), is(notNullValue()));
        assertNode("/testroot/workarea");

        Session session1 = repository.login();
        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(false));

        session.save();

        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session1.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session1.getNode("/testroot/workarea"), is(notNullValue()));
        session1.logout();

        assertThat(session3.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session3.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session3.getNode("/testroot/workarea"), is(notNullValue()));
        session3.logout();
    }

    @Test
    public void shouldImportIntoSessionTheSystemViewOfTheContentUsedInTckTests() throws Exception {
        Session session3 = repository.login();

        session.nodeTypeManager().registerNodeTypes(resourceStream("tck/tck_test_types.cnd"), true);
        session.importXML("/",
                          resourceStream("tck/systemViewForTckTests.xml"),
                          ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        assertThat(session.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertNode("/testroot/workarea");

        Session session1 = repository.login();
        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(false));

        session.save();

        assertThat(session1.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session1.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session1.getNode("/testroot/workarea"), is(notNullValue()));
        session1.logout();

        assertThat(session3.getRootNode().hasNode("testroot/workarea"), is(true));
        assertThat(session3.getRootNode().getNode("testroot/workarea"), is(notNullValue()));
        assertThat(session3.getNode("/testroot/workarea"), is(notNullValue()));
        session3.logout();
    }

    @Test
    @FixFor("MODE-1573")
    public void shouldPerformRoundTripOnDocumentViewWithBinaryContent() throws Exception {
        JcrTools tools = new JcrTools();

        File binaryFile = new File("src/test/resources/io/binary.pdf");
        assert (binaryFile.exists() && binaryFile.isFile());

        File outputFile = File.createTempFile("modeshape_import_export_" + System.currentTimeMillis(), "_test");
        outputFile.deleteOnExit();
        tools.uploadFile(session, "file", binaryFile);
        session.save();
        session.exportDocumentView("/file", new FileOutputStream(outputFile), false, false);
        assertTrue(outputFile.length() > 0);

        session.getRootNode().getNode("file").remove();
        session.save();
        //sleep so that the binary can be properly cleaned up (this is done via a listener)
        Thread.sleep(200);

        session.getWorkspace().importXML("/", new FileInputStream(outputFile), ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        assertNotNull(session.getNode("/file"));
        assertNotNull(session.getNode("/file/jcr:content"));
        Property data = session.getNode("/file/jcr:content").getProperty("jcr:data");
        assertNotNull(data);
        Binary binary = (Binary)data.getBinary();
        assertNotNull(binary);
        assertEquals(binaryFile.length(), binary.getSize());
    }

    @FixFor("MODE-1478")
    @Test
    public void shouldBeAbleToImportDroolsXMLIntoSystemView() throws Exception {
        startRepositoryWithConfiguration(resourceStream("config/drools-repository.json"));
        session.importXML("/", resourceStream("io/drools-system-view.xml"), ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        assertNode("/drools:repository", "nt:folder");
        assertNode("/drools:repository/drools:package_area", "nt:folder");
        assertNode("/drools:repository/drools:package_area/defaultPackage", "drools:packageNodeType");
        assertNode("/drools:repository/drools:package_area/defaultPackage/assets", "drools:versionableAssetFolder");
        assertNode("/drools:repository/drools:package_area/defaultPackage/assets/drools", "drools:assetNodeType");
        assertNode("/drools:repository/drools:packagesnapshot_area", "nt:folder");
        assertNode("/drools:repository/drools:tag_area", "nt:folder");
        assertNode("/drools:repository/drools:state_area", "nt:folder");
        assertNode("/drools:repository/drools.package.migrated", "nt:folder");
    }

    @FixFor("MODE-1795")
    @Test
    public void shouldBeAbleToImportXmlFileThatUsesDefaultNamespaceWithNonBlankUri() throws Exception {
        session.importXML("/",
                          resourceStream("io/simple-document-view-with-default-namespace.xml"),
                          ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        // Get the prefix for the namespace used in the imported file ...
        String prefix = session.getWorkspace().getNamespaceRegistry().getPrefix("http://www.ns.com");
        assertNode("/" + prefix + ":childNode", "nt:unstructured");
    }

    @FixFor("MODE-1945")
    @Test
    public void shouldBeAbleToImportDocumentViewTwiceWithRemoveExistingCollisionMode() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cars.cnd");

        // Set up the repository ...
        assertImport("io/full-workspace-document-view-with-uuids.xml", "/", ImportBehavior.REMOVE_EXISTING);
        assertCarsImported();

        assertImport("io/full-workspace-document-view-with-uuids.xml", "/", ImportBehavior.REMOVE_EXISTING);
        assertCarsImported();
    }

    @FixFor("MODE-1945")
    @Test
    public void shouldBeAbleToImportSystemViewWithBinaryTwiceWithRemoveExistingCollisionMode2() throws Exception {
        // Register the node types ...
        tools.registerNodeTypes(session, "cnd/magnolia.cnd");
        // Now import the file ...
        assertImport("io/system-export-with-binary-data-and-uuids.xml", "/",
                     ImportBehavior.REMOVE_EXISTING); // no matching UUIDs
        // expected
        assertImport("io/system-export-with-binary-data-and-uuids.xml", "/",
                     ImportBehavior.REMOVE_EXISTING); // no matching UUIDs
        // expected
    }

    @Test
    @FixFor("MODE-1961")
    public void shouldBeAbleToImportTwiceWithoutLoosingMixins() throws Exception {
        tools.registerNodeTypes(session, "cnd/brix.cnd");
        session.save();

        InputStream brixWorkspace = resourceStream("io/brixWorkspace.xml");
        session.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        session.save();

        JcrNode root = (JcrNode)session.getItem("/brix:root");
        Set<Name> rootMixins = root.getMixinTypeNames();
        assertTrue(rootMixins.contains(session.nameFactory().create("brix:node")));

        brixWorkspace = resourceStream("io/brixWorkspace.xml");
        session.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        session.save();

        root = (JcrNode)session.getItem("/brix:root");
        rootMixins = root.getMixinTypeNames();
        assertTrue(rootMixins.contains(session.nameFactory().create("brix:node")));
    }

    @Test
    @FixFor("MODE-2039")
    public void shouldImportVersionedSystemView() throws Exception {
        assertImport("io/system-export-with-versioning.xml", "/", ImportBehavior.REMOVE_EXISTING); // no matching UUIDs expected
    }

    @Test
    @FixFor( "MODE-2172" )
    public void shouldDocumentImportCheckedInNodes() throws Exception {
        Node node1 = session.getRootNode().addNode("node1");
        node1.addMixin("mix:versionable");
        Node node2 = session.getRootNode().addNode("node2");
        node2.addMixin("mix:versionable");
        session.save();

        JcrVersionManager versionManager = session.getWorkspace().getVersionManager();
        versionManager.checkpoint("/node1");
        session.getNode("/node1").setProperty("11", "some string");
        session.getNode("/node1").setProperty("11a1", "some string");
        session.save();
        versionManager.checkin("/node1");

        versionManager.checkpoint("/node2");

        //export the data
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportDocumentView("/", baos, false, false);
        session.getWorkspace().importXML("/", new ByteArrayInputStream(baos.toByteArray()),
                                         ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);

        assertEquals(((org.modeshape.jcr.api.Property) session.getItem("/node1/11")).getString(), "some string");
        assertEquals(((org.modeshape.jcr.api.Property) session.getItem("/node1/11a1")).getString(), "some string");
    }

    @Test
    @FixFor( "MODE-2171" )
    public void shouldNotExportACLsInSystemView() throws Exception {
        Node node = session.getRootNode().addNode("node");
        AccessControlList acl = acl("/node");
        AccessControlManager accessControlManager = session.getAccessControlManager();
        acl.addAccessControlEntry(SimplePrincipal.EVERYONE, new Privilege[]{ accessControlManager.privilegeFromName(
                Privilege.JCR_ALL)});
        accessControlManager.setPolicy("/node", acl);
        assertTrue(hasMixin(node, ModeShapeLexicon.ACCESS_CONTROLLABLE_STRING));
        session.save();

        //export the data
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportSystemView("/", baos, false, false);

        node.remove();
        session.save();

        session.importXML("/", new ByteArrayInputStream(baos.toByteArray()),
                          ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        node = session.getNode("/node");
        assertTrue(hasMixin(node, ModeShapeLexicon.ACCESS_CONTROLLABLE_STRING));
        assertFalse(node.getNodes().hasNext());
    }

    @Test
    @FixFor( "MODE-2171" )
    public void shouldNotExportACLsInDocumentView() throws Exception {
        Node node = session.getRootNode().addNode("node");
        AccessControlList acl = acl("/node");
        AccessControlManager accessControlManager = session.getAccessControlManager();
        acl.addAccessControlEntry(SimplePrincipal.EVERYONE, new Privilege[]{ accessControlManager.privilegeFromName(
                Privilege.JCR_ALL)});
        accessControlManager.setPolicy("/node", acl);
        assertTrue(hasMixin(node, ModeShapeLexicon.ACCESS_CONTROLLABLE_STRING));
        session.save();

        //export the data
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportDocumentView("/", baos, false, false);

        node.remove();
        session.save();

        session.importXML("/", new ByteArrayInputStream(baos.toByteArray()),
                          ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        node = session.getNode("/node");
        assertTrue(hasMixin(node, ModeShapeLexicon.ACCESS_CONTROLLABLE_STRING));
        assertFalse(node.getNodes().hasNext());
    }

    @Test
    @FixFor( "MODE-2035" )
    public void shouldExportViewsWithLocks() throws Exception {
        Node node1 = session.getRootNode().addNode("node1");
        node1.addMixin("mix:lockable");
        Node node1_1 = node1.addNode("node1_1");
        node1_1.addMixin("mix:lockable");
        Node node2 = session.getRootNode().addNode("node2");
        node2.addMixin("mix:lockable");
        session.save();
        session.getWorkspace().lockManager().lock("/node1", true, true, Long.MAX_VALUE, null);
        session.getWorkspace().lockManager().lock("/node2", false, false, Long.MAX_VALUE, null);

        testImportExport("/", "/", ExportType.SYSTEM, true, false, true);
        testImportExport("/", "/", ExportType.DOCUMENT, true, false, true);
    }

    @Test
    @FixFor( "MODE-2192" )
    public void shouldImportSystemViewWithCheckedInNodes() throws Exception {
        tools.registerNodeTypes(session, "cnd/ecm.cnd");

        InputStream stream = resourceStream("io/ecm.xml");
        session.importXML("/", stream, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        session.save();
        JcrVersionManager versionManager = session.getWorkspace().getVersionManager();

        assertNode("/root");
        Node file = assertNode("/root/file1", "nt:file");
        assertTrue(file.isCheckedOut());
        Version fileVersion = versionManager.checkin("/root/file1");
        assertEquals("1.0", fileVersion.getName());
        assertEquals(2, versionManager.getVersionHistory("/root/file1").getAllVersions().getSize());

        Node doc1 = assertNode("/root/folder1/doc1", "nt:file");
        assertTrue(doc1.isCheckedOut());
        Version docVersion = versionManager.checkin("/root/folder1/doc1");
        assertEquals("1.0", docVersion.getName());
        assertEquals(2, versionManager.getVersionHistory("/root/folder1/doc1").getAllVersions().getSize());

        Node content = assertNode("/root/folder1/doc1/jcr:content", "nt:resource");
        assertTrue(content.isCheckedOut());
        Version contentVersion = versionManager.checkin("/root/folder1/doc1/jcr:content");
        assertEquals("1.0", contentVersion.getName());
        assertEquals(2, versionManager.getVersionHistory("/root/folder1/doc1/jcr:content").getAllVersions().getSize());
    }

    @Test
    @FixFor( "MODE-2012" )
    @SkipLongRunning( "There are 4 other test cases in JcrWorkspaceTest which validate the fix" )
    public void shouldBeAbleToImportAndCloneWorkspaces() throws Exception {
        String root = "/brix:root";

        // setup
        String workspaceA = "workspace_a";
        String workspaceB = "workspace_b";
        String workspaceC = "workspace_c";

        Workspace wsA, wsB, wsC;
        JcrSession sessA, sessB, sessC;

        JcrWorkspace rootWS = session.getWorkspace();
        rootWS.createWorkspace(workspaceA);
        sessA = repository.login(workspaceA);

        rootWS.createWorkspace(workspaceB);
        sessB = repository.login(workspaceB);

        rootWS.createWorkspace(workspaceC);
        sessC = repository.login(workspaceC);

        wsA = sessA.getWorkspace();
        wsB = sessB.getWorkspace();
        wsC = sessC.getWorkspace();

        // namespace registering
        wsA.getNamespaceRegistry().registerNamespace("brix", "http://brix-cms.googlecode.com");
        wsB.getNamespaceRegistry().registerNamespace("brix", "http://brix-cms.googlecode.com");
        wsC.getNamespaceRegistry().registerNamespace("brix", "http://brix-cms.googlecode.com");

        // initial imports
        tools.registerNodeTypes(sessA, "cnd/brix.cnd");
        sessA.save();
        InputStream brixWorkspace = resourceStream("io/brixWorkspace.xml");
        sessA.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        sessA.save();

        tools.registerNodeTypes(sessB, "cnd/brix.cnd");
        sessB.save();

        brixWorkspace = resourceStream("io/brixWorkspace.xml");
        sessB.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        sessB.save();

        tools.registerNodeTypes(sessC, "cnd/brix.cnd");
        sessC.save();

        brixWorkspace = resourceStream("io/brixWorkspace.xml");
        sessC.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        sessC.save();

        // re-import
        if (print) {
            new JcrTools().printSubgraph(sessA.getNode(root));
        }
        sessA.getItem(root).remove();
        sessA.save();

        brixWorkspace = resourceStream("io/brixWorkspace.xml");
        sessA.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        sessA.save();

        // now we clone the workspace A over the other ones at the path of root...
        wsB.getSession().removeItem(root);
        wsB.getSession().save();
        wsB.clone(workspaceA, root, root, true);
        wsB.getSession().save();

        wsC.getSession().removeItem(root);
        wsC.getSession().save();
        wsC.clone(workspaceB, root, root, true);
        wsC.getSession().save();

        // re-import a second time
        sessA.getItem(root).remove();
        sessA.save();

        brixWorkspace = resourceStream("io/brixWorkspace.xml");
        sessA.importXML("/", brixWorkspace, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
        sessA.save();

        sessA.logout();
        sessB.logout();
        sessC.logout();
    }

    private void assertCarsImported() throws RepositoryException {
        assertNode("/a/b/Cars");
        assertNode("/a/b/Cars/Hybrid");
        assertNode("/a/b/Cars/Hybrid/Toyota Prius");
        assertNode("/a/b/Cars/Sports/Infiniti G37");
        assertNode("/a/b/Cars/Utility/Land Rover LR3");
        assertNoNode("/a/b/Cars[2]");
        assertNoNode("/a/b/Cars/Hybrid[2]");
        assertNoNode("/a/b/Cars/Hybrid/Toyota Prius[2]");
        assertNoNode("/a/b/Cars/Sports[2]");
    }

    @FixFor( "MODE-2284" )
    @Test
    public void shouldRestoreBackreferencePropertiesAterImport() throws Exception {
        Node referenceableNode = session.getRootNode().addNode("referenceable");
        referenceableNode.addMixin(JcrMixLexicon.REFERENCEABLE.toString());
        Value strongRefValue = session.getValueFactory().createValue(referenceableNode, false);

        Node node1 = session.getRootNode().addNode("node1");
        node1.setProperty("prop1", strongRefValue);

        session.save();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        session.exportSystemView("/referenceable", outputStream, false, false);

        // Import node tree. This lose backreferences for all nodes in the imported tree
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        session.importXML("/referenceable", inputStream, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);

        // Now save the changes
        session.save();

        PropertyIterator propertyIterator = referenceableNode.getReferences();
        assertEquals(1, propertyIterator.getSize());
    }

    @Test
    @FixFor( "MODE-2359" )
    public void importingMultipleTimeWithReplaceExistingShouldNotIncreaseReferencesCount() throws Exception {
        registerNodeTypes("cnd/ab-references.cnd");
        session.getNode("/").addNode("testRoot");
        session.save();

        // A - this is a simple referenceable node
        // [test:a] > mix:referenceable
        session.importXML("/testRoot", resourceStream("io/a-references.xml"), ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        session.save();

        int repeatCount = 2;
        for (int i = 0; i < repeatCount; i++) {
            // B - this is a simple node that refers to the node A
            // [test:b] > mix:referenceable
            // - test:prop_ref_a (reference) < test:a
            session.importXML("/testRoot", resourceStream("io/b-references.xml"), ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
            session.save();
        }

        // make sure we only have 2 nodes (i.e. replace_existing worked)
        assertEquals(2, session.getNode("/testRoot").getNodes().getSize());

        AbstractJcrNode a = session.getNode("/testRoot/a");
        AbstractJcrNode b = session.getNode("/testRoot/b");

        // make sure "a' has only referrer
        assertEquals(1, a.getReferences().getSize());

        // Remove node B.
        b.remove();
        session.save();

        // After remove node B, node A should have zero referrers
        a.remove();
        session.save();
    }

    @Test
    @FixFor( "MODE-2375" )
    public void importingShouldKeepCorrectReferrerCount() throws Exception {
        Node testRoot = session.getRootNode().addNode("testRoot");

        //create the firt referrer first, so that it's exported before the referenceable node
        Node referrerOne = testRoot.addNode("referrerOne");

        // Create referenceable node
        Node referenceableNode = testRoot.addNode("referenceable");
        referenceableNode.addMixin(JcrMixLexicon.REFERENCEABLE.toString());
        Value strongRefValue = session.getValueFactory().createValue(referenceableNode, false);

        // Create second referrer
        Node referrerTwo = testRoot.addNode("referrerTwo");
        referrerTwo.setProperty("prop1", strongRefValue);

        // Set strong reference for the first referrer to referenceable node
        referrerOne.setProperty("prop1", strongRefValue);

        session.save();

        // Check that we have two referrers
        assertEquals(2, session.getNode("/testRoot/referenceable").getReferences().getSize());

        // Export nodes will be in the following order: referrerOne, referenceable, referrerTwo
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        session.exportSystemView("/testRoot", outputStream, false, false);

        // Cleanup
        session.getNode("/testRoot").remove();
        session.save();

        // Import nodes.
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        session.importXML("/", inputStream, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING);
        session.save();

        // Check that we have two referrers.
        // We must not lose the referrer from node referrerOne.
        assertEquals(2, session.getNode("/testRoot/referenceable").getReferences().getSize());
    }

    @Test
    @FixFor( "MODE-2482" )
    public void shouldSupportMultiValuedPropertiesInDocumentView() throws Exception {
        Node test = session.getRootNode().addNode("testRoot");
        test.setProperty("prop1", "value 1");
        String[] values = { "value 1", "value 2", "value 3" };
        test.setProperty("prop2", values);
        session.save();

        File file = new File("target/test-classes/document_view_multi_prop.xml");
        FileUtil.delete(file);
        FileOutputStream outputStream = new FileOutputStream(file);
        exportDocumentView("/testRoot", outputStream);

        session.getNode("/testRoot").remove();
        session.save();

        importFile("/", file.getName(), ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        assertNotNull(session.getNode("/testRoot"));
        Property p1 = (Property)session.getItem("/testRoot/prop1");
        assertFalse(p1.isMultiple());
        assertEquals("value 1", p1.getString());
        Property p2 = (Property)session.getItem("/testRoot/prop2");
        assertTrue(p2.isMultiple());
        Value[] jcrValues = p2.getValues();
        List<String> actualValues = new ArrayList<>(jcrValues.length);
        for (Value jcrValue : jcrValues) {
            actualValues.add(jcrValue.getString());
        }
        assertArrayEquals(values, actualValues.toArray());
    }

    @Test
    @FixFor( "MODE-2482 ")
    public void shouldSupportMultipleMixinsInDocumentView() throws Exception {
        registerNodeTypes("cnd/mixins.cnd");

        Node test = session.getRootNode().addNode("a", "nt:set");
        test.addMixin("mix:a");
        test.addMixin("mix:b");
        test.setProperty("jcr:a", "a");
        test.setProperty("jcr:b", "b");
        session.save();

        File file = new File("target/test-classes/document_view_mode_2482.xml");
        FileUtil.delete(file);
        FileOutputStream outputStream = new FileOutputStream(file);
        exportDocumentView("/a", outputStream);

        session.getRootNode().addNode("b", "nt:folder");
        session.save();
        importFile("/b", file.getName(), ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

        assertNotNull("/b/a");
        assertEquals("a", ((Property)session.getItem("/b/a/jcr:a")).getString());
        assertEquals("b", ((Property) session.getItem("/b/a/jcr:b")).getString());
    }

    // ----------------------------------------------------------------------------------------------------------------
    // Utilities
    // ----------------------------------------------------------------------------------------------------------------

    protected static enum ImportBehavior {
        CREATE_NEW(ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW),
        REPLACE_EXISTING(ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING),
        REMOVE_EXISTING(ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING),
        THROW(ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);

        private final int jcrValue;

        private ImportBehavior( int value ) {
            this.jcrValue = value;
        }

        public int getJcrValue() {
            return jcrValue;
        }
    }

    protected void importFile( String importIntoPath,
                               String resourceName,
                               int importBehavior ) throws Exception {
        // Import the car content ...
        InputStream stream = getClass().getClassLoader().getResourceAsStream(resourceName);
        assertThat(stream, is(notNullValue()));
        try {
            session.importXML(importIntoPath, stream, importBehavior); // shouldn't exist yet
        } finally {
            stream.close();
        }
    }

    protected Node assertImport( String resourceName,
                                 String pathToParent,
                                 ImportBehavior behavior ) throws RepositoryException, IOException {
        InputStream istream = resourceStream(resourceName);
        return assertImport(istream, pathToParent, behavior);
    }

    protected Node assertImport( File resource,
                                 String pathToParent,
                                 ImportBehavior behavior ) throws RepositoryException, IOException {
        InputStream istream = new FileInputStream(resource);
        return assertImport(istream, pathToParent, behavior);
    }

    protected Node assertImport( InputStream istream,
                                 String pathToParent,
                                 ImportBehavior behavior ) throws RepositoryException, IOException {
        // Make the parent node if it does not exist ...
        Path parentPath = path(pathToParent);
        assertThat(parentPath.isAbsolute(), is(true));
        Node node = session.getRootNode();
        boolean found = true;
        for (Path.Segment segment : parentPath) {
            String name = asString(segment);
            if (found) {
                try {
                    node = node.getNode(name);
                    found = true;
                } catch (PathNotFoundException e) {
                    found = false;
                }
            }
            if (!found) {
                node = node.addNode(name, "nt:unstructured");
            }
        }
        if (!found) {
            // We added at least one node, so we need to save it before importing ...
            session.save();
        }

        // Verify that the parent node does exist now ...
        assertNode(pathToParent);

        // Now, load the content of the resource being imported ...
        assertThat(istream, is(notNullValue()));
        try {
            session.getWorkspace().importXML(pathToParent, istream, behavior.getJcrValue());
        } finally {
            istream.close();
        }

        session.save();
        return node;
    }

    protected File exportSystemView( String pathToParent ) throws IOException, RepositoryException {
        assertNode(pathToParent);

        // Export to a string ...
        File tmp = File.createTempFile("JcrImportExportText-", "");
        FileOutputStream ostream = new FileOutputStream(tmp);
        boolean skipBinary = false;
        boolean noRecurse = false;
        session.exportSystemView(pathToParent, ostream, skipBinary, noRecurse);
        return tmp;
    }

    protected void exportDocumentView( String pathToParent,
                                       OutputStream ostream ) throws RepositoryException, IOException {
        boolean skipBinary = false;
        boolean noRecurse = false;
        try {
            session.exportDocumentView(pathToParent, ostream, skipBinary, noRecurse);
        } finally {
            ostream.close();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
The Charles Hays Secondary School wrestling team poses together during Northwest zones in Smithers on Feb. 17. Top row: Austin Houle, Dylon Cruz, Logan Sears, Tatum Acker and Josh Wittchen. Bottom row: Mason Dileta, Aaron Roubicek and Cody Schaeffer (Submitted photo)
Charles Hays wrestling on the rise
Prince Rupert Rainmakers wrestling team is ready for more success after their first season
Mar. 18, 2018 6:30 p.m.
When he began the process of building a wrestling program at Charles Hays Secondary School (CHSS), Dane Waldal wasn't sure what kind of success a fledgling team would have.
Four months and two individual zone championship wins later, he is still impressed by what his athletes were able to accomplish.
"I was absolutely blown away," Waldal said. "We got started a little bit late, and for all the imperfect things that happened this season, they managed to put on a great performance at zones."
READ MORE: MVP of the Week – Leaving it all on the mat
Competing in their first wrestling competition in years, the Rainmakers had a strong showing at the Northwest zones championships in Smithers on Feb. 17. Eight wrestlers from CHSS took the mat with Tatum Acker beating Neve Foreman to win the girls' 75-kilogram division and Josh Wittchen beating Hunter Aitken to win the boys' 78-kilogram division.
Waldal said most of the matches were closer than the final results indicated.
"Every kid had at least a chance at scoring a pin," he said. "They had their opponent close to a pin and they all scored points in their match, which is rare for a wrestler."
Waldal is originally from the Regina area in Saskatchewan, and had an opportunity to learn how to wrestle from national championship-level coaches. He has competed in both wrestling and amateur level mixed martial arts bouts, and over the years, developed a passion for the different arts and styles of fighting.
When he arrived at CHSS in 2017 as a teacher, Waldal saw an opportunity to share that passion with young athletes and to build up Prince Rupert's next generation of grapplers.
"I knew I might not have the most experience, but the school had wrestling mats and lots of interested kids," he said. "So it was up to me to give the kids an opportunity to get on the mats."
Waldal spent the early part of the school's fall term putting up posters, spreading the word and building up hype for the team. In November, the team had its first practice, which was attended by approximately 40 students. Waldal started by teaching the group some of the basic moves and techniques of wrestling before moving onto more complex movements.
READ MORE: MVP of the Week – The fighter's life
That first practice was a challenge and Waldal said he could see which of the athletes really enjoyed the grind.
"There's the first time you get on the mat and you're pushing each other and throwing each other," he said. "Some kids when they get thrown for the first time or they get down on the mat, they have trouble getting back up.
"What I find with good wrestlers is that those kinds of adverse situations are what get them more excited."
The wrestlers that remained on the team formed that core group that travelled to Smithers, and even though they did not all win their matches, Waldal is confident they have built a foundation that will carry them through to next year's season.
"I can't wait until next year," he said. "Most of them had only seen a wrestling mat for the first time in November.
"Next year we'll be ready."
matthew.allen@thenorthernview.com
MVP of the Week: Leaving it on the mat
Runners get festive in Terrace St. Patricks Day Run

redpajama_set_name: RedPajamaCommonCrawl


The key word to this issue is Fill Weight Value. This is referring to the fact that Excel 97-2003 (.xls) has a limit of 65,000 something rows that can be in a single spreadsheet. Scrub can only handle .csv and .txt files. This error means the user is using a .xlsx file (Excel 2007+). The user needs to open their Excel file and save it as a .csv file. Anything past 65,000 will be deleted when saving to .xls from .xlsx.


text:
Life with an emotional support animal
Service Dog Battle Over VA Hospital Denial Of Access
Service Dog Battle Over VA Hospital Denial Of Access.
WHAT DOES MY SERVICE DOG DO WHEN I PASS OUT?
WHAT AN ANXIETY ATTACK LOOKS LIKE WITH A SERVICE DOG
WARNING THIS VIDEO IS A SIMULATED ANXIETY ATTACK. if this will trigger you or you simply dont want to see what an anxiety attack looks like dont watch!!! i know this a very vulnerable thing for me to post on the internet but i am all about being real and showing what mental illness is like. yes my attacks are usually 10x worse than this but i simulated a short calmer one for the sake of training and filming. this is to educate people on how service dogs can help with anxiety attacks. i do not care about the hate i will get because this will help atleast one person. the angles are pretty bad and you could not see alot of what brantley is trained to do but you get the idea! he is trained to not leave me alone, prevent me from hurting myself, sooth me, and stop unwanted behaviors. that is why he uses his paws to stop me from hurting myself, performs dpt, tactile simulation, and interupts behaviors. if you see this happening in public to anyone leave them alone and let their service dog do their job:)
Service dog stabbed to death, allegedly by owner
Jacob Bushkin, 27, is accused of stabbing his 4-year-old golden retriever, Cub, more than 100 times.
Vietnam Veteran gets service dog
Former Dallas Cowboy surprises girl with new dog after her service dog was killed
Best Western Hotel Stripped Of Brand Name After Rejecting Boy Who Uses Service Dog
A Louisiana Best Western hotel that rejected a family with a service dog may get permanently terminated from the brand it represents.
Beau Vaughn has a rare type of epilepsy that requires him to always be accompanied by his assistance dog, Chip, who can sense when the boy is about to have a seizure, WAFB reported on Tuesday. While the Vaughns are not required to alert a hotel when they are coming with the service animal, Beau's mom, Karen, always does, just to be considerate.
But instead of getting an OK from the Baton Rouge establishment that is required by the Americans With Disabilities Act (ADA), the North Carolina mom got an email saying that their reservation had been canceled because the hotel isn't "pet friendly."
After WAFB reported the disheartening situation, the story went viral, leading advocates to call and complain and even threaten to riot.
The owner of the local Best Western told WAFB that it had made a "mistake," but the corporate office didn't take the situation lightly.
On Thursday, the news outlet reported that the corporate office decided to restrict the hotel from using the Best Western name and the hotel's future association with the brand is still being determined.
"We provide extensive training to ensure our hotels understand and address the needs of guests with special needs," the company said in a statement. "We deeply regret the matter and we will continue to proactively communicate ADA requirements and training to Best Western branded hotels to ensure all guests are treated with the utmost dignity and respect."
This case is particularly concerning considering how critical of a role such dogs play in the lives of people who live with conditions similar to Beau's.
Brianna Lynch also has epilepsy and has frequent seizures. She sometimes even forgets to breathe, which can send her into an episode.
While her family is vigilant about watching over their little girl, they've had to also elicit the help of Charlie, a Great Dane, who can detect when Brianna is about to have a seizure.
"Charlie is so sensitive to her needs — if the other dogs get boisterous, he will stand by her side to ensure she doesn't get knocked over," the girl's mom, Arabella Scanlan, told the Irish Times. "We know, when he is acting strange, she is going to have a seizure."
Girl, 13, wins Supreme Court case regarding service dog
WASHINGTON — The Supreme Court on Wednesday sided with a 13-year-old Michigan girl with cerebral palsy who spent years battling school officials for the right to bring her service dog — a goldendoodle named Wonder — to class.
The justices ruled unanimously that federal disability laws might allow Ehlena Fry to pursue her case in court without first having to wade through a lengthy administrative process.
The ruling is a win for advocacy groups that want to make it easier for disabled students to protect their rights under the Americans with Disabilities Act. School officials had argued that administrative remedies are an easier and less costly way to resolve educational disputes.
Writing for the court, Justice Elena Kagan said exhausting the administrative process is not always required in such cases. But she said further fact-finding is needed to decide whether Fry can pursue her case in court.
Lower courts had ruled against Fry, saying she first had to try informally resolving her dispute with the school district.
"We're thrilled that the Supreme Court has torn down unfair barriers faced by students who seek to vindicate their rights under the Americans with Disabilities Act," said Michael Steinberg, legal director of the American Civil Liberties Union in Michigan.The ACLU represented Fry throughout her legal proceedings.
Fry's family sought to use Wonder when Ehlena started kindergarten and suffered from severe mobility problems. Wonder was specially trained to help open doors, pick up items and give Ehlena a measure of independence.
But her school district 75 miles southwest of Detroit initially said Wonder could not accompany her and insisted adult aides could help Ehlena.
School officials later relented a bit, but placed so many restrictions on the dog that Ehlena's parents decided to home-school her. She later transferred to a different public school that welcomed Wonder.
At issue is the interplay of two federal disability laws. The school district said it could bar the dog under the Individuals with Disabilities Education Act, which allows a teacher's aide to assist students instead. That law requires families that contest school decisions to first go through administrative proceedings.
But the family said it could sue for damages under a different law, the Americans with Disabilities Act, because the district refused to accommodate Wonder over a two-and-a-half year period.
In her opinion for the court, Kagan offered two examples. In one, a child who uses a wheelchair sues a school for discrimination because the building lacks access ramps. That case, she said, could just as easily be brought against a library or theater and hinges on equality of access to public facilities, not whether a school's special education program is adequate.
In her other example, Kagan described a student with a learning disability who sues the school for failing to provide remedial math tutoring. She said the essence of that lawsuit is whether the school offers an adequate education.
Kagan said nothing in the Frys' lawsuit suggests a focus on the adequacy of her education. Rather, the family is asserting Ehlena's right to bring a service dog to school regardless of alternatives the school district provided.
But Kagan did not completely eliminate the possibility of a different outcome. She said the lower court must look more closely at the facts to decide.
Fry's mobility and independence has improved since she was younger and she now attends school without Wonder.
Naomi Gittins, managing director of legal advocacy at National School Boards Association, said the court's ruling may cause more confusion than help for lower courts trying to apply the law. Her group backed the Michigan school district in the case.
"Going right to court is never a good approach when you're talking about educational issues," she said. "It could result in court cases that run up bills rather than a parent talking about this with the school."
Service Dog Receives College Diploma Alongside Owner | NBC Nightly News
Amazing': Service dog helps 11-year-old girl with rare disorder walk
By A. Pawlowski
When Bella met George, something wonderful happened. Not long ago, the 11-year-old with a rare disorder was clinging to crutches, but now she's walking with the help of the Great Dane, a 2-year-old service dog who has become her best friend and constant companion.
Bella Burton, 11, gets a kiss from George, her service dog.Courtesy Burton family
She's made so much progress, the family was recently astonished to see her dash and frolic in the grass as her big furry protector looked on.
"I don't remember the last time I watched my child run through the yard," Rachel Burton, Bella's mom, told TODAY. "Seeing her just run was amazing to us."
The Burtons, who live in Woburn, Massachusetts, will travel to Orlando, Florida, next month where George will be honored by the American Kennel Club for his impact on the family.
Bella and George share a light moment.Courtesy Burton family
It's been a long road for Bella and her loved ones.
When the girl was 2, her parents noticed she wasn't keeping up on her growth curve. The problem stumped her doctor, who suggested genetic testing to find out what was wrong. The tests revealed she had Morquio syndrome, a progressive disorder in which the body doesn't produce enough of a key enzyme. That leads to a buildup of sugar molecules, which can cause problems with bone development and growth.
It's estimated the syndrome occurs in only 1 of every 200,000 births.
George accompanies Bella to her medical appointments.Courtesy Burton family
In her young life so far, Bella has had nine major surgeries, including reconstruction of her hips and feet. She's also had problems with mobility, getting around on crutches but using them more to swing her legs rather than walking on them. Her parents worried she was losing muscle strength in her lower body, relying on her upper body instead to move.
That all changed when she met George.
The Burtons weren't looking for a service animal, but about two years ago, they heard about the Service Dog Project in Ipswich, Massachusetts, which trains and donates Great Danes for people with balance and mobility issues.
Standing tall, with George's support.Courtesy Burton family
With its impressive height and heft, a good temperament and easygoing lifestyle, the breed is perfect for the job, the non-profit explains.
Most dogs are paired with adults, but when the family began visiting, it was clear the girl was ready for a canine companion.
"Once we saw Bella being around those dogs, how she was always in such a great mood and she loved going there, we thought, 'What are we waiting for?'" Burton recalled.
"When she was visiting George and he didn't want her to leave his kennel, they were like, let's try them."
George is now 2 years old and weighs 131 pounds.Courtesy Burton family
The Burtons brought him home just for the weekend over several weeks at first, then permanently added George to the family in January. They're grateful the fully trained animal was donated by the Service Dog Project.
Bella weighs 44 pounds and stands 43 inches tall. Soon, she put away the crutches and began to walk, with the help of her furry 131-pound friend. With her height, the dog's back is right by her armpit, providing lots of stability.
Bella leans on George for support.Courtesy Burton family
"She leans on him for support like she would if she used one crutch. But it's much more exciting when it's a dog than a crutch," Burton said.
George now goes everywhere Bella goes. He spends the day with her at school, where he walks her from class to class and patiently lies in a bed right next to her desk. He doesn't bark or demand to go outside, Burton said. The other kids are used to his presence and know they can't pet him because he's there to work.
George is also a comfort during Bella's medical appointments, including a weekly six-hour infusion of a medicine that gives her more energy.
"At first, he did not like it when she would get her IV put in. He would want to get up and protect her. But then he realized it had to be done," Burton said.
At night, he climbs into bed with the little girl, often sleeping beside her.
Bedtime for Bella and George.Courtesy Burton family
Bella's prognosis is hard to predict, her mom said. Some people with Morquio syndrome have lived to 20, others are in their 40s and still fine. Bella continues to see specialists who monitor her for issues related to the disorder.
Each time, George is there.
"He's totally a member of the family now," Burton said.
SERVICE DOG SULLY HAS A NEW JOB WITH NAVY
Former President George H.W. Bush's service dog made headlines a when President Bush passed last year. Once again Sully is in the news with his new job at the U.S. Navy at Walter Reed National Military Medical Center outside Washington.
Sully's new appointment is the rank of hospital corpsman second class. Sully's swearing in;
"Your appointment as a petty officer in the United States Navy makes you heir to a long and proud tradition of naval leadership," said a Navy spokesman at the Bethesda, Maryland, ceremony. The dog then was outfitted with a new "military uniform" — a service dog vest representing the medical center's dog team.
"Do you affirm or pant as a hospital corpsman in the United States Navy that you will support, comfort and cure warriors and their families, active duty and retired? That you embrace our staff and bear unconditional love and solace, especially on busy days? That you take this obligation freely, without any promise of treats or tummy rubs and that you will faithfully discharge the duties to provide joy, love and nurturing for our soldiers, sailors, airmen, Marines, and sailors and their families?"
Sully joins the medical center's facility emotional support animal dog program. His duties will include reducing stress and increasing well-being among patients and staff. Sully captured hearts last year after a photo went viral of Sully resting near President Bush's casket at the US Capitol.
Trained by America's VetDogs — a nonprofit organization that trains service dogs for disabled military veterans and first responders — to be a service dog, therapy dog and guide dog, Sully is capable of doing a number of tasks, from answering phones to turning lights on and off.
"Not only is he good at retrieving things, he helped the President by opening doors, knew when to get assistance from someone else, and knew when Bush needed comfort, so he would place his head on his lap," Hibbard said.
The service dogs at Walter Reed collectively work over 200 hours per month and average 2,500 contacts, according to a spokesperson for for the facility.
Source Google News


text:
FacilityPro.com Comes Up with Another $40 Mil
ATLANTA-The provider of a B2B electronic marketplace for commercial property owners picked up $25 million in its September first-round financing effort.
By Judith Schonbak | October 27, 2000 at 01:01 AM
ATLANTA-FacilityPro.com seems to have found favor with investors. The provider of a B2B electronic marketplace for commercial property owners just completed its second round of funding for $40 million.
The Series B financing follows on the heels of the company's September 2000 first round for $25 million. First Union Capital Partners of Charlotte topped off the $40 million goal with a $5 million investment.
Series B also included an increased amount of $10 million from a previous investor, Austin Ventures, an Austin TX-based venture capital firm. The initial round of financing for FacilityPro.com came from Constellation Real Technologies, a consortium of large U.S. real estate companies.
FacilityPro.com plans to use the second-round monies to expand its online marketplace offerings and to add consulting and operating personnel, according to the company.
It is also expanding its board of directors from three members to six, including one board seat for First Union Capital Partners and two for Constellation Technologies. That brings the number of outside directors to four.
Founded two years ago, FacilityPro.com currently has more than 2,500 users at 600 locations in 43 states, representing 110 million sf of commercial space.
Westcore Buys 4M-SF Industrial Portfolio From USAA Real Estate
The firm closed the year with the acquisition of a 4 million-square-foot industrial portfolio located in nine major markets.


text:
The conformation of dynorphin A-(1–13) in aqueous solution as studied by fourier transform infrared spectroscopy
Resolve DOI: https://doi.org/10.1016/0022-2860(89)80010-9
Search for: Surewicz, Witlod K.1 ; Search for: Mantsch, Henry H.1
National Research Council Canada
Journal of Molecular Structure
Infrared spectra of commercial preparations of the opioid agonist dynorphin A-(1–13) contain an absorption band at 1673 cm⁻¹. While this band can be, and previously has been, interpreted as indicative of a β-sheet structure in dynorphin A-(1–13), we have now established that the band does not originate from the peptide per se, but that it arises from the antisymmetric COO⁻ stretching vibration of the counterion trifluoroacetate. After repurification, the IR spectrum of dynorphin A-(1–13) is devoid of the 1673 cm⁻¹ band and is highly characteristic of an unordered conformation of this peptide in aqueous solution. Trifluoroacetate and other organic counterions are likely to be present in commercial preparations of other synthetic peptides, and one should be careful with the interpretation of their IR spectra in the region of the conformation-sensitive amide bands.
Elsevier B.V.
0126dae3-44c2-4457-9013-5564a0e39466


text:
2 polls: U.S. Senate race in Texas is tightening between Ted Cruz, Beto O'Rourke
Two polls suggest U.S. Rep. Beto O'Rourke is within striking distance of U.S. Sen. Ted Cruz. Both put the U.S. Senate race in Texas in single digits.
2 polls: U.S. Senate race in Texas is tightening between Ted Cruz, Beto O'Rourke Two polls suggest U.S. Rep. Beto O'Rourke is within striking distance of U.S. Sen. Ted Cruz. Both put the U.S. Senate race in Texas in single digits. Check out this story on tcpalm.com: https://www.elpasotimes.com/story/news/2018/08/02/polls-u-s-senate-race-texas-tightens-ted-cruz-beto-orourke/888077002/
By Alex Samuels, The Texas Tribune Published 9:54 a.m. ET Aug. 2, 2018 | Updated 1:22 p.m. ET Aug. 2, 2018
U.S. Senate Candidate Beto O'Rourke at El Paso campaign event Sunday
U.S Rep. Beto O'Rourke talks from a stage to a large gathering of local supporters during a 'Menudo & Mariachi' campaign stop in his hometown of El Paso in a parking lot at 415 E. Yandell Drive near downtown El Paso Sunday. About 1,000 people showed up to have menudo, listen to a mariachi group and hear O'Rourke deliver a rousing talk in which he announced the start of a 34-day road trip to visit 50 cities and more than 100 town hall events. He said El Paso should be the example for the rest of the country. 'This is a time to celebrate the fact that people chose to come here to this community to start their lives in the United States of America in El Paso Texas USA.' 800 people sent in reservations via social media in advance, campaign workers said. O'Rourke said his campaign has raised $10.4 million from individual contributions without taking any money from political action committees or special interest groups. RUDY GUTIERREZ / EL PASO TIMES
Itzel Martinez, left, and Sebastian Moncayo pose for a photo with U.S. Senate Candidate Beto O'Rourke during a campaign event in El Paso Sunday. RUDY GUTIERREZ / EL PASO TIMES
U.S. Senate candidate U.S. Rep. Beto O'Rourke speaks to El Paso supporters during a 'Menudo & Mariachis' event July 29 at 415 E. Yandell Drive near Downtown El Paso. RUDY GUTIERREZ/EL PASO TIMES
Yadira Arellano with a Beto O'Rourke yard sign she picked up at O'Rourke's campaign event Sunday. RUDY GUTIERREZ / EL PASO TIMES
People line up for menudo at a 'Menudo & Mariachi' event for Democratic U.S. Senate candidate Beto O'Rourke Sunday near downtown El Paso. RUDY GUTIERREZ / EL PASO TIMES
Beto O'Rourke supporter Patti Wetzel shows off her dress during a campaign event Sunday. RUDY GUTIERREZ / EL PASO TIMES
Beto buttons at a campaign event Sunday. RUDY GUTIERREZ / EL PASO TIMES
Ireland Bowcutt, 2, looks up at Democratic U.S. Senate candidate Beto O'Rourke during a campaign event Sunday near downtown El Paso. RUDY GUTIERREZ / EL PASO TIMES
One of a number of food trucks at a campaign event for Democratic U.S. Senate candidate Beto O'Rourke Sunday. RUDY GUTIERREZ / EL PASO TIMES
Democratic U.S. Senate candidate Beto O'Rourke appeared at a 'Menudo & Mariachis' campaign event Sunday in El Paso. RUDY GUTIERREZ / EL PASO TIMES
Menudo is served at a campaign event for Democratic U.S. Senate candidate Beto O'Rourke Sunday at 415 E. Yandell Drive near downtown El Paso. RUDY GUTIERREZ / EL PASO TIMES
Victoria Carreto gets her photo taken with Democratic U.S. Senate Candidate Beto O'Rourke Sunday. RUDY GUTIERREZ / EL PASO TIMES
People line up for menudo at a campaign event for Democratic U.S. Senate candidate Beto O'Rourke Sunday. RUDY GUTIERREZ / EL PASO TIMES
Beto T-shirts on sale Sunday. RUDY GUTIERREZ / EL PASO TIMES
Aiden Alonzo, 6, gets his arm painted by Georgena Askew Sunday. RUDY GUTIERREZ / EL PASO TIMES
Democratic U.S. Senate candidate Beto O'Rourke greets Trish Owen Sunday. RUDY GUTIERREZ / EL PASO TIMES
Sen. Ted Cruz, R-Texas, speaks during a news conference at the U.S. Capitol on June 19, 2018 in Washington.(Photo: Alex Wroblewski, Getty Images)
Two polls released Wednesday suggest a a tightening race between U.S. Sen. Ted Cruz and U.S. Rep. Beto O'Rourke.
A new poll from Quinnipiac University gives Cruz a 6-point lead: 49 percent of registered Texas voters reported backing the Republican incumbent while 43 percent said they support O'Rourke, an El Paso Democrat. The poll's margin of error is 3.5 percent. The results are closer than a poll Quinnipiac released in late May, which showed Cruz holding an 11-point lead over his opponent.
"U.S. Sen. Ted Cruz has a slight, by no means overwhelming, lead," said Peter Brown, assistant director of the Quinnipiac Poll. "Congressman Beto O'Rourke has done a good job making the race competitive. With three months until Election Day, he is clearly in contention. A Democratic victory in the Lone Star state would be a serious blow to GOP hopes of keeping their U.S. Senate majority."
More: Beto O'Rourke accepts Ted Cruz debate challenge, asks for debate in El Paso
More: U.S. Senate candidate Beto O'Rourke makes announcement at El Paso campaign event
The poll found 50 percent of Texas voters had a favorable view of Cruz while 42 percent had an unfavorable view. O'Rourke, on the other hand, had a 33 percent favorability rating, with 43 percent of voters not knowing enough about the congressman to form an opinion of him.
Quinnipiac released its poll just hours after Texas Lyceum released polling that showed the race between Cruz and O'Rourke as in a dead heat.
Texas Lyceum showed Cruz having a slim 2-point lead over O'Rourke: 41 percent to 39 percent. Nineteen percent of voters said they were undecided. Cruz's lead in that poll fell within the 4.67 percent margin of error.
"O'Rourke continues to nip at Cruz's heels, but it's a long way to go until Election Day," Josh Blank, Lyceum's poll research director, said in a news release. "If this race looks different than the rest, that's probably because it is because a strong Democratic challenger raising prolific sums of money and tons of earned media."
More: Beto O'Rourke releases first video ad in Texas' Senate race against Ted Cruz
More: El Paso lawmakers Beto O'Rourke and Will Hurd win award for bipartisan road trip
Even before it was released, the Lyceum poll drew skepticism from Cruz supporters. Cruz's pollster Chris Wilson published an article on Mediumquestioning whether it would be accurate.
"Dating back to 2008 the Texas Lyceum has generously given Democrats a massive house effect boost of seven (7!!!) points," he wrote, adding that the poll has historically overestimated the share of the Hispanic vote.
As of July 11, O'Rourke had raised more than $23.6 million since he launched his Senate campaign in November, including more than $10.4 million raised in three months. Cruz and his affiliated fundraising political action committees raised more than $17.5 million as of July 11.
Other Texas political races
With 97 days before the November general election, both polls revealed good news for Gov. Greg Abbott in his bid for re-election against former Dallas County Sheriff Lupe Valdez. The Republican incumbent — who's sitting on a hefty war chest ahead of November — is leading his opponent by 16 percentage points with 22 percent of likely voters undecided, according to the Texas Lyceum poll. The Quinnipiac poll gave Abbott a 13-point lead over Valdez.
And two other Republican statewides – Lt. Gov. Dan Patrick and Attorney General Ken Paxton – hold 10-point leads over their Democratic challengers Mike Collier and Justin Nelson, respectively, according to the Lyceum poll. Quinnipiac did not poll the lieutenant governor or attorney general's races.
Meanwhile, President Donald Trump is in a less comfortable position among Texas voters. Among those surveyed in the Texas Lyceum poll, 52 percent said they disapproved of the president's job performance — including 85 percent of Democrats. Eighty-five percent of Republicans said they were satisfied with Trump. These numbers are on par with what Quinnipiac found: 46 percent of Texans said they approve of the job the president is doing, while 49 percent disapprove.
In its news release, Texas Lyceum said its poll was conducted via a telephone survey of adult Texans. Respondents were randomly selected and questioned by live interviewers, pollsters said.
This article originally appeared in The Texas Tribune.
The Texas Tribune is a nonprofit, nonpartisan media organization that informs Texans — and engages with them — about public policy, politics, government and statewide issues.
Read or Share this story: https://www.elpasotimes.com/story/news/2018/08/02/polls-u-s-senate-race-texas-tightens-ted-cruz-beto-orourke/888077002/