Example usage for org.springframework.core.io ClassPathResource getInputStream

List of usage examples for org.springframework.core.io ClassPathResource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource getInputStream.

Prototype

@Override
public InputStream getInputStream() throws IOException 

Source Link

Document

This implementation opens an InputStream for the given class path resource.

Usage

From source file:nl.surfnet.spring.security.opensaml.controller.AuthnRequestController.java

@RequestMapping(value = { "/OpenSAML.sso/Metadata" }, method = RequestMethod.GET)
public void metaData(HttpServletResponse response) throws IOException {
    /*//from  ww  w. j a v  a2s . c o  m
     * see https://rnd.feide.no/2010/01/05/
     * metadata_aggregation_requirements_specification/#section_5_5_3
     */
    response.setHeader("Content-Type", "application/xml");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    String result = IOUtils.toString(new ClassPathResource("metadata-template-sp.xml").getInputStream());

    result = result.replace("%VALID_UNTIL%",
            df.format(new DateTime().toDateMidnight().toDateTime().plusDays(1).toDate()));
    result = result.replace("%ENTITY_ID%", entityID);
    result = result.replace("%ASSERTION_CONSUMER_SERVICE_URL%", assertionConsumerServiceURL);

    Properties props = new Properties();
    props.load(new ClassPathResource("metadata.defaults.properties").getInputStream());

    if (StringUtils.hasText(metaDataProperties)) {
        ClassPathResource classPathResource = new ClassPathResource(metaDataProperties);
        if (classPathResource.exists()) {
            props.load(classPathResource.getInputStream());
        }
    }

    result = result.replace("%NAMEID_FORMAT%", props.getProperty("nameid-format"));

    result = result.replace("%SERVICE_NAME_EN%", props.getProperty("service-name-en"));
    result = result.replace("%SERVICE_NAME_NL%", props.getProperty("service-name-nl"));
    result = result.replace("%SERVICE_DESCRIPTION_EN%", props.getProperty("service-description-en"));
    result = result.replace("%SERVICE_DESCRIPTION_NL%", props.getProperty("service-description-nl"));

    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_GIVEN_NAME%",
            props.getProperty("contact-person-administrative-given-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_SUR_NAME%",
            props.getProperty("contact-person-administrative-sur-name"));
    result = result.replace("%CONTACT_PERSON_ADMINISTRATIVE_EMAIL%",
            props.getProperty("contact-person-administrative-email"));

    result = result.replace("%CONTACT_PERSON_TECHNICAL_GIVEN_NAME%",
            props.getProperty("contact-person-technical-given-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_SUR_NAME%",
            props.getProperty("contact-person-technical-sur-name"));
    result = result.replace("%CONTACT_PERSON_TECHNICAL_EMAIL%",
            props.getProperty("contact-person-technical-email"));

    result = result.replace("%CONTACT_PERSON_SUPPORT_GIVEN_NAME%",
            props.getProperty("contact-person-support-given-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_SUR_NAME%",
            props.getProperty("contact-person-support-sur-name"));
    result = result.replace("%CONTACT_PERSON_SUPPORT_EMAIL%",
            props.getProperty("contact-person-support-email"));

    response.getOutputStream().write(result.getBytes());
    response.flushBuffer();

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * This test tries to simulate the shuffling that is done by MS Word 2003 
 * with regard to metadata extraction.//  w w w .ja  v a 2 s  .co m
 * <p>
 * 1: Setup an inbound rule for ContentMetadataExtractor.
 * 2: Write ContentDiskDriverTest1 file to ContentDiskDriver.docx
 * 3: Check metadata extraction for non update test
 * Simulate a WORD 2003 CIFS shuffle
 * 4: Write ContentDiskDriverTest2 file to ~WRD0003.TMP
 * 5: Rename ContentDiskDriver.docx to ~WRL0003.TMP
 * 6: Rename ~WRD0003.TMP to ContentDiskDriver.docx
 * 7: Check metadata extraction
 */
public void testMetadataExtraction() throws Exception {
    logger.debug("testMetadataExtraction");
    final String FILE_NAME = "ContentDiskDriver.docx";
    final String FILE_OLD_TEMP = "~WRL0003.TMP";
    final String FILE_NEW_TEMP = "~WRD0003.TMP";

    class TestContext {
        NodeRef testDirNodeRef;
        NodeRef testNodeRef;
        NetworkFile firstFileHandle;
        NetworkFile secondFileHandle;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testMetadataExtraction";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "test", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageDirCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteDirectory(testSession, testConnection, TEST_DIR);
            return null;
        }
    };

    try {
        tran.doInTransaction(deleteGarbageDirCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("create Test directory" + TEST_DIR);
    RetryingTransactionCallback<Void> createTestDirCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            testContext.testDirNodeRef = getNodeForPath(testConnection, TEST_DIR);
            assertNotNull("testDirNodeRef is null", testContext.testDirNodeRef);

            UserTransaction txn = transactionService.getUserTransaction();

            return null;

        }
    };
    tran.doInTransaction(createTestDirCB);
    logger.debug("Create rule on test dir");

    RetryingTransactionCallback<Void> createRuleCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            Rule rule = new Rule();
            rule.setRuleType(RuleType.INBOUND);
            rule.applyToChildren(true);
            rule.setRuleDisabled(false);
            rule.setTitle("Extract Metadata from content");
            rule.setDescription("ContentDiskDriverTest");

            Map<String, Serializable> props = new HashMap<String, Serializable>(1);
            Action extractAction = actionService.createAction("extract-metadata", props);

            ActionCondition noCondition1 = actionService.createActionCondition(NoConditionEvaluator.NAME);
            extractAction.addActionCondition(noCondition1);

            ActionCondition noCondition2 = actionService.createActionCondition(NoConditionEvaluator.NAME);
            CompositeAction compAction = actionService.createCompositeAction();
            compAction.setTitle("Extract Metadata");
            compAction.setDescription("Content Disk Driver Test - Extract Metadata");
            compAction.addAction(extractAction);
            compAction.addActionCondition(noCondition2);

            rule.setAction(compAction);

            ruleService.saveRule(testContext.testDirNodeRef, rule);

            logger.debug("rule created");

            return null;
        }
    };
    tran.doInTransaction(createRuleCB, false, true);

    /**
     * Create a file in the test directory
     */
    logger.debug("create test file in test directory");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            /**
             * Create the file we are going to use to test
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.firstFileHandle);

            // now load up the node with lots of other stuff that we will test to see if it gets preserved during the
            // shuffle.
            testContext.testNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);
            assertNotNull("testContext.testNodeRef is null", testContext.testNodeRef);

            // test non CM namespace property
            nodeService.setProperty(testContext.testNodeRef, TransferModel.PROP_ENABLED, true);

            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    logger.debug("step b: write content to test file");

    /**
     * Write ContentDiskDriverTest1.docx to the test file,
     */
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest1.docx");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest1.docx", fileResource);
            writeResourceToNetworkFile(fileResource, testContext.firstFileHandle);

            logger.debug("close the file, firstFileHandle");
            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    logger.debug("Step c: validate metadata has been extracted.");

    /**
     * c: check simple case of meta-data extraction has worked.
     */
    RetryingTransactionCallback<Void> validateFirstExtractionCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            Map<QName, Serializable> props = nodeService.getProperties(testContext.testNodeRef);

            assertTrue("Enabled property has been lost", props.containsKey(TransferModel.PROP_ENABLED));

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertEquals("size is wrong", 11302, data.getSize());
            assertEquals("mimeType is wrong",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    data.getMimetype());

            // These metadata values should be extracted.
            assertEquals("description is not correct", "This is a test file",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_DESCRIPTION));
            assertEquals("title is not correct", "ContentDiskDriverTest",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_TITLE));
            assertEquals("author is not correct", "mrogers",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_AUTHOR));

            return null;
        }
    };
    tran.doInTransaction(validateFirstExtractionCB, false, true);

    /**
     * d: Save the new file as an update file in the test directory
     */
    logger.debug("Step d: create update file in test directory " + FILE_NEW_TEMP);
    RetryingTransactionCallback<Void> createUpdateFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            /**
             * Create the file we are going to use to test
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.secondFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.secondFileHandle);

            return null;
        }
    };
    tran.doInTransaction(createUpdateFileCB, false, true);

    RetryingTransactionCallback<Void> writeFile2CB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest2.docx");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest2.docx", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.secondFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.secondFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFile2CB, false, true);

    /**
     * rename the old file
     */
    logger.debug("move old file out of the way.");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME,
                    TEST_DIR + "\\" + FILE_OLD_TEMP);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * Check the old file has gone.
     */
    RetryingTransactionCallback<Void> validateOldFileGoneCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            try {
                driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            } catch (IOException e) {
                // expect to go here since previous step renamed the file.
            }

            return null;
        }
    };
    tran.doInTransaction(validateOldFileGoneCB, false, true);

    //        /**
    //         * Check metadata extraction on intermediate new file
    //         */
    //        RetryingTransactionCallback<Void> validateIntermediateCB = new RetryingTransactionCallback<Void>() {
    //
    //            @Override
    //            public Void execute() throws Throwable
    //            {
    //               NodeRef updateNodeRef = driver.getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP);
    //               
    //               Map<QName, Serializable> props = nodeService.getProperties(updateNodeRef);
    //                        
    //               // These metadata values should be extracted from file2.
    //               assertEquals("intermediate file description is not correct", "Content Disk Test 2", props.get(ContentModel.PROP_DESCRIPTION));
    //               assertEquals("intermediate file title is not correct", "Updated", props.get(ContentModel.PROP_TITLE));
    //               assertEquals("intermediate file author is not correct", "mrogers", props.get(ContentModel.PROP_AUTHOR));
    //
    //               return null;
    //            }
    //        };
    //        
    //        tran.doInTransaction(validateIntermediateCB, true, true);

    /**
     * Move the new file into place, stuff should get shuffled
     */
    logger.debug("move new file into place.");
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("validate update has run correctly.");
    RetryingTransactionCallback<Void> validateUpdateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            // Check trx:enabled has been shuffled and not lost.
            assertTrue("node does not contain shuffled ENABLED property",
                    props.containsKey(TransferModel.PROP_ENABLED));

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertEquals("mimeType is wrong",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    data.getMimetype());
            assertEquals("size is wrong", 11265, data.getSize());

            // These metadata values should be extracted from file2.   However they will not be applied in PRAGMATIC mode.
            //               assertEquals("description is not correct", "Content Disk Test 2", props.get(ContentModel.PROP_DESCRIPTION));
            //               assertEquals("title is not correct", "Updated", props.get(ContentModel.PROP_TITLE));
            //               assertEquals("author is not correct", "mrogers", props.get(ContentModel.PROP_AUTHOR));

            return null;
        }
    };

    tran.doInTransaction(validateUpdateCB, true, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * ALF-12812/*from   w  ww  .j  a v a 2  s . com*/
 * 
 * This test tries to simulate the shuffling that is done by MS Word 2011 for Mac 
 * with regard to metadata extraction.  In particular the temporary file names are
 * different.
 * <p>
 * 1: Setup an update rule for ContentMetadataExtractor.
 * Simulate a WORD 2011 for Mac Create
 * 2: Write "Word Work File D_1725484373.tmp"
 * 3: Close file
 * 4: Rename "Word Work File D_1725484373.tmp" to ContentDiskDriver.docx
 * 5: Check metadata extraction
 */
public void testMetadataExtractionForMac() throws Exception {
    logger.debug("testMetadataExtractionForMac");
    final String FILE_NAME = "ContentDiskDriver.docx";
    //final String FILE_OLD_TEMP = "._Word Work File D_1725484373.tmp";
    final String FILE_NEW_TEMP = "Word Work File D_1725484373.tmp";

    class TestContext {
        NodeRef testDirNodeRef;
        NodeRef testNodeRef;
        NetworkFile firstFileHandle;
        //            NetworkFile secondFileHandle;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testMetadataExtractionForMac";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "cifs", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageDirCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteDirectory(testSession, testConnection, TEST_DIR);
            return null;
        }
    };

    try {
        tran.doInTransaction(deleteGarbageDirCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("create Test directory" + TEST_DIR);
    RetryingTransactionCallback<Void> createTestDirCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            testContext.testDirNodeRef = getNodeForPath(testConnection, TEST_DIR);
            assertNotNull("testDirNodeRef is null", testContext.testDirNodeRef);

            UserTransaction txn = transactionService.getUserTransaction();

            return null;

        }
    };
    tran.doInTransaction(createTestDirCB);
    logger.debug("Create rule on test dir");

    RetryingTransactionCallback<Void> createRuleCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            Rule rule = new Rule();
            rule.setRuleType(RuleType.UPDATE);
            rule.applyToChildren(true);
            rule.setRuleDisabled(false);
            rule.setTitle("Extract Metadata from update content");
            rule.setDescription("ContentDiskDriverTest");

            Map<String, Serializable> props = new HashMap<String, Serializable>(1);
            Action extractAction = actionService.createAction("extract-metadata", props);

            ActionCondition noCondition1 = actionService.createActionCondition(NoConditionEvaluator.NAME);
            extractAction.addActionCondition(noCondition1);

            ActionCondition noCondition2 = actionService.createActionCondition(NoConditionEvaluator.NAME);
            CompositeAction compAction = actionService.createCompositeAction();
            compAction.setTitle("Extract Metadata");
            compAction.setDescription("Content Disk Driver Test - Extract Metadata");
            compAction.addAction(extractAction);
            compAction.addActionCondition(noCondition2);

            rule.setAction(compAction);

            ruleService.saveRule(testContext.testDirNodeRef, rule);

            logger.debug("rule created");

            return null;
        }
    };
    tran.doInTransaction(createRuleCB, false, true);

    /**
     * Create a file in the test directory
     */
    logger.debug("create test file in test directory");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            /**
             * Create the file we are going to use to test
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull("first file Handle is null", testContext.firstFileHandle);

            // now load up the node with lots of other stuff that we will test to see if it gets preserved during the
            // shuffle.
            testContext.testNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP);
            assertNotNull("testContext.testNodeRef is null", testContext.testNodeRef);

            // test non CM namespace property
            nodeService.setProperty(testContext.testNodeRef, TransferModel.PROP_ENABLED, true);

            // Check that the temporary aspect has been applied.
            assertTrue("temporary aspect not applied",
                    nodeService.hasAspect(testContext.testNodeRef, ContentModel.ASPECT_TEMPORARY));
            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    logger.debug("step b: write content to test file");

    /**
     * Write ContentDiskDriverTest1.docx to the test file,
     */
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest1.docx");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest1.docx", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    logger.debug("Step b: rename the test file.");

    /**
     * Move the new file into place, stuff should get shuffled
     */
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("Step c: validate metadata has been extracted.");
    /**
    * c: check simple case of meta-data extraction has worked.
    */
    RetryingTransactionCallback<Void> validateFirstExtractionCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            Map<QName, Serializable> props = nodeService.getProperties(testContext.testNodeRef);

            assertTrue("Enabled property has been lost", props.containsKey(TransferModel.PROP_ENABLED));

            // Check that the temporary aspect has been applied.
            assertTrue("temporary aspect has not been removed",
                    !nodeService.hasAspect(testContext.testNodeRef, ContentModel.ASPECT_TEMPORARY));
            assertTrue("hidden aspect has not been removed",
                    !nodeService.hasAspect(testContext.testNodeRef, ContentModel.ASPECT_HIDDEN));

            // These metadata values should be extracted.
            assertEquals("description is not correct", "This is a test file",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_DESCRIPTION));
            assertEquals("title is not correct", "ContentDiskDriverTest",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_TITLE));
            assertEquals("author is not correct", "mrogers",
                    nodeService.getProperty(testContext.testNodeRef, ContentModel.PROP_AUTHOR));

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertEquals("mimeType is wrong",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    data.getMimetype());
            assertEquals("size is wrong", 11302, data.getSize());

            return null;
        }
    };
    tran.doInTransaction(validateFirstExtractionCB, false, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Simulates a SaveAs from Word2003/* ww  w.  j  a v  a 2s  .  c  o  m*/
 * 1. Create new document SAVEAS.DOC, file did not exist
 * 2. Create -WRDnnnn.TMP file, where 'nnnn' is a 4 digit sequence to make the name unique
 * 3. Rename SAVEAS.DOC to Backup of SAVEAS.wbk
 * 4. Rename -WRDnnnn.TMP to SAVEAS.DOC 
 */
public void testScenarioMSWord2003SaveAsShuffle() throws Exception {
    logger.debug("testScenarioMSWord2003SaveShuffle");
    final String FILE_NAME = "SAVEAS.DOC";
    final String FILE_OLD_TEMP = "SAVEAS.wbk";
    final String FILE_NEW_TEMP = "~WRD0002.TMP";

    class TestContext {
        NetworkFile firstFileHandle;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testScenarioMSWord2003SaveAsShuffle";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "test", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    /**
     * Create a file in the test directory
     */

    try {
        tran.doInTransaction(deleteGarbageFileCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("a) create new file");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            /**
             * Create the file we are going to use
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    /**
     * b) Save the new file
     * Write ContentDiskDriverTest3.doc to the test file,
     */
    logger.debug("b) move new file into place");
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest3.doc");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest3.doc", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    /**
     * c) rename the old file
     */
    logger.debug("c) rename old file");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME,
                    TEST_DIR + "\\" + FILE_OLD_TEMP);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * d) Move the new file into place, stuff should get shuffled
     */
    logger.debug("d) move new file into place");
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("e) validate results");
    /**
     * Now validate everything is correct
     */
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertNotNull("data is null", data);
            assertEquals("size is wrong", 26112, data.getSize());
            assertEquals("mimeType is wrong", "application/msword", data.getMimetype());

            return null;
        }
    };

    tran.doInTransaction(validateCB, true, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Simulates a SaveAs from Word2003 for a checked out file
 * //from   w  w  w .ja  v  a2s . co  m
 * 1. Create new document TESTFILE.DOC, file did not exist
 * 2. CheckOut TESTFILE.DOC
 * 3. Create -WRDnnnn.TMP file, where 'nnnn' is a 4 digit sequence to make the name unique
 * 4. Rename TESTFILE(Working Copy).DOC to Backup of SAVEAS.wbk
 * 5. Rename -WRDnnnn.TMP to TESTFILE(Working Copy).DOC 
 * 6  CheckIn working copy.
 * 7. Validate TESTFILE.DOC
 */
public void testScenarioMSWord2003SaveAsShuffleCheckedOutFile() throws Exception {
    logger.debug("testScenarioMSWord2003SaveShuffleLockedFile");
    final String FILE_NAME = "TESTFILE.DOC";
    final String FILE_OLD_TEMP = "SAVEAS.wbk";
    final String FILE_NEW_TEMP = "~WRD0002.TMP";

    class TestContext {
        NetworkFile firstFileHandle;
        String workingFileName;
        NodeRef workingCopy;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testScenarioMSWord2003ShuffleLockedFile";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "test", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    /**
     * Create a file in the test directory
     */

    try {
        tran.doInTransaction(deleteGarbageFileCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("a) create new file and check out");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            /**
             * Create the file we are going to use
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.firstFileHandle);
            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            /**
             * CheckOut the test node
             */
            NodeRef workingCopy = checkOutCheckInService.checkout(shuffledNodeRef);
            assertNotNull("Working copy is null", workingCopy);
            testContext.workingCopy = workingCopy;

            ChildAssociationRef ref = nodeService.getPrimaryParent(workingCopy);
            QName name = ref.getQName();
            testContext.workingFileName = ref.getQName().getLocalName();
            assertNotNull("working file name is null", testContext.workingFileName);

            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    /**
     * b) Save the new file
     * Write ContentDiskDriverTest3.doc to the test file,
     */
    logger.debug("b) move new file into place");
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest3.doc");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest3.doc", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    /**
     * c) rename the old working file
     */
    logger.debug("c) rename old file");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + testContext.workingFileName,
                    TEST_DIR + "\\" + FILE_OLD_TEMP);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * d) Move the new file into place, stuff should get shuffled
     */
    logger.debug("d) move new file into place");
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + testContext.workingFileName);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("e) now check in");

    /**
     * Now Check In
     */
    RetryingTransactionCallback<Void> checkInCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            checkOutCheckInService.checkin(testContext.workingCopy, null);
            return null;
        }
    };

    tran.doInTransaction(checkInCB, false, true);

    logger.debug("e) validate results");
    /**
     * Now validate everything is correct
     */
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertNotNull("data is null", data);
            assertEquals("size is wrong", 26112, data.getSize());
            assertEquals("mimeType is wrong", "application/msword", data.getMimetype());

            return null;
        }
    };

    tran.doInTransaction(validateCB, true, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Simulates a Save from Powerpoint 2011 Mac
 * 0. FileA.pptx already exists.//from   ww w  .  j  a v a2s. c  om
 * 1. Create new document FileA1.pptx
 * 2. Delete FileA.pptx
 * 3. Rename FileA1.pptx to FileA.pptx 
 */
public void testScenarioMSPowerpoint2011MacSaveShuffle() throws Exception {
    logger.debug("testScenarioMSPowerpoint2011MacSaveShuffle(");

    final String FILE_NAME = "FileA.pptx";
    final String FILE_NEW_TEMP = "FileA1.pptx";

    class TestContext {
        NetworkFile firstFileHandle;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testScenarioMSPowerpoint2011MacSaveShuffle";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "cifs", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    /**
     * Create a file in the test directory
     */

    try {
        logger.debug("expect to get exception - cleaning garbage");
        tran.doInTransaction(deleteGarbageFileCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("0) create new file");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            /**
             * Create the file we are going to use (FileA.pptx)
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.firstFileHandle);

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            NodeRef file1NodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);
            nodeService.addAspect(file1NodeRef, ContentModel.ASPECT_VERSIONABLE, null);

            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    /**
     * b) Save the new file
     * Write ContentDiskDriverTest3.doc to the test file,
     */
    logger.debug("b) write some content");
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest3.doc");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest3.doc", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    /**
     * c) delete the old file
     */
    logger.debug("c) delete old file");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * d) Move the new file into place, stuff should get shuffled
     */
    logger.debug("d) rename new file into place");
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("e) validate results");
    /**
     * Now validate everything is correct
     */
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertNotNull("data is null", data);
            assertEquals("size is wrong", 26112, data.getSize());
            assertEquals("mimeType is wrong", "application/msword", data.getMimetype());

            assertTrue("versionable aspect missing",
                    nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_VERSIONABLE));
            assertTrue("hidden aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_HIDDEN));
            assertTrue("temporary aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_TEMPORARY));

            return null;
        }
    };

    tran.doInTransaction(validateCB, true, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Simulates a Save from Excel 2011 Mac// w  w w . jav a2 s .  co  m
 * 0. FileA.xlsx already exists.
 * 1. Create new document ._A8A09200
 * 2. Delete FileA.xlsx
 * 3. Rename ._A8A09200 to FileA.xlsx 
 */
public void testScenarioMSExcel2011MacSaveShuffle() throws Exception {
    logger.debug("testScenarioMSExcel2011MacSaveShuffle(");

    final String FILE_NAME = "FileA.xlsx";
    final String FILE_NEW_TEMP = "._A8A09200";

    class TestContext {
        NetworkFile firstFileHandle;
    }
    ;

    final TestContext testContext = new TestContext();

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\testScenarioMSExcel2011MacSaveShuffle";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "cifs", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    /**
     * Create a file in the test directory
     */

    try {
        logger.debug("expect to get exception - cleaning garbage");
        tran.doInTransaction(deleteGarbageFileCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("0) create new file");
    RetryingTransactionCallback<Void> createFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {

            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            /**
             * Create the file we are going to use (FileA.xlsx)
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(testContext.firstFileHandle);

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            NodeRef file1NodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);
            nodeService.addAspect(file1NodeRef, ContentModel.ASPECT_VERSIONABLE, null);

            return null;
        }
    };
    tran.doInTransaction(createFileCB, false, true);

    /**
     * b) Save the new file
     * Write ContentDiskDriverTest3.doc to the test file,
     */
    logger.debug("b) write some content");
    RetryingTransactionCallback<Void> writeFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NEW_TEMP, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest3.doc");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest3.doc", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(writeFileCB, false, true);

    /**
     * c) delete the old file
     */
    logger.debug("c) delete old file");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * d) Move the new file into place, stuff should get shuffled
     */
    logger.debug("d) rename new file into place");
    RetryingTransactionCallback<Void> moveNewFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.renameFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NEW_TEMP,
                    TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    tran.doInTransaction(moveNewFileCB, false, true);

    logger.debug("e) validate results");
    /**
     * Now validate everything is correct
     */
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertNotNull("data is null", data);
            assertEquals("size is wrong", 26112, data.getSize());
            assertEquals("mimeType is wrong", "application/msword", data.getMimetype());

            assertTrue("versionable aspect missing",
                    nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_VERSIONABLE));
            assertTrue("hidden aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_HIDDEN));
            assertTrue("temporary aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_TEMPORARY));

            return null;
        }
    };

    tran.doInTransaction(validateCB, true, true);

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Simulates a Mac Lion Drag and Drop //from  w  w  w.j a va  2 s.  co  m
 * 0. ALF-15158.diff  already exists and is versionable
 * 1. Delete ALF-15158.diff 
 * 2. Create new document ALF-15158.diff 
 */
public void testMacDragAndDrop() throws Exception {
    logger.debug("testMacDragAndDrop()");

    final String FILE_NAME = "ALF-15158.diff";

    class TestContext {
        NetworkFile firstFileHandle;
        NodeRef file1NodeRef;
    }
    ;

    final String TEST_DIR = TEST_ROOT_DOS_PATH + "\\MacDragAndDrop";

    ServerConfiguration scfg = new ServerConfiguration("testServer");
    TestServer testServer = new TestServer("testServer", scfg);
    final SrvSession testSession = new TestSrvSession(666, testServer, "cifs", "remoteName");
    DiskSharedDevice share = getDiskSharedDevice();
    final TreeConnection testConnection = testServer.getTreeConnection(share);
    final RetryingTransactionHelper tran = transactionService.getRetryingTransactionHelper();

    /**
     * Clean up just in case garbage is left from a previous run
     */
    RetryingTransactionCallback<Void> deleteGarbageFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };

    /**
     * Create a file in the test directory
     */

    try {
        logger.debug("expect to get exception - cleaning garbage");
        tran.doInTransaction(deleteGarbageFileCB);
    } catch (Exception e) {
        // expect to go here
    }

    logger.debug("0) create new file");
    RetryingTransactionCallback<TestContext> createFileCB = new RetryingTransactionCallback<TestContext>() {
        @Override
        public TestContext execute() throws Throwable {

            TestContext ctx = new TestContext();
            /**
             * Create the test directory we are going to use 
             */
            FileOpenParams createRootDirParams = new FileOpenParams(TEST_ROOT_DOS_PATH, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            FileOpenParams createDirParams = new FileOpenParams(TEST_DIR, 0, AccessMode.ReadWrite,
                    FileAttribute.NTNormal, 0);
            driver.createDirectory(testSession, testConnection, createRootDirParams);
            driver.createDirectory(testSession, testConnection, createDirParams);

            /**
             * Create the file we are going to use (FileA.pptx)
             */
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            ctx.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);
            assertNotNull(ctx.firstFileHandle);

            driver.closeFile(testSession, testConnection, ctx.firstFileHandle);

            ctx.file1NodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);
            nodeService.addAspect(ctx.file1NodeRef, ContentModel.ASPECT_VERSIONABLE, null);

            return ctx;
        }
    };
    final TestContext testContext = tran.doInTransaction(createFileCB, false, true);

    /**
     * 1) delete the old file
     */
    logger.debug("1) delete old file");
    RetryingTransactionCallback<Void> renameOldFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            driver.deleteFile(testSession, testConnection, TEST_DIR + "\\" + FILE_NAME);
            return null;
        }
    };
    tran.doInTransaction(renameOldFileCB, false, true);

    /**
     * 2) CreateNewFile and write some new content
     * 
     */
    logger.debug("2) write some content");
    RetryingTransactionCallback<Void> restoreFileCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            testContext.firstFileHandle = driver.createFile(testSession, testConnection, createFileParams);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTest3.doc");
            assertNotNull("unable to find test resource filesys/ContentDiskDriverTest3.doc", fileResource);

            byte[] buffer = new byte[1000];
            InputStream is = fileResource.getInputStream();
            try {
                long offset = 0;
                int i = is.read(buffer, 0, buffer.length);
                while (i > 0) {
                    testContext.firstFileHandle.writeFile(buffer, i, 0, offset);
                    offset += i;
                    i = is.read(buffer, 0, buffer.length);
                }
            } finally {
                is.close();
            }

            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            return null;
        }
    };
    tran.doInTransaction(restoreFileCB, false, true);

    logger.debug("3) validate results");
    /**
     * Now validate everything is correct
     */
    RetryingTransactionCallback<Void> validateCB = new RetryingTransactionCallback<Void>() {

        @Override
        public Void execute() throws Throwable {
            NodeRef shuffledNodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);

            Map<QName, Serializable> props = nodeService.getProperties(shuffledNodeRef);

            ContentData data = (ContentData) props.get(ContentModel.PROP_CONTENT);
            assertNotNull("data is null", data);
            assertEquals("size is wrong", 26112, data.getSize());
            assertEquals("mimeType is wrong", "application/msword", data.getMimetype());

            assertTrue("versionable aspect missing",
                    nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_VERSIONABLE));
            assertTrue("hidden aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_HIDDEN));
            assertTrue("temporary aspect still applied",
                    !nodeService.hasAspect(shuffledNodeRef, ContentModel.ASPECT_TEMPORARY));

            assertEquals("Node ref has changed", shuffledNodeRef, testContext.file1NodeRef);
            return null;
        }
    };

    tran.doInTransaction(validateCB, true, true);
    logger.debug("end testMacDragAndDrop");

}

From source file:org.alfresco.filesys.repo.ContentDiskDriverTest.java

/**
 * Write the resource to the specified NetworkFile
 * @param resource//from   w w w  .  j a v a  2s.  c  o  m
 * @param file
 * @throws IOException
 */
private void writeResourceToNetworkFile(ClassPathResource resource, NetworkFile file) throws IOException {

    byte[] buffer = new byte[1000];
    InputStream is = resource.getInputStream();
    try {
        long offset = 0;
        int i = is.read(buffer, 0, buffer.length);
        while (i > 0) {
            file.writeFile(buffer, i, 0, offset);
            offset += i;
            i = is.read(buffer, 0, buffer.length);
        }
    } finally {
        is.close();
    }
}

From source file:org.alfresco.repo.tenant.TenantInterpreter.java

/**
 * Execute a single command using the BufferedReader passed in for any data needed.
 *
 * TODO: Use decent parser!/*from w  w  w  .j  a va 2  s  .c o  m*/
 *
 * @param line The unparsed command
 * @return The textual output of the command.
 */
public String executeCommand(String line) throws IOException {
    String[] command = line.split(" ");
    if (command.length == 0) {
        command = new String[1];
        command[0] = line;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bout);

    // repeat last command?
    if (command[0].equals("r")) {
        if (lastCommand == null) {
            return "No command entered yet.";
        }
        return "repeating command " + lastCommand + "\n\n" + executeCommand(lastCommand);
    }

    // remember last command
    lastCommand = line;

    // execute command
    if (command[0].equals("help")) {
        String helpFile = I18NUtil.getMessage("tenant_console.help");
        ClassPathResource helpResource = new ClassPathResource(helpFile);
        byte[] helpBytes = new byte[500];
        InputStream helpStream = helpResource.getInputStream();
        try {
            int read = helpStream.read(helpBytes);
            while (read != -1) {
                bout.write(helpBytes, 0, read);
                read = helpStream.read(helpBytes);
            }
        } finally {
            helpStream.close();
        }
    }

    else if (command[0].equals("show")) {
        if (command.length < 2) {
            return "Syntax Error, try 'help'.\n";
        }

        else if (command[1].equals("tenants")) {
            List<Tenant> tenants = tenantAdminService.getAllTenants();

            for (Tenant tenant : tenants) {
                if (tenant.isEnabled()) {
                    String contentRoot = tenant.getRootContentStoreDir();
                    out.println("Enabled  - Tenant: " + tenant.getTenantDomain() + " (" + contentRoot + ")");
                }
            }

            out.println("");

            for (Tenant tenant : tenants) {
                if (!tenant.isEnabled()) {
                    String contentRoot = tenant.getRootContentStoreDir();
                    out.println("Disabled - Tenant: " + tenant.getTenantDomain() + " (" + contentRoot + ")");
                }
            }
        }

        else if (command[1].equals("tenant")) {
            if (command.length != 3) {
                return "Syntax Error, try 'help'.\n";
            }

            String tenantDomain = new String(command[2]).toLowerCase();
            Tenant tenant = tenantAdminService.getTenant(tenantDomain);

            String contentRoot = tenant.getRootContentStoreDir();
            if (tenant.isEnabled()) {
                out.println("Enabled - Tenant: " + tenant.getTenantDomain() + " (" + contentRoot + ")");
            } else {
                out.println("Disabled - Tenant: " + tenant.getTenantDomain() + " (" + contentRoot + ")");
            }
        }

        else {
            return "No such sub-command, try 'help'.\n";
        }
    }

    else if (command[0].equals("create")) {
        if ((command.length < 3) || (command.length > 5)) {
            return "Syntax Error, try 'help'.\n";
        }

        String newTenant = new String(command[1]).toLowerCase();
        char[] tenantAdminRawPassword = new String(command[2]).toCharArray();
        String contentRoot = null;
        if (command.length >= 4) {
            contentRoot = new String(command[3]);
            if ("null".equals(contentRoot)) {
                contentRoot = null;
            }
        }

        String dbUrl = null;
        if (command.length >= 5) {
            // experimental (unsupported)
            dbUrl = new String(command[4]);
            if ("null".equals(dbUrl)) {
                dbUrl = null;
            }
        }

        tenantAdminService.createTenant(newTenant, tenantAdminRawPassword, contentRoot, dbUrl);

        out.println("created tenant: " + newTenant);
    }

    else if (command[0].equals("import")) {
        if ((command.length != 3) && (command.length != 4)) {
            return "Syntax Error, try 'help'.\n";
        }

        String newTenant = new String(command[1]).toLowerCase();
        File directorySource = new File(command[2]);

        String contentRoot = null;
        if (command.length == 4) {
            contentRoot = new String(command[3]);
        }

        tenantAdminService.importTenant(newTenant, directorySource, contentRoot);

        out.println("imported tenant: " + newTenant);
    }

    else if (command[0].equals("export")) {
        if (command.length != 3) {
            return "Syntax Error, try 'help'.\n";
        }

        String tenant = new String(command[1]).toLowerCase();
        File directoryDestination = new File(command[2]);

        tenantAdminService.exportTenant(tenant, directoryDestination);

        out.println("exported tenant: " + tenant);
    }

    // TODO - not fully working yet
    else if (command[0].equals("delete")) {
        if (command.length != 2) {
            return "Syntax Error, try 'help'.\n";
        }

        String tenantDomain = new String(command[1]).toLowerCase();

        tenantAdminService.deleteTenant(tenantDomain);
        out.println("Deleted tenant: " + tenantDomain);
    }

    else if (command[0].equals("enable")) {
        if (command.length != 2) {
            return "Syntax Error, try 'help'.\n";
        }

        String tenantDomain = new String(command[1]).toLowerCase();

        tenantAdminService.enableTenant(tenantDomain);
        out.println("Enabled tenant: " + tenantDomain);
    }

    else if (command[0].equals("disable")) {
        if (command.length != 2) {
            return "Syntax Error, try 'help'.\n";
        }

        String tenantDomain = new String(command[1]).toLowerCase();

        tenantAdminService.disableTenant(tenantDomain);
        out.println("Disabled tenant: " + tenantDomain);
    }

    else if (command[0].equals("changeAdminPassword")) {
        if (command.length != 3) {
            return "Syntax Error, try 'help'.\n";
        }

        String tenantDomain = new String(command[1]).toLowerCase();

        final String newPassword = new String(command[2]);
        final String tenantAdminUsername = tenantService.getDomainUser(getBaseAdminUsername(), tenantDomain);

        AuthenticationUtil.runAs(new RunAsWork<Object>() {
            public Object doWork() throws Exception {
                authenticationService.setAuthentication(tenantAdminUsername, newPassword.toCharArray());
                return null;
            }
        }, tenantAdminUsername);
    }

    else {
        return "No such command, try 'help'.\n";
    }

    out.flush();
    String retVal = new String(bout.toByteArray());
    out.close();
    return retVal;
}