Search in sources :

Example 76 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class LdapUserProviderFactory method updated.

/**
 * {@inheritDoc}
 *
 * @see org.osgi.service.cm.ManagedServiceFactory#updated(java.lang.String, java.util.Dictionary)
 */
@Override
public void updated(String pid, Dictionary properties) throws ConfigurationException {
    logger.debug("Updating LdapUserProviderFactory");
    String organization = (String) properties.get(ORGANIZATION_KEY);
    if (StringUtils.isBlank(organization))
        throw new ConfigurationException(ORGANIZATION_KEY, "is not set");
    String searchBase = (String) properties.get(SEARCH_BASE_KEY);
    if (StringUtils.isBlank(searchBase))
        throw new ConfigurationException(SEARCH_BASE_KEY, "is not set");
    String searchFilter = (String) properties.get(SEARCH_FILTER_KEY);
    if (StringUtils.isBlank(searchFilter))
        throw new ConfigurationException(SEARCH_FILTER_KEY, "is not set");
    String url = (String) properties.get(LDAP_URL_KEY);
    if (StringUtils.isBlank(url))
        throw new ConfigurationException(LDAP_URL_KEY, "is not set");
    String instanceId = (String) properties.get(INSTANCE_ID_KEY);
    if (StringUtils.isBlank(instanceId))
        throw new ConfigurationException(INSTANCE_ID_KEY, "is not set");
    String userDn = (String) properties.get(SEARCH_USER_DN);
    String password = (String) properties.get(SEARCH_PASSWORD);
    String roleAttributes = (String) properties.get(ROLE_ATTRIBUTES_KEY);
    String rolePrefix = (String) properties.get(ROLE_PREFIX_KEY);
    String[] excludePrefixes = null;
    String strExcludePrefixes = (String) properties.get(EXCLUDE_PREFIXES_KEY);
    if (StringUtils.isNotBlank(strExcludePrefixes)) {
        excludePrefixes = strExcludePrefixes.split(",");
    }
    // Make sure that property convertToUppercase is true by default
    String strUppercase = (String) properties.get(UPPERCASE_KEY);
    boolean convertToUppercase = StringUtils.isBlank(strUppercase) ? true : Boolean.valueOf(strUppercase);
    String[] extraRoles = new String[0];
    String strExtraRoles = (String) properties.get(EXTRA_ROLES_KEY);
    if (StringUtils.isNotBlank(strExtraRoles)) {
        extraRoles = strExtraRoles.split(",");
    }
    int cacheSize = 1000;
    logger.debug("Using cache size {} for {}", properties.get(CACHE_SIZE), LdapUserProviderFactory.class.getName());
    try {
        if (properties.get(CACHE_SIZE) != null) {
            Integer configuredCacheSize = Integer.parseInt(properties.get(CACHE_SIZE).toString());
            if (configuredCacheSize != null) {
                cacheSize = configuredCacheSize.intValue();
            }
        }
    } catch (Exception e) {
        logger.warn("{} could not be loaded, default value is used: {}", CACHE_SIZE, cacheSize);
    }
    int cacheExpiration = 1;
    try {
        if (properties.get(CACHE_EXPIRATION) != null) {
            Integer configuredCacheExpiration = Integer.parseInt(properties.get(CACHE_EXPIRATION).toString());
            if (configuredCacheExpiration != null) {
                cacheExpiration = configuredCacheExpiration.intValue();
            }
        }
    } catch (Exception e) {
        logger.warn("{} could not be loaded, default value is used: {}", CACHE_EXPIRATION, cacheExpiration);
    }
    // Now that we have everything we need, go ahead and activate a new provider, removing an old one if necessary
    ServiceRegistration existingRegistration = providerRegistrations.remove(pid);
    if (existingRegistration != null) {
        existingRegistration.unregister();
    }
    Organization org;
    try {
        org = orgDirectory.getOrganization(organization);
    } catch (NotFoundException e) {
        logger.warn("Organization {} not found!", organization);
        throw new ConfigurationException(ORGANIZATION_KEY, "not found");
    }
    // Dictionary to include a property to identify this LDAP instance in the security.xml file
    Hashtable<String, String> dict = new Hashtable<>();
    dict.put(INSTANCE_ID_SERVICE_PROPERTY_KEY, instanceId);
    // Instantiate this LDAP instance and register it as such
    LdapUserProviderInstance provider = new LdapUserProviderInstance(pid, org, searchBase, searchFilter, url, userDn, password, roleAttributes, rolePrefix, extraRoles, excludePrefixes, convertToUppercase, cacheSize, cacheExpiration, securityService);
    providerRegistrations.put(pid, bundleContext.registerService(UserProvider.class.getName(), provider, null));
    OpencastLdapAuthoritiesPopulator authoritiesPopulator = new OpencastLdapAuthoritiesPopulator(roleAttributes, rolePrefix, excludePrefixes, convertToUppercase, org, securityService, groupRoleProvider, extraRoles);
    // Also, register this instance as LdapAuthoritiesPopulator so that it can be used within the security.xml file
    authoritiesPopulatorRegistrations.put(pid, bundleContext.registerService(LdapAuthoritiesPopulator.class.getName(), authoritiesPopulator, dict));
}
Also used : Organization(org.opencastproject.security.api.Organization) Hashtable(java.util.Hashtable) NotFoundException(org.opencastproject.util.NotFoundException) NotFoundException(org.opencastproject.util.NotFoundException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 77 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class JpaGroupRoleProviderTest method testUpdateGroupNotAllowedAsNonAdminUser.

@Test
public void testUpdateGroupNotAllowedAsNonAdminUser() throws UnauthorizedException {
    JpaGroup group = new JpaGroup("test", org1, "Test", "Test group", Collections.set(new JpaRole(SecurityConstants.GLOBAL_ADMIN_ROLE, org1)));
    try {
        provider.addGroup(group);
        Group loadGroup = provider.loadGroup(group.getGroupId(), group.getOrganization().getId());
        assertNotNull(loadGroup);
        assertEquals(loadGroup.getGroupId(), loadGroup.getGroupId());
    } catch (Exception e) {
        fail("The group schould be added");
    }
    JpaUser user = new JpaUser("user", "pass1", org1, "User", "user@localhost", "opencast", true, Collections.set(new JpaRole("ROLE_USER", org1)));
    // Set the security sevice
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(user).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(org1).anyTimes();
    EasyMock.replay(securityService);
    provider.setSecurityService(securityService);
    try {
        // try add ROLE_USER
        Response updateGroupResponse = provider.updateGroup(group.getGroupId(), group.getName(), group.getDescription(), "ROLE_USER, " + SecurityConstants.GLOBAL_ADMIN_ROLE, null);
        assertNotNull(updateGroupResponse);
        assertEquals(HttpStatus.SC_FORBIDDEN, updateGroupResponse.getStatus());
        // try remove ROLE_ADMIN
        updateGroupResponse = provider.updateGroup(group.getGroupId(), group.getName(), group.getDescription(), "ROLE_USER", null);
        assertNotNull(updateGroupResponse);
        assertEquals(HttpStatus.SC_FORBIDDEN, updateGroupResponse.getStatus());
    } catch (NotFoundException e) {
        fail("The existing group isn't found");
    }
}
Also used : JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) Response(javax.ws.rs.core.Response) JpaGroup(org.opencastproject.security.impl.jpa.JpaGroup) Group(org.opencastproject.security.api.Group) SecurityService(org.opencastproject.security.api.SecurityService) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Test(org.junit.Test)

Example 78 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class JpaUserProviderTest method testUpdateUser.

@Test
public void testUpdateUser() throws Exception {
    Set<JpaRole> authorities = new HashSet<JpaRole>();
    authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));
    JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
    provider.addUser(user);
    User loadUser = provider.loadUser("user1");
    assertNotNull(loadUser);
    authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
    String newPassword = "newPassword";
    JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);
    User loadUpdatedUser = provider.updateUser(updateUser);
    // User loadUpdatedUser = provider.loadUser(user.getUsername());
    assertNotNull(loadUpdatedUser);
    assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
    assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());
    assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());
    updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);
    try {
        provider.updateUser(updateUser);
        fail("Should throw a NotFoundException");
    } catch (NotFoundException e) {
        assertTrue("User not found.", true);
    }
}
Also used : User(org.opencastproject.security.api.User) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 79 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class AbstractEventEndpoint method updateAssets.

// MH-12085 Add manually uploaded assets, multipart file upload has to be a POST
@POST
@Path("{eventId}/assets")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RestQuery(name = "updateAssets", description = "Update or create an asset for the eventId by the given metadata as JSON and files in the body", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "metadata", isRequired = true, type = RestParameter.Type.TEXT, description = "The list of asset metadata") }, reponses = { @RestResponse(description = "The asset has been added.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Could not add asset, problem with the metadata or files.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }, returnDescription = "The workflow identifier")
public Response updateAssets(@PathParam("eventId") final String eventId, @Context HttpServletRequest request) throws Exception {
    try {
        MediaPackage mp = getMediaPackageByEventId(eventId);
        String result = getIndexService().updateEventAssets(mp, request);
        return Response.status(Status.CREATED).entity(result).build();
    } catch (NotFoundException e) {
        return notFound("Cannot find an event with id '%s'.", eventId);
    } catch (IllegalArgumentException e) {
        return RestUtil.R.badRequest(e.getMessage());
    } catch (Exception e) {
        return RestUtil.R.serverError();
    }
}
Also used : MediaPackage(org.opencastproject.mediapackage.MediaPackage) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 80 with NotFoundException

use of org.opencastproject.util.NotFoundException in project opencast by opencast.

the class AbstractEventEndpoint method updateEventWorkflow.

@PUT
@Path("{eventId}/workflows")
@RestQuery(name = "updateEventWorkflow", description = "Update the workflow configuration for the scheduled event with the given id", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "configuration", isRequired = true, description = "The workflow configuration as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "Request executed succesfully", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }, returnDescription = "The method does not retrun any content.")
public Response updateEventWorkflow(@PathParam("eventId") String id, @FormParam("configuration") String configuration) throws SearchIndexException, UnauthorizedException {
    Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", id);
    if (!optEvent.get().hasRecordingStarted()) {
        try {
            JSONObject configJSON;
            try {
                configJSON = (JSONObject) new JSONParser().parse(configuration);
            } catch (Exception e) {
                logger.warn("Unable to parse the workflow configuration {}", configuration);
                return badRequest();
            }
            Opt<Map<String, String>> caMetadataOpt = Opt.none();
            Opt<Map<String, String>> workflowConfigOpt = Opt.none();
            String workflowId = (String) configJSON.get("id");
            Map<String, String> caMetadata = new HashMap<>(getSchedulerService().getCaptureAgentConfiguration(id));
            if (!workflowId.equals(caMetadata.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION))) {
                caMetadata.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowId);
                caMetadataOpt = Opt.some(caMetadata);
            }
            Map<String, String> workflowConfig = new HashMap<>((JSONObject) configJSON.get("configuration"));
            Map<String, String> oldWorkflowConfig = new HashMap<>(getSchedulerService().getWorkflowConfig(id));
            if (!oldWorkflowConfig.equals(workflowConfig))
                workflowConfigOpt = Opt.some(workflowConfig);
            if (caMetadataOpt.isNone() && workflowConfigOpt.isNone())
                return Response.noContent().build();
            getSchedulerService().updateEvent(id, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.<MediaPackage>none(), workflowConfigOpt, caMetadataOpt, Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
            return Response.noContent().build();
        } catch (NotFoundException e) {
            return notFound("Cannot find event %s in scheduler service", id);
        } catch (SchedulerException e) {
            logger.error("Unable to update scheduling workflow data for event with id {}", id);
            throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        return badRequest(String.format("Event %s workflow can not be updated as the recording already started.", id));
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) JSONObject(org.json.simple.JSONObject) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

NotFoundException (org.opencastproject.util.NotFoundException)382 IOException (java.io.IOException)137 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)130 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)79 MediaPackage (org.opencastproject.mediapackage.MediaPackage)69 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)67 EntityManager (javax.persistence.EntityManager)55 SeriesException (org.opencastproject.series.api.SeriesException)53 Path (javax.ws.rs.Path)52 WebApplicationException (javax.ws.rs.WebApplicationException)52 RestQuery (org.opencastproject.util.doc.rest.RestQuery)51 ConfigurationException (org.osgi.service.cm.ConfigurationException)51 URI (java.net.URI)50 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)50 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)49 Date (java.util.Date)48 Test (org.junit.Test)47 File (java.io.File)46 HttpResponse (org.apache.http.HttpResponse)46 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)46