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

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

Introduction

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

Prototype

@Override
public File getFile() throws IOException 

Source Link

Document

This implementation returns a File reference for the underlying class path resource, provided that it refers to a file in the file system.

Usage

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

/**
 * Open and close of a project file changes certain header properties.
 * Test File 1 has been opened and closed.
 * @throws Exception//from w w  w .  j a v a  2s.  co m
 */
public void testProjectTrivialDiffProjectFiles() throws Exception {
    CIFSContentComparator contentComparator = new CIFSContentComparator();
    contentComparator.init();

    ClassPathResource file0Resource = new ClassPathResource("filesys/ContentComparatorTest0.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest0.mpp", file0Resource);

    ClassPathResource file1Resource = new ClassPathResource("filesys/ContentComparatorTest1.mpp");
    assertNotNull("unable to find test resource filesys/ContentComparatorTest1.mpp", file1Resource);

    /**
     * Compare trivially different project files, should ignore trivial differences and be equal 
     */
    {
        File file0 = file0Resource.getFile();
        File file1 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-project");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file1);
        assertTrue("compare trivially different project file, should be equal", result);
    }
}

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

/**
 * Open and close of an excel 2003 file changes certain header properties.
 * Test File 1 has been opened and closed in excel2003.
 * @throws Exception//from   w  w w .j  a va 2 s  .c  o m
 */
public void testDiffExcel2003Files() throws Exception {
    CIFSContentComparator contentComparator = new CIFSContentComparator();
    contentComparator.init();

    ClassPathResource file0Resource = new ClassPathResource("filesys/ContentComparatorTestExcel2003-1.xls");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestExcel2003-1.xls", file0Resource);

    ClassPathResource file1Resource = new ClassPathResource("filesys/ContentComparatorTestExcel2003-2.xls");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestExcel2003-2.xls", file1Resource);

    ClassPathResource file3Resource = new ClassPathResource("filesys/ContentComparatorTestExcel2003-3.xls");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestExcel2003-3.xls", file3Resource);

    ClassPathResource file4Resource = new ClassPathResource("filesys/ContentComparatorTestExcel2003-4.xls");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestExcel2003-4.xls", file4Resource);

    ClassPathResource file5Resource = new ClassPathResource("filesys/ContentComparatorTestExcel2003-5.xls");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestExcel2003-5.xls", file5Resource);

    /**
     * Compare trivially different excel files, should ignore trivial differences and be equal 
     */
    {
        File file0 = file0Resource.getFile();
        File file1 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-excel");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file1);
        assertTrue("compare trivially different project file, should be equal", result);
    }

    /**
     * Compare different project files, should not be ignored 
     */
    {
        File file0 = file0Resource.getFile();
        File file3 = file3Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-excel");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file3);
        assertTrue("different excel2003 file, failed to note difference", !result);
    }

    /**
     * Compare xls files that has different owning users(different [WRITEACCESS]) 
     */
    {
        File file4 = file4Resource.getFile();
        File file5 = file5Resource.getFile();

        ContentReader reader = new FileContentReader(file4);
        reader.setMimetype("application/vnd.ms-excel");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file5);
        assertTrue("compare trivially different xls files, should be equal", result);
    }
}

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

/**
 * Open and close of a PowerPoint 2003 file changes last edit username property hence changes file size.
 *
 * Test File 0 is created on initial PowerPoint instance
 * Test File 1 file is edited on initial PowerPoint instance so that the file size has been increased by less than 3073 bytes.
 * Test File 2 has been opened and closed on target PowerPoint instance hence lastEditUserName has been changed.
 * Test File 3 has been opened edited and closed on target PowerPoint instance hence lastEditUserName has been changed
 *     but the difference of sizes is still less than 3073 bytes.
 * Test File 4 has been edited on initial PowerPoint instance so that the file size has been reduced.
 * Test File 5 has been edited on initial PowerPoint instance so that the file size has been increased by more than 3072 bytes.
 *
 * @throws Exception/*from   ww  w .  jav a  2 s . c o m*/
 */
public void testDiffPowerPoint2003Files() throws Exception {
    CIFSContentComparator contentComparator = new CIFSContentComparator();
    contentComparator.init();

    ClassPathResource file0Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-0-initial.ppt");
    assertNotNull("unable to find test resource filesys/ContentComparatorTestPowerPoint2003-0-initial.ppt",
            file0Resource);

    ClassPathResource file1Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-1-edited-lt-3073bytes.ppt");
    assertNotNull(
            "unable to find test resource filesys/ContentComparatorTestPowerPoint2003-1-edited-lt-3073bytes.ppt",
            file1Resource);

    ClassPathResource file2Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-2-opened-closed.ppt");
    assertNotNull(
            "unable to find test resource filesys/ContentComparatorTestPowerPoint2003-2-opened-closed.ppt",
            file2Resource);

    ClassPathResource file3Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-3-opened-edited-closed.ppt");
    assertNotNull(
            "unable to find test resource filesys/ContentComparatorTestPowerPoint2003-3-opened-edited-closed.ppt",
            file3Resource);

    ClassPathResource file4Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-4-edited-lt-0bytes.ppt");
    assertNotNull(
            "unable to find test resource filesys/ContentComparatorTestPowerPoint2003-4-edited-lt-0bytes.ppt",
            file4Resource);

    ClassPathResource file5Resource = new ClassPathResource(
            "filesys/ContentComparatorTestPowerPoint2003-5-edited-gt-3072bytes.ppt");
    assertNotNull(
            "unable to find test resource filesys/ContentComparatorTestPowerPoint2003-5-edited-gt-3072bytes.ppt",
            file5Resource);

    /**
     * Compare different powerpoint files, should not be ignored
     */
    {
        File file0 = file0Resource.getFile();
        File file1 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-powerpoint");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file1);
        assertTrue("compare different powerpoint files, should not be equal", !result);
    }
    //        
    //      Test commented out, fails after implementation corrected - so there is a another bug in the content 
    //        comparison raised MNT-14860 to investigate.
    //        
    //        /**
    //         * Compare trivially different powerpoint files, should ignore trivial differences and be equal
    //         */
    //        {
    //            File file0 = file0Resource.getFile();
    //            File file2 = file2Resource.getFile();
    //
    //            ContentReader reader = new FileContentReader(file0);
    //            reader.setMimetype("application/vnd.ms-powerpoint");
    //            reader.setEncoding("UTF-8");
    //            boolean result = contentComparator.isContentEqual(reader, file2);
    //            assertTrue("compare trivially different powerpoint files, should be equal", result);
    //        }

    /**
     * Compare different powerpoint files, should not be ignored
     */
    {
        File file0 = file0Resource.getFile();
        File file3 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-powerpoint");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file3);
        assertTrue("compare different powerpoint files, should not be equal", !result);
    }

    /**
     * Compare different powerpoint files, should not be ignored
     */
    {
        File file0 = file0Resource.getFile();
        File file4 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-powerpoint");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file4);
        assertTrue("compare different powerpoint files, should not be equal", !result);
    }

    /**
     * Compare different powerpoint files, should not be ignored
     */
    {
        File file0 = file0Resource.getFile();
        File file5 = file1Resource.getFile();

        ContentReader reader = new FileContentReader(file0);
        reader.setMimetype("application/vnd.ms-powerpoint");
        reader.setEncoding("UTF-8");
        boolean result = contentComparator.isContentEqual(reader, file5);
        assertTrue("compare different powerpoint files, should not be equal", !result);
    }
}

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

/**
 * Guess mimetype with sufficient data - originally related to ACE-4523
 * Simulate creating a plain text document via Alfresco Share
 * then updating it via CIFS/FTP/*from w ww . j a v a2 s .  co m*/
 * 
 * 1. create a document called "foo" with just a little data with an explicit (incorrect) mimetype set.
 * 2. update the document with different text
 * 3. check the mimetype of the test doc has changed (since it can be guessed)
 */
public void testMimetypeWithSufficientData() throws Exception {
    logger.debug("testMimetypeWithInsufficiantData");

    // a file without a clue about mimetype
    final String FILE_NAME = "foo";

    class TestContext {
        NetworkFile firstFileHandle;
        String mimetype;
    }
    ;
    final TestContext testContext = new TestContext();

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

    // this is a made up mimetype - so there is no way that it could be guessed.
    final String TEST_MIMETYPE = "text\bar";

    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;
        }
    };
    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 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);
            driver.closeFile(testSession, testConnection, testContext.firstFileHandle);

            ClassPathResource fileResource = new ClassPathResource("filesys/ContentDiskDriverTestTxt1.txt");
            // Add the test content via the content writer to simulate being created via Share.
            NodeRef file1NodeRef = getNodeForPath(testConnection, TEST_DIR + "\\" + FILE_NAME);
            ContentWriter contentWriter2 = contentService.getWriter(file1NodeRef, ContentModel.PROP_CONTENT,
                    true);
            // this is a made up mimetype - so there is no way that it could be guessed.
            contentWriter2.setMimetype(TEST_MIMETYPE);
            contentWriter2.putContent(fileResource.getFile());

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

    /**
     * b) Update the file via CIFS
     */
    logger.debug("b) update file via CIFS");
    RetryingTransactionCallback<Void> updateFileCB = new RetryingTransactionCallback<Void>() {
        @Override
        public Void execute() throws Exception {
            FileOpenParams createFileParams = new FileOpenParams(TEST_DIR + "\\" + FILE_NAME, 0,
                    AccessMode.ReadWrite, FileAttribute.NTNormal, 0);
            NetworkFile file = driver.openFile(testSession, testConnection, createFileParams);
            assertNotNull(file);
            String testContent = "Bar";
            byte[] testContentBytes = testContent.getBytes();
            file.writeFile(testContentBytes, testContentBytes.length, 0, 0);
            driver.closeFile(testSession, testConnection, file);
            return null;
        }
    };
    tran.doInTransaction(updateFileCB, false, true);

    logger.debug("c) 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);

            /**
             * Validate mimetype has changed - we can guess that it is text !
             */
            assertEquals("mimeType is wrong", MimetypeMap.MIMETYPE_TEXT_PLAIN, data.getMimetype());

            return null;
        }
    };
    tran.doInTransaction(validateCB, true, true);
    logger.debug("end testMimetypeWithSufficientData");
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

private void importInternal(String acpName, NodeRef space) throws IOException {
    // Importing IMAP test acp
    ClassPathResource acpResource = new ClassPathResource(acpName);
    ACPImportPackageHandler acpHandler = new ACPImportPackageHandler(acpResource.getFile(), null);
    Location importLocation = new Location(space);
    importerService.importView(acpHandler, importLocation, null, null);
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testEightBitMessage() throws Exception {

    Store lstore = session.getStore(PROTOCOL);
    lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD);

    String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME;

    IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName);
    lfolder.open(Folder.READ_WRITE);/*from w  w  w.  j a  va 2 s .  c  o m*/

    InputStream messageFileInputStream1 = null;
    InputStream messageFileInputStream2 = null;
    try {
        ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml");
        messageFileInputStream1 = new FileInputStream(fileResource.getFile());
        Message message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                messageFileInputStream1);
        String subject = message.getSubject();

        // get original bytes for further comparation
        messageFileInputStream2 = new FileInputStream(fileResource.getFile());
        byte[] original = ASCIIUtility.getBytes(messageFileInputStream2);

        Message[] messages = { message };

        lfolder.appendMessages(messages);

        // The search is not implemented. 
        // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit");
        // messages = folder.search(term);

        // So wee need to get our test message's UID from the repo

        String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":"
                + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]";

        QueryParameterDefinition[] params = new QueryParameterDefinition[1];
        params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE,
                serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject);

        List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params,
                namespaceService, true);

        // does the message exist
        assertEquals(1, nodeRefs.size());

        NodeRef messageNodeRef = nodeRefs.get(0);

        // get message UID
        Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID);

        // fetch the massage
        RFC822DATA data = getRFC822Message(lfolder, dbid);

        assertNotNull("Can't fetch a message from the repositiry", data);

        byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream());

        assertTrue("Original message doesn't coincide to the message processed by the repository",
                Arrays.equals(original, processed));
    } finally {
        if (messageFileInputStream1 != null)
            messageFileInputStream1.close();
        if (messageFileInputStream2 != null)
            messageFileInputStream2.close();
    }

    // close connection
    lfolder.close(true);
    lstore.close();

}

From source file:org.alfresco.repo.imap.LoadTester.java

private void importTestData(String acpName, NodeRef space) throws IOException {
    ClassPathResource acpResource = new ClassPathResource(acpName);
    ACPImportPackageHandler acpHandler = new ACPImportPackageHandler(acpResource.getFile(), null);
    Location importLocation = new Location(space);
    importerService.importView(acpHandler, importLocation, null, null);
}

From source file:org.deeplearning4j.models.glove.CoOccurrencesTest.java

@Before
public void before() throws Exception {
    FileUtils.deleteDirectory(new File("word2vec-index"));
    ClassPathResource resource = new ClassPathResource("other/oneline.txt");
    File file = resource.getFile();
    iter = new LineSentenceIterator(file);
    iter.setPreProcessor(new SentencePreProcessor() {
        @Override/*from   ww w .  ja va  2 s.c  o  m*/
        public String preProcess(String sentence) {
            return StringCleaning.stripPunct(sentence);
        }
    });
    vocabCache = new InMemoryLookupCache();

    textVectorizer = new TfidfVectorizer.Builder().tokenize(tokenizerFactory).cache(vocabCache).iterate(iter)
            .minWords(1).stopWords(new ArrayList<String>()).build();

    textVectorizer.fit();

    coOccurrences = new CoOccurrences.Builder().cache(vocabCache).iterate(iter).symmetric(false)
            .tokenizer(tokenizerFactory).windowSize(15).build();

}

From source file:org.deeplearning4j.models.glove.CoOccurrencesTest.java

@Test
public void testTokens() throws Exception {
    ClassPathResource resource = new ClassPathResource("big/raw_sentences.txt");
    File file = resource.getFile();
    iter = new LineSentenceIterator(file);
    iter.setPreProcessor(new SentencePreProcessor() {
        @Override/* w  ww  .j  a  v a2 s .c  o m*/
        public String preProcess(String sentence) {
            return sentence.toLowerCase();
        }
    });
    List<String> lines = IOUtils.readLines(new ClassPathResource(("big/tokens.txt")).getInputStream());
    int count = 0;
    while (iter.hasNext()) {
        List<String> tokens = tokenizerFactory.create(iter.nextSentence()).getTokens();
        String[] split = lines.get(count).split(" ");
        int count2 = Integer.parseInt(split[0]);
        assertEquals(count, count2);
        assertEquals("Sentence " + count, Integer.parseInt(split[1]), tokens.size());
        count++;
    }
}

From source file:org.deeplearning4j.models.glove.GloveTest.java

@Before
public void before() throws Exception {

    ClassPathResource resource = new ClassPathResource("other/oneline.txt");
    File file = resource.getFile().getParentFile();
    iter = UimaSentenceIterator.createWithPath(file.getAbsolutePath());

}