Search in sources :

Example 6 with Collection

use of org.dspace.content.Collection in project DSpace by DSpace.

the class WorkflowItemRestRepositoryIT method whenWorkspaceitemBecomeWorkflowitemWithAccessConditionsTheBitstremMustBeDownloableTest.

@Test
public void whenWorkspaceitemBecomeWorkflowitemWithAccessConditionsTheBitstremMustBeDownloableTest() throws Exception {
    context.turnOffAuthorisationSystem();
    EPerson submitter = EPersonBuilder.createEPerson(context).withEmail("submitter@example.com").withPassword(password).build();
    EPerson reviewer1 = EPersonBuilder.createEPerson(context).withEmail("reviewer1@example.com").withPassword(password).build();
    parentCommunity = CommunityBuilder.createCommunity(context).withName("Parent Community").build();
    Collection collection1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").withWorkflowGroup(1, reviewer1).build();
    Bitstream bitstream = null;
    WorkspaceItem witem = null;
    String bitstreamContent = "0123456789";
    AtomicReference<Integer> idRef = new AtomicReference<Integer>();
    try (InputStream is = IOUtils.toInputStream(bitstreamContent, Charset.defaultCharset())) {
        context.setCurrentUser(submitter);
        witem = WorkspaceItemBuilder.createWorkspaceItem(context, collection1).withTitle("Test WorkspaceItem").withIssueDate("2019-10-01").build();
        bitstream = BitstreamBuilder.createBitstream(context, witem.getItem(), is).withName("Test bitstream").withDescription("This is a bitstream to test range requests").withMimeType("text/plain").build();
        context.restoreAuthSystemState();
        String tokenEPerson = getAuthToken(eperson.getEmail(), password);
        String tokenSubmitter = getAuthToken(submitter.getEmail(), password);
        String tokenReviewer1 = getAuthToken(reviewer1.getEmail(), password);
        // submitter can download the bitstream
        getClient(tokenSubmitter).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isOk()).andExpect(header().string("Accept-Ranges", "bytes")).andExpect(header().string("ETag", "\"" + bitstream.getChecksum() + "\"")).andExpect(content().contentType("text/plain")).andExpect(content().bytes(bitstreamContent.getBytes()));
        // reviewer can't still download the bitstream
        getClient(tokenReviewer1).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isForbidden());
        // others can't download the bitstream
        getClient(tokenEPerson).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isForbidden());
        // create a list of values to use in add operation
        List<Operation> addAccessCondition = new ArrayList<>();
        List<Map<String, String>> accessConditions = new ArrayList<Map<String, String>>();
        Map<String, String> value = new HashMap<>();
        value.put("name", "administrator");
        accessConditions.add(value);
        addAccessCondition.add(new AddOperation("/sections/upload/files/0/accessConditions", accessConditions));
        String patchBody = getPatchContent(addAccessCondition);
        getClient(tokenSubmitter).perform(patch("/api/submission/workspaceitems/" + witem.getID()).content(patchBody).contentType(MediaType.APPLICATION_JSON_PATCH_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].name", is("administrator"))).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].startDate", nullValue())).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].endDate", nullValue()));
        // verify that the patch changes have been persisted
        getClient(tokenSubmitter).perform(get("/api/submission/workspaceitems/" + witem.getID())).andExpect(status().isOk()).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].name", is("administrator"))).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].startDate", nullValue())).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].endDate", nullValue()));
        // submit the workspaceitem to start the workflow
        getClient(tokenSubmitter).perform(post(BASE_REST_SERVER_URL + "/api/workflow/workflowitems").content("/api/submission/workspaceitems/" + witem.getID()).contentType(textUriContentType)).andExpect(status().isCreated()).andDo(result -> idRef.set(read(result.getResponse().getContentAsString(), "$.id")));
        // check that the workflowitem is persisted
        getClient(tokenSubmitter).perform(get("/api/workflow/workflowitems/" + idRef.get())).andExpect(status().isOk()).andExpect(jsonPath("$", Matchers.is(WorkflowItemMatcher.matchItemWithTitleAndDateIssued(null, "Test WorkspaceItem", "2019-10-01")))).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].name", is("administrator"))).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].startDate", nullValue())).andExpect(jsonPath("$.sections.upload.files[0].accessConditions[0].endDate", nullValue()));
        // reviewer can download the bitstream
        getClient(tokenReviewer1).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isOk()).andExpect(header().string("Accept-Ranges", "bytes")).andExpect(header().string("ETag", "\"" + bitstream.getChecksum() + "\"")).andExpect(content().contentType("text/plain")).andExpect(content().bytes(bitstreamContent.getBytes()));
        // submitter can download the bitstream
        getClient(tokenSubmitter).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isOk()).andExpect(header().string("Accept-Ranges", "bytes")).andExpect(header().string("ETag", "\"" + bitstream.getChecksum() + "\"")).andExpect(content().contentType("text/plain")).andExpect(content().bytes(bitstreamContent.getBytes()));
        // others can't download the bitstream
        getClient(tokenEPerson).perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")).andExpect(status().isForbidden());
    } finally {
        // remove the workflowitem if any
        WorkflowItemBuilder.deleteWorkflowItem(idRef.get());
    }
}
Also used : Bitstream(org.dspace.content.Bitstream) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) ReplaceOperation(org.dspace.app.rest.model.patch.ReplaceOperation) RemoveOperation(org.dspace.app.rest.model.patch.RemoveOperation) AddOperation(org.dspace.app.rest.model.patch.AddOperation) Operation(org.dspace.app.rest.model.patch.Operation) AddOperation(org.dspace.app.rest.model.patch.AddOperation) EPerson(org.dspace.eperson.EPerson) Collection(org.dspace.content.Collection) Map(java.util.Map) HashMap(java.util.HashMap) WorkspaceItem(org.dspace.content.WorkspaceItem) AbstractControllerIntegrationTest(org.dspace.app.rest.test.AbstractControllerIntegrationTest) Test(org.junit.Test)

Example 7 with Collection

use of org.dspace.content.Collection in project DSpace by DSpace.

the class ItemIndexFactoryImpl method getLocations.

@Override
public List<String> getLocations(Context context, IndexableItem indexableDSpaceObject) throws SQLException {
    final Item item = indexableDSpaceObject.getIndexedObject();
    List<String> locations = new ArrayList<>();
    // build list of community ids
    List<Community> communities = itemService.getCommunities(context, item);
    // build list of collection ids
    List<Collection> collections = item.getCollections();
    // now put those into strings
    int i = 0;
    for (i = 0; i < communities.size(); i++) {
        locations.add("m" + communities.get(i).getID());
    }
    for (i = 0; i < collections.size(); i++) {
        locations.add("l" + collections.get(i).getID());
    }
    return locations;
}
Also used : XmlWorkflowItem(org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem) WorkspaceItem(org.dspace.content.WorkspaceItem) Item(org.dspace.content.Item) ArrayList(java.util.ArrayList) Collection(org.dspace.content.Collection) Community(org.dspace.content.Community)

Example 8 with Collection

use of org.dspace.content.Collection in project DSpace by DSpace.

the class ItemIndexFactoryImpl method addDiscoveryFields.

@Override
public void addDiscoveryFields(SolrInputDocument doc, Context context, Item item, List<DiscoveryConfiguration> discoveryConfigurations) throws SQLException, IOException {
    // use the item service to retrieve the owning collection also for inprogress submission
    Collection collection = (Collection) itemService.getParentObject(context, item);
    // Keep a list of our sort values which we added, sort values can only be added once
    List<String> sortFieldsAdded = new ArrayList<>();
    Map<String, List<DiscoverySearchFilter>> searchFilters = new HashMap<>();
    Set<String> hitHighlightingFields = new HashSet<>();
    try {
        // A map used to save each sidebarFacet config by the metadata fields
        Map<String, DiscoverySortFieldConfiguration> sortFields = new HashMap<>();
        Map<String, DiscoveryRecentSubmissionsConfiguration> recentSubmissionsConfigurationMap = new HashMap<>();
        Set<String> moreLikeThisFields = new HashSet<>();
        // some configuration are returned multiple times, skip them to save CPU cycles
        Set<String> appliedConf = new HashSet<>();
        // it is common to have search filter shared between multiple configurations
        Set<String> appliedDiscoverySearchFilter = new HashSet<>();
        for (DiscoveryConfiguration discoveryConfiguration : discoveryConfigurations) {
            if (appliedConf.contains(discoveryConfiguration.getId())) {
                continue;
            } else {
                appliedConf.add(discoveryConfiguration.getId());
            }
            for (int i = 0; i < discoveryConfiguration.getSearchFilters().size(); i++) {
                if (appliedDiscoverySearchFilter.contains(discoveryConfiguration.getSearchFilters().get(i).getIndexFieldName())) {
                    continue;
                } else {
                    appliedDiscoverySearchFilter.add(discoveryConfiguration.getSearchFilters().get(i).getIndexFieldName());
                }
                List<MetadataValue> metadataValueList = new LinkedList<>();
                boolean shouldExposeMinMax = false;
                DiscoverySearchFilter discoverySearchFilter = discoveryConfiguration.getSearchFilters().get(i);
                if (StringUtils.equalsIgnoreCase(discoverySearchFilter.getFilterType(), "facet")) {
                    if (((DiscoverySearchFilterFacet) discoverySearchFilter).exposeMinAndMaxValue()) {
                        shouldExposeMinMax = true;
                    }
                }
                for (int j = 0; j < discoverySearchFilter.getMetadataFields().size(); j++) {
                    String metadataField = discoverySearchFilter.getMetadataFields().get(j);
                    List<DiscoverySearchFilter> resultingList;
                    if (searchFilters.get(metadataField) != null) {
                        resultingList = searchFilters.get(metadataField);
                    } else {
                        // New metadata field, create a new list for it
                        resultingList = new ArrayList<>();
                    }
                    if (shouldExposeMinMax) {
                        String[] splittedMetadataField = metadataField.split("\\.");
                        String schema = splittedMetadataField[0];
                        String element = splittedMetadataField.length > 1 ? splittedMetadataField[1] : null;
                        String qualifier = splittedMetadataField.length > 2 ? splittedMetadataField[2] : null;
                        metadataValueList.addAll(itemService.getMetadata(item, schema, element, qualifier, Item.ANY));
                    }
                    resultingList.add(discoverySearchFilter);
                    searchFilters.put(metadataField, resultingList);
                }
                if (!metadataValueList.isEmpty() && shouldExposeMinMax) {
                    metadataValueList.sort((mdv1, mdv2) -> mdv1.getValue().compareTo(mdv2.getValue()));
                    MetadataValue firstMetadataValue = metadataValueList.get(0);
                    MetadataValue lastMetadataValue = metadataValueList.get(metadataValueList.size() - 1);
                    doc.addField(discoverySearchFilter.getIndexFieldName() + "_min", firstMetadataValue.getValue());
                    doc.addField(discoverySearchFilter.getIndexFieldName() + "_min_sort", firstMetadataValue.getValue());
                    doc.addField(discoverySearchFilter.getIndexFieldName() + "_max", lastMetadataValue.getValue());
                    doc.addField(discoverySearchFilter.getIndexFieldName() + "_max_sort", lastMetadataValue.getValue());
                }
            }
            DiscoverySortConfiguration sortConfiguration = discoveryConfiguration.getSearchSortConfiguration();
            if (sortConfiguration != null) {
                for (DiscoverySortFieldConfiguration discoverySortConfiguration : sortConfiguration.getSortFields()) {
                    sortFields.put(discoverySortConfiguration.getMetadataField(), discoverySortConfiguration);
                }
            }
            DiscoveryRecentSubmissionsConfiguration recentSubmissionConfiguration = discoveryConfiguration.getRecentSubmissionConfiguration();
            if (recentSubmissionConfiguration != null) {
                recentSubmissionsConfigurationMap.put(recentSubmissionConfiguration.getMetadataSortField(), recentSubmissionConfiguration);
            }
            DiscoveryHitHighlightingConfiguration hitHighlightingConfiguration = discoveryConfiguration.getHitHighlightingConfiguration();
            if (hitHighlightingConfiguration != null) {
                List<DiscoveryHitHighlightFieldConfiguration> fieldConfigurations = hitHighlightingConfiguration.getMetadataFields();
                for (DiscoveryHitHighlightFieldConfiguration fieldConfiguration : fieldConfigurations) {
                    hitHighlightingFields.add(fieldConfiguration.getField());
                }
            }
            DiscoveryMoreLikeThisConfiguration moreLikeThisConfiguration = discoveryConfiguration.getMoreLikeThisConfiguration();
            if (moreLikeThisConfiguration != null) {
                for (String metadataField : moreLikeThisConfiguration.getSimilarityMetadataFields()) {
                    moreLikeThisFields.add(metadataField);
                }
            }
        }
        List<String> toProjectionFields = new ArrayList<>();
        String[] projectionFields = DSpaceServicesFactory.getInstance().getConfigurationService().getArrayProperty("discovery.index.projection");
        if (projectionFields != null) {
            for (String field : projectionFields) {
                toProjectionFields.add(field.trim());
            }
        }
        List<String> toIgnoreMetadataFields = SearchUtils.getIgnoredMetadataFields(item.getType());
        List<MetadataValue> mydc = itemService.getMetadata(item, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
        for (MetadataValue meta : mydc) {
            MetadataField metadataField = meta.getMetadataField();
            MetadataSchema metadataSchema = metadataField.getMetadataSchema();
            String field = metadataSchema.getName() + "." + metadataField.getElement();
            String unqualifiedField = field;
            String value = meta.getValue();
            if (value == null) {
                continue;
            }
            if (metadataField.getQualifier() != null && !metadataField.getQualifier().trim().equals("")) {
                field += "." + metadataField.getQualifier();
            }
            // We are not indexing provenance, this is useless
            if (toIgnoreMetadataFields != null && (toIgnoreMetadataFields.contains(field) || toIgnoreMetadataFields.contains(unqualifiedField + "." + Item.ANY))) {
                continue;
            }
            String authority = null;
            String preferedLabel = null;
            List<String> variants = null;
            boolean isAuthorityControlled = metadataAuthorityService.isAuthorityControlled(metadataField);
            int minConfidence = isAuthorityControlled ? metadataAuthorityService.getMinConfidence(metadataField) : Choices.CF_ACCEPTED;
            if (isAuthorityControlled && meta.getAuthority() != null && meta.getConfidence() >= minConfidence) {
                boolean ignoreAuthority = DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore." + field, DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore", Boolean.FALSE), true);
                if (!ignoreAuthority) {
                    authority = meta.getAuthority();
                    boolean ignorePrefered = DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore-prefered." + field, DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore-prefered", Boolean.FALSE), true);
                    if (!ignorePrefered) {
                        try {
                            preferedLabel = choiceAuthorityService.getLabel(meta, collection, meta.getLanguage());
                        } catch (Exception e) {
                            log.warn("Failed to get preferred label for " + field, e);
                        }
                    }
                    boolean ignoreVariants = DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore-variants." + field, DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyAsType("discovery.index.authority.ignore-variants", Boolean.FALSE), true);
                    if (!ignoreVariants) {
                        try {
                            variants = choiceAuthorityService.getVariants(meta, collection);
                        } catch (Exception e) {
                            log.warn("Failed to get variants for " + field, e);
                        }
                    }
                }
            }
            if ((searchFilters.get(field) != null || searchFilters.get(unqualifiedField + "." + Item.ANY) != null)) {
                List<DiscoverySearchFilter> searchFilterConfigs = searchFilters.get(field);
                if (searchFilterConfigs == null) {
                    searchFilterConfigs = searchFilters.get(unqualifiedField + "." + Item.ANY);
                }
                for (DiscoverySearchFilter searchFilter : searchFilterConfigs) {
                    Date date = null;
                    String separator = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("discovery.solr.facets.split.char");
                    if (separator == null) {
                        separator = SearchUtils.FILTER_SEPARATOR;
                    }
                    if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                        // For our search filters that are dates we format them properly
                        date = MultiFormatDateParser.parse(value);
                        if (date != null) {
                            // TODO: make this date format configurable !
                            value = DateFormatUtils.formatUTC(date, "yyyy-MM-dd");
                        }
                    }
                    doc.addField(searchFilter.getIndexFieldName(), value);
                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", value);
                    if (authority != null && preferedLabel == null) {
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword", value + SearchUtils.AUTHORITY_SEPARATOR + authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_authority", authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_acid", value.toLowerCase() + separator + value + SearchUtils.AUTHORITY_SEPARATOR + authority);
                    }
                    if (preferedLabel != null) {
                        doc.addField(searchFilter.getIndexFieldName(), preferedLabel);
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword", preferedLabel);
                        doc.addField(searchFilter.getIndexFieldName() + "_keyword", preferedLabel + SearchUtils.AUTHORITY_SEPARATOR + authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_authority", authority);
                        doc.addField(searchFilter.getIndexFieldName() + "_acid", preferedLabel.toLowerCase() + separator + preferedLabel + SearchUtils.AUTHORITY_SEPARATOR + authority);
                    }
                    if (variants != null) {
                        for (String var : variants) {
                            doc.addField(searchFilter.getIndexFieldName() + "_keyword", var);
                            doc.addField(searchFilter.getIndexFieldName() + "_acid", var.toLowerCase() + separator + var + SearchUtils.AUTHORITY_SEPARATOR + authority);
                        }
                    }
                    // Add a dynamic fields for auto complete in search
                    doc.addField(searchFilter.getIndexFieldName() + "_ac", value.toLowerCase() + separator + value);
                    if (preferedLabel != null) {
                        doc.addField(searchFilter.getIndexFieldName() + "_ac", preferedLabel.toLowerCase() + separator + preferedLabel);
                    }
                    if (variants != null) {
                        for (String var : variants) {
                            doc.addField(searchFilter.getIndexFieldName() + "_ac", var.toLowerCase() + separator + var);
                        }
                    }
                    if (searchFilter.getFilterType().equals(DiscoverySearchFilterFacet.FILTER_TYPE_FACET)) {
                        if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_TEXT)) {
                            // Solr has issues with facet prefix and cases
                            if (authority != null) {
                                String facetValue = preferedLabel != null ? preferedLabel : value;
                                doc.addField(searchFilter.getIndexFieldName() + "_filter", facetValue.toLowerCase() + separator + facetValue + SearchUtils.AUTHORITY_SEPARATOR + authority);
                            } else {
                                doc.addField(searchFilter.getIndexFieldName() + "_filter", value.toLowerCase() + separator + value);
                            }
                        } else if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                            if (date != null) {
                                String indexField = searchFilter.getIndexFieldName() + ".year";
                                String yearUTC = DateFormatUtils.formatUTC(date, "yyyy");
                                doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC);
                                // add the year to the autocomplete index
                                doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC);
                                doc.addField(indexField, yearUTC);
                                if (yearUTC.startsWith("0")) {
                                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", yearUTC.replaceFirst("0*", ""));
                                    // add date without starting zeros for autocomplete e filtering
                                    doc.addField(searchFilter.getIndexFieldName() + "_ac", yearUTC.replaceFirst("0*", ""));
                                    doc.addField(searchFilter.getIndexFieldName() + "_ac", value.replaceFirst("0*", ""));
                                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", value.replaceFirst("0*", ""));
                                }
                                // & lower bound year of our facet
                                if (doc.getField(indexField + "_sort") == null) {
                                    // We can only add one year so take the first one
                                    doc.addField(indexField + "_sort", yearUTC);
                                }
                            }
                        } else if (searchFilter.getType().equals(DiscoveryConfigurationParameters.TYPE_HIERARCHICAL)) {
                            HierarchicalSidebarFacetConfiguration hierarchicalSidebarFacetConfiguration = (HierarchicalSidebarFacetConfiguration) searchFilter;
                            String[] subValues = value.split(hierarchicalSidebarFacetConfiguration.getSplitter());
                            if (hierarchicalSidebarFacetConfiguration.isSkipFirstNodeLevel() && 1 < subValues.length) {
                                // Remove the first element of our array
                                subValues = (String[]) ArrayUtils.subarray(subValues, 1, subValues.length);
                            }
                            for (int i = 0; i < subValues.length; i++) {
                                StringBuilder valueBuilder = new StringBuilder();
                                for (int j = 0; j <= i; j++) {
                                    valueBuilder.append(subValues[j]);
                                    if (j < i) {
                                        valueBuilder.append(hierarchicalSidebarFacetConfiguration.getSplitter());
                                    }
                                }
                                String indexValue = valueBuilder.toString().trim();
                                doc.addField(searchFilter.getIndexFieldName() + "_tax_" + i + "_filter", indexValue.toLowerCase() + separator + indexValue);
                                // We add the field x times that it has occurred
                                for (int j = i; j < subValues.length; j++) {
                                    doc.addField(searchFilter.getIndexFieldName() + "_filter", indexValue.toLowerCase() + separator + indexValue);
                                    doc.addField(searchFilter.getIndexFieldName() + "_keyword", indexValue);
                                }
                            }
                        }
                    }
                }
            }
            if ((sortFields.get(field) != null || recentSubmissionsConfigurationMap.get(field) != null) && !sortFieldsAdded.contains(field)) {
                // Only add sort value once
                String type;
                if (sortFields.get(field) != null) {
                    type = sortFields.get(field).getType();
                } else {
                    type = recentSubmissionsConfigurationMap.get(field).getType();
                }
                if (type.equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
                    Date date = MultiFormatDateParser.parse(value);
                    if (date != null) {
                        String stringDate = SolrUtils.getDateFormatter().format(date);
                        doc.addField(field + "_dt", stringDate);
                    } else {
                        log.warn("Error while indexing sort date field, item: " + item.getHandle() + " metadata field: " + field + " date value: " + date);
                    }
                } else {
                    doc.addField(field + "_sort", value);
                }
                sortFieldsAdded.add(field);
            }
            if (hitHighlightingFields.contains(field) || hitHighlightingFields.contains("*") || hitHighlightingFields.contains(unqualifiedField + "." + Item.ANY)) {
                if (authority != null) {
                    doc.addField(field + "_hl", value + SearchUtils.AUTHORITY_SEPARATOR + authority);
                } else {
                    doc.addField(field + "_hl", value);
                }
            }
            if (moreLikeThisFields.contains(field) || moreLikeThisFields.contains(unqualifiedField + "." + Item.ANY)) {
                doc.addField(field + "_mlt", value);
            }
            doc.addField(field, value);
            if (authority != null) {
                doc.addField(field + "_authority", authority);
            }
            if (toProjectionFields.contains(field) || toProjectionFields.contains(unqualifiedField + "." + Item.ANY)) {
                StringBuffer variantsToStore = new StringBuffer();
                if (variants != null) {
                    for (String var : variants) {
                        variantsToStore.append(VARIANTS_STORE_SEPARATOR);
                        variantsToStore.append(var);
                    }
                }
                doc.addField(field + "_stored", value + STORE_SEPARATOR + preferedLabel + STORE_SEPARATOR + (variantsToStore.length() > VARIANTS_STORE_SEPARATOR.length() ? variantsToStore.substring(VARIANTS_STORE_SEPARATOR.length()) : "null") + STORE_SEPARATOR + authority + STORE_SEPARATOR + meta.getLanguage());
            }
            if (meta.getLanguage() != null && !meta.getLanguage().trim().equals("")) {
                String langField = field + "." + meta.getLanguage();
                doc.addField(langField, value);
            }
        }
    } catch (Exception e) {
        log.error(LogHelper.getHeader(context, "item_metadata_discovery_error", "Item identifier: " + item.getID()), e);
    }
    log.debug("  Added Metadata");
    try {
        List<MetadataValue> values = itemService.getMetadataByMetadataString(item, "dc.relation.ispartof");
        if (values != null && values.size() > 0 && values.get(0) != null && values.get(0).getValue() != null) {
            // group on parent
            String handlePrefix = handleService.getCanonicalPrefix();
            doc.addField("publication_grp", values.get(0).getValue().replaceFirst(handlePrefix, ""));
        } else {
            // group on self
            doc.addField("publication_grp", item.getHandle());
        }
    } catch (Exception e) {
        log.error(LogHelper.getHeader(context, "item_publication_group_discovery_error", "Item identifier: " + item.getID()), e);
    }
    log.debug("  Added Grouping");
}
Also used : DiscoverySearchFilterFacet(org.dspace.discovery.configuration.DiscoverySearchFilterFacet) HashMap(java.util.HashMap) DiscoveryRecentSubmissionsConfiguration(org.dspace.discovery.configuration.DiscoveryRecentSubmissionsConfiguration) ArrayList(java.util.ArrayList) DiscoveryConfiguration(org.dspace.discovery.configuration.DiscoveryConfiguration) MetadataField(org.dspace.content.MetadataField) DiscoveryHitHighlightingConfiguration(org.dspace.discovery.configuration.DiscoveryHitHighlightingConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet) MetadataValue(org.dspace.content.MetadataValue) DiscoveryHitHighlightFieldConfiguration(org.dspace.discovery.configuration.DiscoveryHitHighlightFieldConfiguration) DiscoverySortConfiguration(org.dspace.discovery.configuration.DiscoverySortConfiguration) MetadataSchema(org.dspace.content.MetadataSchema) LinkedList(java.util.LinkedList) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SQLException(java.sql.SQLException) IOException(java.io.IOException) Date(java.util.Date) DiscoverySortFieldConfiguration(org.dspace.discovery.configuration.DiscoverySortFieldConfiguration) DiscoverySearchFilter(org.dspace.discovery.configuration.DiscoverySearchFilter) Collection(org.dspace.content.Collection) DiscoveryMoreLikeThisConfiguration(org.dspace.discovery.configuration.DiscoveryMoreLikeThisConfiguration) HierarchicalSidebarFacetConfiguration(org.dspace.discovery.configuration.HierarchicalSidebarFacetConfiguration)

Example 9 with Collection

use of org.dspace.content.Collection in project DSpace by DSpace.

the class GroupServiceImpl method getParentObject.

@Override
public DSpaceObject getParentObject(Context context, Group group) throws SQLException {
    if (group == null) {
        return null;
    }
    // if all group management are disallowed
    if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup() || AuthorizeConfiguration.canCollectionAdminManageSubmitters() || AuthorizeConfiguration.canCollectionAdminManageWorkflows() || AuthorizeConfiguration.canCommunityAdminManageAdminGroup() || AuthorizeConfiguration.canCommunityAdminManageCollectionAdminGroup() || AuthorizeConfiguration.canCommunityAdminManageCollectionSubmitters() || AuthorizeConfiguration.canCommunityAdminManageCollectionWorkflows()) {
        // is this a collection related group?
        org.dspace.content.Collection collection = collectionService.findByGroup(context, group);
        if (collection != null) {
            if (group.equals(collection.getSubmitters())) {
                if (AuthorizeConfiguration.canCollectionAdminManageSubmitters()) {
                    return collection;
                } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionSubmitters()) {
                    return collectionService.getParentObject(context, collection);
                }
            }
            if (group.equals(collection.getAdministrators())) {
                if (AuthorizeConfiguration.canCollectionAdminManageAdminGroup()) {
                    return collection;
                } else if (AuthorizeConfiguration.canCommunityAdminManageCollectionAdminGroup()) {
                    return collectionService.getParentObject(context, collection);
                }
            }
        } else {
            if (AuthorizeConfiguration.canCollectionAdminManageWorkflows() || AuthorizeConfiguration.canCommunityAdminManageCollectionWorkflows()) {
                // if the group is used for one or more roles on a single collection,
                // admins can eventually manage it
                List<CollectionRole> collectionRoles = collectionRoleService.findByGroup(context, group);
                if (collectionRoles != null && collectionRoles.size() > 0) {
                    Set<Collection> colls = new HashSet<>();
                    for (CollectionRole cr : collectionRoles) {
                        colls.add(cr.getCollection());
                    }
                    if (colls.size() == 1) {
                        collection = colls.iterator().next();
                        if (AuthorizeConfiguration.canCollectionAdminManageWorkflows()) {
                            return collection;
                        } else {
                            return collectionService.getParentObject(context, collection);
                        }
                    }
                } else {
                    if (AuthorizeConfiguration.canCollectionAdminManagePolicies() || AuthorizeConfiguration.canCommunityAdminManagePolicies() || AuthorizeConfiguration.canCommunityAdminManageCollectionWorkflows()) {
                        List<Group> groups = new ArrayList<>();
                        groups.add(group);
                        List<ResourcePolicy> policies = resourcePolicyService.find(context, null, groups, Constants.DEFAULT_ITEM_READ, Constants.COLLECTION);
                        Optional<ResourcePolicy> defaultPolicy = policies.stream().filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), "ITEM"), group.getName())).findFirst();
                        if (defaultPolicy.isPresent()) {
                            return defaultPolicy.get().getdSpaceObject();
                        }
                        policies = resourcePolicyService.find(context, null, groups, Constants.DEFAULT_BITSTREAM_READ, Constants.COLLECTION);
                        defaultPolicy = policies.stream().filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), "BITSTREAM"), group.getName())).findFirst();
                        if (defaultPolicy.isPresent()) {
                            return defaultPolicy.get().getdSpaceObject();
                        }
                    }
                }
            }
            if (AuthorizeConfiguration.canCommunityAdminManageAdminGroup()) {
                // to manage it?
                return communityService.findByAdminGroup(context, group);
            }
        }
    }
    return null;
}
Also used : Group2GroupCacheDAO(org.dspace.eperson.dao.Group2GroupCacheDAO) CollectionRoleService(org.dspace.xmlworkflow.storedcomponents.service.CollectionRoleService) Event(org.dspace.event.Event) Role(org.dspace.xmlworkflow.Role) LoggerFactory(org.slf4j.LoggerFactory) GroupService(org.dspace.eperson.service.GroupService) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) GroupDAO(org.dspace.eperson.dao.GroupDAO) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) XmlWorkflowFactory(org.dspace.xmlworkflow.factory.XmlWorkflowFactory) HashSet(java.util.HashSet) Constants(org.dspace.core.Constants) SQLException(java.sql.SQLException) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) AuthorizeConfiguration(org.dspace.authorize.AuthorizeConfiguration) AuthorizeService(org.dspace.authorize.service.AuthorizeService) Collection(org.dspace.content.Collection) PoolTaskService(org.dspace.xmlworkflow.storedcomponents.service.PoolTaskService) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) MetadataField(org.dspace.content.MetadataField) DSpaceObjectServiceImpl(org.dspace.content.DSpaceObjectServiceImpl) Step(org.dspace.xmlworkflow.state.Step) AuthorizeException(org.dspace.authorize.AuthorizeException) Set(java.util.Set) UUIDUtils(org.dspace.util.UUIDUtils) UUID(java.util.UUID) EPersonService(org.dspace.eperson.service.EPersonService) ResourcePolicy(org.dspace.authorize.ResourcePolicy) ClaimedTaskService(org.dspace.xmlworkflow.storedcomponents.service.ClaimedTaskService) Objects(java.util.Objects) DSpaceObject(org.dspace.content.DSpaceObject) List(java.util.List) EPersonServiceFactory(org.dspace.eperson.factory.EPersonServiceFactory) Context(org.dspace.core.Context) PoolTask(org.dspace.xmlworkflow.storedcomponents.PoolTask) Optional(java.util.Optional) CommunityService(org.dspace.content.service.CommunityService) LogHelper(org.dspace.core.LogHelper) CollectionRole(org.dspace.xmlworkflow.storedcomponents.CollectionRole) CollectionService(org.dspace.content.service.CollectionService) ClaimedTask(org.dspace.xmlworkflow.storedcomponents.ClaimedTask) ResourcePolicyService(org.dspace.authorize.service.ResourcePolicyService) ArrayList(java.util.ArrayList) Collection(org.dspace.content.Collection) ResourcePolicy(org.dspace.authorize.ResourcePolicy) CollectionRole(org.dspace.xmlworkflow.storedcomponents.CollectionRole) Collection(org.dspace.content.Collection) HashSet(java.util.HashSet)

Example 10 with Collection

use of org.dspace.content.Collection in project DSpace by DSpace.

the class CitationDocumentServiceImpl method isCitationEnabledThroughCollection.

protected boolean isCitationEnabledThroughCollection(Context context, Bitstream bitstream) throws SQLException {
    // Reject quickly if no-enabled collections
    if (citationEnabledCollectionsList.isEmpty()) {
        return false;
    }
    DSpaceObject owningDSO = bitstreamService.getParentObject(context, bitstream);
    if (owningDSO instanceof Item) {
        Item item = (Item) owningDSO;
        List<Collection> collections = item.getCollections();
        for (Collection collection : collections) {
            if (citationEnabledCollectionsList.contains(collection.getHandle())) {
                return true;
            }
        }
    }
    // If previous logic didn't return true, then we're false
    return false;
}
Also used : Item(org.dspace.content.Item) DSpaceObject(org.dspace.content.DSpaceObject) Collection(org.dspace.content.Collection)

Aggregations

Collection (org.dspace.content.Collection)1005 Test (org.junit.Test)812 AbstractControllerIntegrationTest (org.dspace.app.rest.test.AbstractControllerIntegrationTest)733 Community (org.dspace.content.Community)652 Item (org.dspace.content.Item)514 WorkspaceItem (org.dspace.content.WorkspaceItem)342 ArrayList (java.util.ArrayList)218 EPerson (org.dspace.eperson.EPerson)209 XmlWorkflowItem (org.dspace.xmlworkflow.storedcomponents.XmlWorkflowItem)186 InputStream (java.io.InputStream)177 Operation (org.dspace.app.rest.model.patch.Operation)168 ReplaceOperation (org.dspace.app.rest.model.patch.ReplaceOperation)164 AddOperation (org.dspace.app.rest.model.patch.AddOperation)154 RemoveOperation (org.dspace.app.rest.model.patch.RemoveOperation)135 Bitstream (org.dspace.content.Bitstream)119 Matchers.emptyOrNullString (org.hamcrest.Matchers.emptyOrNullString)116 HashMap (java.util.HashMap)80 WorkflowItem (org.dspace.workflow.WorkflowItem)75 Group (org.dspace.eperson.Group)73 SQLException (java.sql.SQLException)70