Search in sources :

Example 1 with TechInfoSet

use of de.catma.document.source.TechInfoSet in project catma by forTEXT.

the class TeiDocument method getTechInfoset.

public TechInfoSet getTechInfoset() {
    TechnicalDescription td = teiHeader.getTechnicalDescription();
    TechInfoSet tis = new TechInfoSet(td.getFileType(), td.getCharset(), td.getFileOSType(), td.getChecksum());
    return tis;
}
Also used : TechInfoSet(de.catma.document.source.TechInfoSet)

Example 2 with TechInfoSet

use of de.catma.document.source.TechInfoSet in project catma by forTEXT.

the class ImportIntrinsicMarkupStep method enter.

@Override
public void enter(boolean back) {
    if (back) {
        return;
    }
    contentPanel.setEnabled(false);
    progressBar.setVisible(true);
    progressBar.setIndeterminate(true);
    @SuppressWarnings("unchecked") final ArrayList<UploadFile> files = new ArrayList<UploadFile>(((Collection<UploadFile>) wizardContext.get(DocumentWizard.WizardContextKey.UPLOAD_FILE_LIST)).stream().filter(uploadFile -> uploadFile.getMimetype().equals(FileType.XML2.getMimeType())).collect(Collectors.toList()));
    final TagManager tagmanager = new TagManager(new TagLibrary());
    BackgroundServiceProvider backgroundServiceProvider = (BackgroundServiceProvider) UI.getCurrent();
    backgroundServiceProvider.submit("inspecting-intrinsic-markup", new DefaultProgressCallable<List<UploadFile>>() {

        @Override
        public List<UploadFile> call() throws Exception {
            IDGenerator idGenerator = new IDGenerator();
            for (UploadFile uploadFile : files) {
                XML2ContentHandler contentHandler = new XML2ContentHandler();
                SourceDocument doc = new SourceDocument(uploadFile.getUuid(), contentHandler);
                SourceDocumentInfo documentInfo = new SourceDocumentInfo();
                TechInfoSet techInfoSet = new TechInfoSet();
                techInfoSet.setURI(uploadFile.getTempFilename());
                documentInfo.setTechInfoSet(techInfoSet);
                contentHandler.setSourceDocumentInfo(documentInfo);
                XmlMarkupCollectionSerializationHandler handler = new XmlMarkupCollectionSerializationHandler(tagmanager, contentHandler, project.getUser().getIdentifier());
                try (FileInputStream fis = new FileInputStream(new File(uploadFile.getTempFilename()))) {
                    AnnotationCollection collection = handler.deserialize(doc, idGenerator.generateCollectionId(), fis);
                    uploadFile.setIntrinsicMarkupCollection(collection);
                }
            }
            return files;
        }
    }, new ExecutionListener<List<UploadFile>>() {

        @Override
        public void done(List<UploadFile> result) {
            contentPanel.setEnabled(true);
            progressBar.setVisible(false);
            progressBar.setIndeterminate(false);
            fileList.clear();
            fileList.addAll(result);
            fileDataProvider.refreshAll();
            tagsetImportList.clear();
            String defaultIntrinsicXMLElmentsName = "Default Intrinsic XML Elements";
            for (TagsetDefinition tagset : tagmanager.getTagLibrary()) {
                if (!tagset.isEmpty()) {
                    TagsetDefinition targetTagset = project.getTagManager().getTagLibrary().getTagsetDefinition(tagset.getUuid());
                    boolean inProject = false;
                    if (targetTagset == null) {
                        targetTagset = tagset;
                    } else {
                        inProject = true;
                    }
                    String namespace = tagset.getName() == null ? "none" : tagset.getName();
                    if (tagset.getName() == null) {
                        tagset.setName(defaultIntrinsicXMLElmentsName);
                    }
                    TagsetImport tagsetImport = new TagsetImport(namespace, tagset, targetTagset, inProject ? TagsetImportState.WILL_BE_MERGED : TagsetImportState.WILL_BE_CREATED);
                    tagsetImportList.add(tagsetImport);
                }
            }
            tagsetDataProvider.refreshAll();
            wizardContext.put(DocumentWizard.WizardContextKey.TAGSET_IMPORT_LIST, tagsetImportList);
            if (stepChangeListener != null) {
                stepChangeListener.stepChanged(ImportIntrinsicMarkupStep.this);
            }
        }

        @Override
        public void error(Throwable t) {
            Logger.getLogger(ImportIntrinsicMarkupStep.class.getName()).log(Level.SEVERE, "Error inspecting files", t);
            String errorMsg = t.getMessage();
            if ((errorMsg == null) || (errorMsg.trim().isEmpty())) {
                errorMsg = "";
            }
            Notification.show("Error", String.format("Error inspecting the contents! " + "\n The underlying error message was:\n%1$s", errorMsg), Type.ERROR_MESSAGE);
        }
    });
}
Also used : SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) ArrayList(java.util.ArrayList) BackgroundServiceProvider(de.catma.backgroundservice.BackgroundServiceProvider) ArrayList(java.util.ArrayList) List(java.util.List) TechInfoSet(de.catma.document.source.TechInfoSet) TagLibrary(de.catma.tag.TagLibrary) AnnotationCollection(de.catma.document.annotation.AnnotationCollection) SourceDocument(de.catma.document.source.SourceDocument) XML2ContentHandler(de.catma.document.source.contenthandler.XML2ContentHandler) FileInputStream(java.io.FileInputStream) TagsetDefinition(de.catma.tag.TagsetDefinition) TagManager(de.catma.tag.TagManager) XmlMarkupCollectionSerializationHandler(de.catma.serialization.intrinsic.xml.XmlMarkupCollectionSerializationHandler) IDGenerator(de.catma.util.IDGenerator) File(java.io.File)

Example 3 with TechInfoSet

use of de.catma.document.source.TechInfoSet in project catma by forTEXT.

the class GitProjectHandlerTest method createSourceDocument.

// @Test
// public void delete() throws Exception {
// try (ILocalGitRepositoryManager jGitRepoManager = new JGitRepoManager(this.catmaProperties.getProperty(CATMAPropertyKey.GitBasedRepositoryBasePath.name()), this.catmaUser)) {
// this.directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
// 
// GitProjectManager gitProjectHandler = new GitProjectManager(
// CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(),
// UserIdentification.userToMap(this.catmaUser.getIdentifier()));
// 
// 
// String projectId = gitProjectHandler.create(
// "Test CATMA Project", "This is a test CATMA project"
// );
// // we don't add the projectId to this.projectsToDeleteOnTearDown as this is the delete test
// 
// assertNotNull(projectId);
// assert projectId.startsWith("CATMA_");
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls
// // return
// assertFalse(jGitRepoManager.isAttached());
// 
// String expectedRootRepositoryName = GitProjectManager.getProjectRootRepositoryName(projectId);
// 
// File expectedRootRepositoryPath = new File(
// jGitRepoManager.getRepositoryBasePath(), expectedRootRepositoryName
// );
// 
// assert expectedRootRepositoryPath.exists();
// assert expectedRootRepositoryPath.isDirectory();
// 
// gitProjectHandler.delete(projectId);
// 
// assertFalse(expectedRootRepositoryPath.exists());
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls
// // return
// assertFalse(jGitRepoManager.isAttached());
// }
// }
// 
// @Test
// public void createTagset() throws Exception {
// try (JGitRepoManager jGitRepoManager = new JGitRepoManager(this.catmaProperties.getProperty(CATMAPropertyKey.GitBasedRepositoryBasePath.name()), this.catmaUser)) {
// this.directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
// 
// GitProjectManager gitProjectManager = new GitProjectManager(
// CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(),
// UserIdentification.userToMap(this.catmaUser.getIdentifier()));
// 
// 
// String projectId = gitProjectManager.create(
// "Test CATMA Project",
// "This is a test CATMA project"
// );
// this.projectsToDeleteOnTearDown.add(projectId);
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls return
// assertFalse(jGitRepoManager.isAttached());
// 
// GitProjectHandler gitProjectHandler = new GitProjectHandler(null, projectId, jGitRepoManager, gitLabServerManager);
// 
// String tagsetId = gitProjectHandler.createTagset(
// 
// null,
// "Test Tagset",
// null
// );
// 
// assertNotNull(tagsetId);
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls return
// assertFalse(jGitRepoManager.isAttached());
// 
// jGitRepoManager.open(projectId, GitProjectManager.getProjectRootRepositoryName(projectId));
// Status status = jGitRepoManager.getGitApi().status().call();
// Set<String> added = status.getAdded();
// 
// assert status.hasUncommittedChanges();
// assert added.contains(".gitmodules");
// assert added.contains(String.format("%s/%s", GitProjectHandler.TAGSET_SUBMODULES_DIRECTORY_NAME, tagsetId));
// }
// }
// 
// @Test
// public void createMarkupCollection() throws Exception {
// try (JGitRepoManager jGitRepoManager = new JGitRepoManager(this.catmaProperties.getProperty(CATMAPropertyKey.GitBasedRepositoryBasePath.name()), this.catmaUser)) {
// this.directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
// 
// GitProjectManager gitProjectManager = new GitProjectManager(
// CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(),
// UserIdentification.userToMap(this.catmaUser.getIdentifier()));
// 
// 
// String projectId = gitProjectManager.create(
// "Test CATMA Project",
// "This is a test CATMA project"
// );
// this.projectsToDeleteOnTearDown.add(projectId);
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls return
// assertFalse(jGitRepoManager.isAttached());
// 
// GitProjectHandler gitProjectHandler = new GitProjectHandler(null, projectId, jGitRepoManager, gitLabServerManager);
// 
// String markupCollectionId = gitProjectHandler.createMarkupCollection(
// null,
// "Test Markup Collection",
// null,
// "fakeSourceDocumentId",
// "fakeSourceDocumentVersion"
// );
// 
// assertNotNull(markupCollectionId);
// 
// // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls return
// assertFalse(jGitRepoManager.isAttached());
// 
// jGitRepoManager.open(projectId, GitProjectManager.getProjectRootRepositoryName(projectId));
// Status status = jGitRepoManager.getGitApi().status().call();
// Set<String> added = status.getAdded();
// 
// assert status.hasUncommittedChanges();
// assert added.contains(".gitmodules");
// assert added.contains(
// String.format(
// "%s/%s", GitProjectHandler.MARKUP_COLLECTION_SUBMODULES_DIRECTORY_NAME, markupCollectionId
// )
// );
// }
// }
@Test
public void createSourceDocument() throws Exception {
    File originalSourceDocument = new File("testdocs/rose_for_emily.pdf");
    File convertedSourceDocument = new File("testdocs/rose_for_emily.txt");
    FileInputStream originalSourceDocumentStream = new FileInputStream(originalSourceDocument);
    FileInputStream convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    IndexInfoSet indexInfoSet = new IndexInfoSet();
    indexInfoSet.setLocale(Locale.ENGLISH);
    ContentInfoSet contentInfoSet = new ContentInfoSet("William Faulkner", "", "", "A Rose for Emily");
    TechInfoSet techInfoSet = new TechInfoSet(FileType.TEXT, StandardCharsets.UTF_8, FileOSType.DOS, 705211438L);
    SourceDocumentInfo sourceDocumentInfo = new SourceDocumentInfo(indexInfoSet, contentInfoSet, techInfoSet);
    Map<String, List<TermInfo>> terms = new TermExtractor(IOUtils.toString(convertedSourceDocumentStream, techInfoSet.getCharset()), new ArrayList<>(), new ArrayList<>(), indexInfoSet.getLocale()).getTerms();
    // need to re-instantiate the stream, otherwise an empty file will be written later on (FileInputStream does not support `reset`)
    convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    String sourceDocumentUuid = new IDGenerator().generateDocumentId();
    // GraphWorktreeProject.TOKENIZED_FILE_EXTENSION
    String tokenizedSourceDocumentFileName = sourceDocumentUuid + "." + "json";
    try (JGitRepoManager jGitRepoManager = new JGitRepoManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted.getUser())) {
        directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
        BackgroundService mockBackgroundService = mock(BackgroundService.class);
        EventBus mockEventBus = mock(EventBus.class);
        GitProjectManager gitProjectManager = new GitProjectManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted, // noop deletion handler
        (projectId) -> {
        }, mockBackgroundService, mockEventBus);
        String projectId = gitProjectManager.create("Test CATMA Project", "This is a test CATMA project");
        // we don't add the projectId to projectsToDeleteOnTearDown as deletion of the user will take care of that for us
        // the JGitRepoManager instance should always be in a detached state after GitProjectManager calls return
        assertFalse(jGitRepoManager.isAttached());
        GitProjectHandler gitProjectHandler = new GitProjectHandler(gitlabManagerRestricted.getUser(), projectId, jGitRepoManager, gitlabManagerRestricted);
        // would usually happen when the project is opened via GraphWorktreeProject
        gitProjectHandler.loadRolesPerResource();
        String revisionHash = gitProjectHandler.createSourceDocument(sourceDocumentUuid, originalSourceDocumentStream, originalSourceDocument.getName(), convertedSourceDocumentStream, convertedSourceDocument.getName(), terms, tokenizedSourceDocumentFileName, sourceDocumentInfo);
        assertNotNull(revisionHash);
        // the JGitRepoManager instance should always be in a detached state after GitProjectHandler calls return
        assertFalse(jGitRepoManager.isAttached());
        jGitRepoManager.open(projectId, GitProjectManager.getProjectRootRepositoryName(projectId));
        Status status = jGitRepoManager.getGitApi().status().call();
        assert status.isClean();
        assertFalse(status.hasUncommittedChanges());
        Iterable<RevCommit> commits = jGitRepoManager.getGitApi().log().all().call();
        @SuppressWarnings("unchecked") List<RevCommit> commitsList = IteratorUtils.toList(commits.iterator());
        assertEquals(1, commitsList.size());
        // TODO: it would be good to check that the revision hash of the commit matches, however GitProjectHandler currently returns the revision hash
        // from the source document repo itself rather than from the root repo
        assertEquals(gitlabManagerRestricted.getUser().getIdentifier(), commitsList.get(0).getCommitterIdent().getName());
        assertEquals(gitlabManagerRestricted.getUser().getEmail(), commitsList.get(0).getCommitterIdent().getEmailAddress());
        assert commitsList.get(0).getFullMessage().contains(String.format("Added Document %s with ID", contentInfoSet.getTitle()));
    // TODO: add assertions for actual paths changed (see commented above - would need to be modified for already committed changes)
    }
}
Also used : Status(org.eclipse.jgit.api.Status) BackgroundService(de.catma.backgroundservice.BackgroundService) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) JGitRepoManager(de.catma.repository.git.managers.JGitRepoManager) TermExtractor(de.catma.indexer.TermExtractor) EventBus(com.google.common.eventbus.EventBus) FileInputStream(java.io.FileInputStream) ContentInfoSet(de.catma.document.source.ContentInfoSet) IndexInfoSet(de.catma.document.source.IndexInfoSet) TechInfoSet(de.catma.document.source.TechInfoSet) File(java.io.File) IDGenerator(de.catma.util.IDGenerator) RevCommit(org.eclipse.jgit.revwalk.RevCommit) GitLabServerManagerTest(de.catma.repository.git.managers.GitLabServerManagerTest) Test(org.junit.jupiter.api.Test)

Example 4 with TechInfoSet

use of de.catma.document.source.TechInfoSet in project catma by forTEXT.

the class GitSourceDocumentHandlerTest method update.

// // how to test for exceptions: https://stackoverflow.com/a/31826781
// @Rule
// public ExpectedException thrown = ExpectedException.none();
// 
// @Test
// public void delete() throws Exception {
// try (ILocalGitRepositoryManager jGitRepoManager = new JGitRepoManager(this.catmaProperties.getProperty(RepositoryPropertyKey.GitBasedRepositoryBasePath.name()), this.catmaUser)) {
// GitSourceDocumentHandler gitSourceDocumentHandler = new GitSourceDocumentHandler(
// jGitRepoManager, this.gitLabServerManager
// );
// 
// thrown.expect(IOException.class);
// thrown.expectMessage("Not implemented");
// gitSourceDocumentHandler.delete("fakeProjectId", "fakeSourceDocumentId");
// }
// }
// 
// @Test
// public void open() throws Exception {
// try (JGitRepoManager jGitRepoManager = new JGitRepoManager(this.catmaProperties.getProperty(RepositoryPropertyKey.GitBasedRepositoryBasePath.name()), this.catmaUser)) {
// this.directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
// 
// HashMap<String, Object> getJsonLdWebAnnotationResult = JsonLdWebAnnotationTest.getJsonLdWebAnnotation(
// jGitRepoManager, this.gitLabServerManager, this.catmaUser
// );
// 
// String projectId = (String)getJsonLdWebAnnotationResult.get("projectUuid");
// String sourceDocumentId = (String)getJsonLdWebAnnotationResult.get("sourceDocumentUuid");
// 
// this.projectsToDeleteOnTearDown.add(projectId);
// 
// GitSourceDocumentHandler gitSourceDocumentHandler = new GitSourceDocumentHandler(
// jGitRepoManager, this.gitLabServerManager
// );
// 
// SourceDocument loadedSourceDocument = gitSourceDocumentHandler.open(projectId, sourceDocumentId);
// 
// assertNotNull(loadedSourceDocument);
// assertEquals(
// "William Faulkner",
// loadedSourceDocument.getSourceContentHandler().getSourceDocumentInfo().getContentInfoSet()
// .getAuthor()
// );
// assertEquals(
// "A Rose for Emily",
// loadedSourceDocument.getSourceContentHandler().getSourceDocumentInfo().getContentInfoSet()
// .getTitle()
// );
// assertNotNull(loadedSourceDocument.getRevisionHash());
// }
// }
@Test
public void update() throws Exception {
    File originalSourceDocument = new File("testdocs/rose_for_emily.pdf");
    File convertedSourceDocument = new File("testdocs/rose_for_emily.txt");
    FileInputStream originalSourceDocumentStream = new FileInputStream(originalSourceDocument);
    FileInputStream convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    IndexInfoSet indexInfoSet = new IndexInfoSet();
    indexInfoSet.setLocale(Locale.ENGLISH);
    ContentInfoSet contentInfoSet = new ContentInfoSet("William Faulkner", "", "", "A Rose for Emily");
    TechInfoSet techInfoSet = new TechInfoSet(FileType.TEXT, StandardCharsets.UTF_8, FileOSType.DOS, 705211438L);
    SourceDocumentInfo sourceDocumentInfo = new SourceDocumentInfo(indexInfoSet, contentInfoSet, techInfoSet);
    Map<String, List<TermInfo>> terms = new TermExtractor(IOUtils.toString(convertedSourceDocumentStream, techInfoSet.getCharset()), new ArrayList<>(), new ArrayList<>(), indexInfoSet.getLocale()).getTerms();
    // need to re-instantiate the stream, otherwise an empty file will be written later on (FileInputStream does not support `reset`)
    convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    String sourceDocumentUuid = new IDGenerator().generateDocumentId();
    // GraphWorktreeProject.TOKENIZED_FILE_EXTENSION
    String tokenizedSourceDocumentFileName = sourceDocumentUuid + "." + "json";
    try (ILocalGitRepositoryManager jGitRepoManager = new JGitRepoManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted.getUser())) {
        directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
        BackgroundService mockBackgroundService = mock(BackgroundService.class);
        EventBus mockEventBus = mock(EventBus.class);
        GitProjectManager gitProjectManager = new GitProjectManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted, // noop deletion handler
        (projectId) -> {
        }, mockBackgroundService, mockEventBus);
        String projectId = gitProjectManager.create("Test CATMA Project", "This is a test CATMA project");
        // we don't add the projectId to projectsToDeleteOnTearDown as deletion of the user will take care of that for us
        // the JGitRepoManager instance should always be in a detached state after GitProjectManager calls return
        assertFalse(jGitRepoManager.isAttached());
        GitSourceDocumentHandler gitSourceDocumentHandler = new GitSourceDocumentHandler(jGitRepoManager, gitlabManagerRestricted, new UsernamePasswordCredentialsProvider("oauth2", gitlabManagerRestricted.getPassword()));
        String revisionHash = gitSourceDocumentHandler.create(projectId, sourceDocumentUuid, originalSourceDocumentStream, originalSourceDocument.getName(), convertedSourceDocumentStream, convertedSourceDocument.getName(), terms, tokenizedSourceDocumentFileName, sourceDocumentInfo);
        assertNotNull(revisionHash);
        // the JGitRepoManager instance should always be in a detached state after GitSourceDocumentHandler calls return
        assertFalse(jGitRepoManager.isAttached());
        // TODO: factor out a function that does all of the above
        jGitRepoManager.open(projectId, sourceDocumentUuid);
        jGitRepoManager.push(new UsernamePasswordCredentialsProvider("oauth2", gitlabManagerRestricted.getPassword()));
        String remoteUri = jGitRepoManager.getRemoteUrl(null);
        jGitRepoManager.detach();
        // open the project root repository
        jGitRepoManager.open(projectId, GitProjectManager.getProjectRootRepositoryName(projectId));
        // create the submodule
        File targetSubmodulePath = Paths.get(jGitRepoManager.getRepositoryWorkTree().getAbsolutePath(), SOURCE_DOCUMENT_SUBMODULES_DIRECTORY_NAME, sourceDocumentUuid).toFile();
        // submodule files and the changed .gitmodules file are automatically staged
        jGitRepoManager.addSubmodule(targetSubmodulePath, remoteUri, new UsernamePasswordCredentialsProvider("oauth2", gitlabManagerRestricted.getPassword()));
        jGitRepoManager.detach();
        SourceDocument sourceDocument = gitSourceDocumentHandler.open(projectId, sourceDocumentUuid);
        sourceDocument.getSourceContentHandler().getSourceDocumentInfo().setContentInfoSet(new ContentInfoSet("William Faulkner (updated)", "Test description (new)", "Test publisher (new)", "A Rose for Emily (updated)"));
        String sourceDocumentRevision = gitSourceDocumentHandler.update(projectId, sourceDocument);
        assertNotNull(sourceDocumentRevision);
        String expectedSerializedSourceDocumentInfo = "" + "{\n" + "  \"gitContentInfoSet\": {\n" + "    \"author\": \"William Faulkner (updated)\",\n" + "    \"description\": \"Test description (new)\",\n" + "    \"publisher\": \"Test publisher (new)\",\n" + "    \"title\": \"A Rose for Emily (updated)\"\n" + "  },\n" + "  \"gitIndexInfoSet\": {\n" + "    \"locale\": \"en\",\n" + "    \"unseparableCharacterSequences\": [],\n" + "    \"userDefinedSeparatingCharacters\": []\n" + "  },\n" + "  \"gitTechInfoSet\": {\n" + "    \"charset\": \"UTF-8\",\n" + "    \"checksum\": 705211438,\n" + "    \"fileName\": null,\n" + "    \"fileOSType\": \"DOS\",\n" + "    \"fileType\": \"TEXT\",\n" + "    \"mimeType\": \"text/plain\",\n" + "    \"uri\": null\n" + "  }\n" + "}";
        assertEquals(expectedSerializedSourceDocumentInfo, FileUtils.readFileToString(new File(targetSubmodulePath, "header.json"), StandardCharsets.UTF_8));
    }
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) BackgroundService(de.catma.backgroundservice.BackgroundService) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) ILocalGitRepositoryManager(de.catma.repository.git.interfaces.ILocalGitRepositoryManager) JGitRepoManager(de.catma.repository.git.managers.JGitRepoManager) SourceDocument(de.catma.document.source.SourceDocument) TermExtractor(de.catma.indexer.TermExtractor) EventBus(com.google.common.eventbus.EventBus) FileInputStream(java.io.FileInputStream) ContentInfoSet(de.catma.document.source.ContentInfoSet) IndexInfoSet(de.catma.document.source.IndexInfoSet) TechInfoSet(de.catma.document.source.TechInfoSet) File(java.io.File) IDGenerator(de.catma.util.IDGenerator) GitLabServerManagerTest(de.catma.repository.git.managers.GitLabServerManagerTest) Test(org.junit.jupiter.api.Test)

Example 5 with TechInfoSet

use of de.catma.document.source.TechInfoSet in project catma by forTEXT.

the class GitSourceDocumentHandlerTest method create.

@Test
public void create() throws Exception {
    File originalSourceDocument = new File("testdocs/rose_for_emily.pdf");
    File convertedSourceDocument = new File("testdocs/rose_for_emily.txt");
    FileInputStream originalSourceDocumentStream = new FileInputStream(originalSourceDocument);
    FileInputStream convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    IndexInfoSet indexInfoSet = new IndexInfoSet();
    indexInfoSet.setLocale(Locale.ENGLISH);
    ContentInfoSet contentInfoSet = new ContentInfoSet("William Faulkner", "", "", "A Rose for Emily");
    TechInfoSet techInfoSet = new TechInfoSet(FileType.TEXT, StandardCharsets.UTF_8, FileOSType.DOS, 705211438L);
    SourceDocumentInfo sourceDocumentInfo = new SourceDocumentInfo(indexInfoSet, contentInfoSet, techInfoSet);
    Map<String, List<TermInfo>> terms = new TermExtractor(IOUtils.toString(convertedSourceDocumentStream, techInfoSet.getCharset()), new ArrayList<>(), new ArrayList<>(), indexInfoSet.getLocale()).getTerms();
    // need to re-instantiate the stream, otherwise an empty file will be written later on (FileInputStream does not support `reset`)
    convertedSourceDocumentStream = new FileInputStream(convertedSourceDocument);
    String sourceDocumentUuid = new IDGenerator().generateDocumentId();
    // GraphWorktreeProject.TOKENIZED_FILE_EXTENSION
    String tokenizedSourceDocumentFileName = sourceDocumentUuid + "." + "json";
    try (ILocalGitRepositoryManager jGitRepoManager = new JGitRepoManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted.getUser())) {
        directoriesToDeleteOnTearDown.add(jGitRepoManager.getRepositoryBasePath());
        BackgroundService mockBackgroundService = mock(BackgroundService.class);
        EventBus mockEventBus = mock(EventBus.class);
        GitProjectManager gitProjectManager = new GitProjectManager(CATMAPropertyKey.GitBasedRepositoryBasePath.getValue(), gitlabManagerRestricted, // noop deletion handler
        (projectId) -> {
        }, mockBackgroundService, mockEventBus);
        String projectId = gitProjectManager.create("Test CATMA Project", "This is a test CATMA project");
        // we don't add the projectId to projectsToDeleteOnTearDown as deletion of the user will take care of that for us
        // the JGitRepoManager instance should always be in a detached state after GitProjectManager calls return
        assertFalse(jGitRepoManager.isAttached());
        GitSourceDocumentHandler gitSourceDocumentHandler = new GitSourceDocumentHandler(jGitRepoManager, gitlabManagerRestricted, new UsernamePasswordCredentialsProvider("oauth2", gitlabManagerRestricted.getPassword()));
        String revisionHash = gitSourceDocumentHandler.create(projectId, sourceDocumentUuid, originalSourceDocumentStream, originalSourceDocument.getName(), convertedSourceDocumentStream, convertedSourceDocument.getName(), terms, tokenizedSourceDocumentFileName, sourceDocumentInfo);
        assertNotNull(revisionHash);
        // the JGitRepoManager instance should always be in a detached state after GitSourceDocumentHandler calls return
        assertFalse(jGitRepoManager.isAttached());
        File expectedRepoPath = Paths.get(jGitRepoManager.getRepositoryBasePath().getPath(), projectId, sourceDocumentUuid).toFile();
        assert expectedRepoPath.exists();
        assert expectedRepoPath.isDirectory();
        assert Arrays.asList(expectedRepoPath.list()).contains("rose_for_emily.pdf");
        assert Arrays.asList(expectedRepoPath.list()).contains("rose_for_emily.txt");
        assert FileUtils.contentEquals(originalSourceDocument, new File(expectedRepoPath, "rose_for_emily.pdf"));
        assert FileUtils.contentEquals(convertedSourceDocument, new File(expectedRepoPath, "rose_for_emily.txt"));
        assert Arrays.asList(expectedRepoPath.list()).contains("header.json");
        String expectedSerializedSourceDocumentInfo = "" + "{\n" + "  \"gitContentInfoSet\": {\n" + "    \"author\": \"William Faulkner\",\n" + "    \"description\": \"\",\n" + "    \"publisher\": \"\",\n" + "    \"title\": \"A Rose for Emily\"\n" + "  },\n" + "  \"gitIndexInfoSet\": {\n" + "    \"locale\": \"en\",\n" + "    \"unseparableCharacterSequences\": [],\n" + "    \"userDefinedSeparatingCharacters\": []\n" + "  },\n" + "  \"gitTechInfoSet\": {\n" + "    \"charset\": \"UTF-8\",\n" + "    \"checksum\": 705211438,\n" + "    \"fileName\": null,\n" + "    \"fileOSType\": \"DOS\",\n" + "    \"fileType\": \"TEXT\",\n" + "    \"mimeType\": \"text/plain\",\n" + "    \"uri\": null\n" + "  }\n" + "}";
        assertEquals(expectedSerializedSourceDocumentInfo, FileUtils.readFileToString(new File(expectedRepoPath, "header.json"), StandardCharsets.UTF_8));
    }
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) BackgroundService(de.catma.backgroundservice.BackgroundService) SourceDocumentInfo(de.catma.document.source.SourceDocumentInfo) ILocalGitRepositoryManager(de.catma.repository.git.interfaces.ILocalGitRepositoryManager) JGitRepoManager(de.catma.repository.git.managers.JGitRepoManager) TermExtractor(de.catma.indexer.TermExtractor) EventBus(com.google.common.eventbus.EventBus) FileInputStream(java.io.FileInputStream) ContentInfoSet(de.catma.document.source.ContentInfoSet) IndexInfoSet(de.catma.document.source.IndexInfoSet) TechInfoSet(de.catma.document.source.TechInfoSet) File(java.io.File) IDGenerator(de.catma.util.IDGenerator) GitLabServerManagerTest(de.catma.repository.git.managers.GitLabServerManagerTest) Test(org.junit.jupiter.api.Test)

Aggregations

TechInfoSet (de.catma.document.source.TechInfoSet)11 SourceDocumentInfo (de.catma.document.source.SourceDocumentInfo)9 IndexInfoSet (de.catma.document.source.IndexInfoSet)8 File (java.io.File)8 FileInputStream (java.io.FileInputStream)8 ContentInfoSet (de.catma.document.source.ContentInfoSet)6 IDGenerator (de.catma.util.IDGenerator)6 XML2ContentHandler (de.catma.document.source.contenthandler.XML2ContentHandler)4 JGitRepoManager (de.catma.repository.git.managers.JGitRepoManager)4 ArrayList (java.util.ArrayList)4 EventBus (com.google.common.eventbus.EventBus)3 BackgroundService (de.catma.backgroundservice.BackgroundService)3 SourceDocument (de.catma.document.source.SourceDocument)3 TermExtractor (de.catma.indexer.TermExtractor)3 GitLabServerManagerTest (de.catma.repository.git.managers.GitLabServerManagerTest)3 List (java.util.List)3 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)3 Test (org.junit.jupiter.api.Test)3 Notification (com.vaadin.ui.Notification)2 Type (com.vaadin.ui.Notification.Type)2