Search in sources :

Example 26 with NotNull

use of javax.validation.constraints.NotNull in project graylog2-server by Graylog2.

the class RestTools method buildExternalUri.

public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) {
    Optional<URI> externalUri = Optional.empty();
    final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER);
    if (headers != null && !headers.isEmpty()) {
        externalUri = headers.stream().filter(s -> {
            try {
                if (Strings.isNullOrEmpty(s)) {
                    return false;
                }
                final URI uri = new URI(s);
                if (!uri.isAbsolute()) {
                    return true;
                }
                switch(uri.getScheme()) {
                    case "http":
                    case "https":
                        return true;
                }
                return false;
            } catch (URISyntaxException e) {
                return false;
            }
        }).map(URI::create).findFirst();
    }
    final URI uri = externalUri.orElse(defaultUri);
    // Make sure we return an URI object with a trailing slash
    if (!uri.toString().endsWith("/")) {
        return URI.create(uri.toString() + "/");
    }
    return uri;
}
Also used : Request(org.glassfish.grizzly.http.server.Request) URISyntaxException(java.net.URISyntaxException) SecurityContext(javax.ws.rs.core.SecurityContext) Set(java.util.Set) ShiroPrincipal(org.graylog2.shared.security.ShiroPrincipal) NotNull(javax.validation.constraints.NotNull) UnknownHostException(java.net.UnknownHostException) IpSubnet(org.graylog2.utilities.IpSubnet) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Strings(com.google.common.base.Strings) HttpConfiguration(org.graylog2.configuration.HttpConfiguration) List(java.util.List) Principal(java.security.Principal) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Optional(java.util.Optional) URI(java.net.URI) Resource(org.glassfish.jersey.server.model.Resource) Nullable(javax.annotation.Nullable) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 27 with NotNull

use of javax.validation.constraints.NotNull in project CzechIdMng by bcvsolutions.

the class SysRemoteServerController method getConnectorTypes.

/**
 * Returns connector types registered on given remote server.
 *
 * @return connector types
 */
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{backendId}/connector-types")
@PreAuthorize("hasAuthority('" + AccGroupPermission.REMOTESERVER_READ + "')")
@ApiOperation(value = "Get supported connector types", nickname = "getConnectorTypes", tags = { SysRemoteServerController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = AccGroupPermission.REMOTESERVER_READ, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = AccGroupPermission.REMOTESERVER_READ, description = "") }) })
public Resources<ConnectorTypeDto> getConnectorTypes(@ApiParam(value = "Remote server uuid identifier or code.", required = true) @PathVariable @NotNull String backendId) {
    SysConnectorServerDto connectorServer = getDto(backendId);
    if (connectorServer == null) {
        throw new EntityNotFoundException(getService().getEntityClass(), backendId);
    }
    // 
    try {
        List<IcConnectorInfo> connectorInfos = Lists.newArrayList();
        for (IcConfigurationService config : icConfiguration.getIcConfigs().values()) {
            connectorServer.setPassword(remoteServerService.getPassword(connectorServer.getId()));
            Set<IcConnectorInfo> availableRemoteConnectors = config.getAvailableRemoteConnectors(connectorServer);
            if (CollectionUtils.isNotEmpty(availableRemoteConnectors)) {
                connectorInfos.addAll(availableRemoteConnectors);
            }
        }
        // Find connector types for existing connectors.
        List<ConnectorTypeDto> connectorTypes = connectorManager.getSupportedTypes().stream().filter(connectorType -> {
            return connectorInfos.stream().anyMatch(connectorInfo -> connectorType.getConnectorName().equals(connectorInfo.getConnectorKey().getConnectorName()));
        }).map(connectorType -> {
            // Find connector info and set version to the connectorTypeDto.
            IcConnectorInfo info = connectorInfos.stream().filter(connectorInfo -> connectorType.getConnectorName().equals(connectorInfo.getConnectorKey().getConnectorName())).findFirst().orElse(null);
            ConnectorTypeDto connectorTypeDto = connectorManager.convertTypeToDto(connectorType);
            connectorTypeDto.setLocal(true);
            if (info != null) {
                connectorTypeDto.setVersion(info.getConnectorKey().getBundleVersion());
                connectorTypeDto.setName(info.getConnectorDisplayName());
            }
            return connectorTypeDto;
        }).collect(Collectors.toList());
        // Find connectors without extension (specific connector type).
        List<ConnectorTypeDto> defaultConnectorTypes = connectorInfos.stream().map(info -> {
            ConnectorTypeDto connectorTypeDto = connectorManager.convertIcConnectorInfoToDto(info);
            connectorTypeDto.setLocal(true);
            return connectorTypeDto;
        }).filter(type -> {
            return !connectorTypes.stream().anyMatch(supportedType -> supportedType.getConnectorName().equals(type.getConnectorName()) && supportedType.isHideParentConnector());
        }).collect(Collectors.toList());
        connectorTypes.addAll(defaultConnectorTypes);
        return new Resources<>(connectorTypes.stream().sorted(Comparator.comparing(ConnectorTypeDto::getOrder)).collect(Collectors.toList()));
    } catch (IcInvalidCredentialException e) {
        throw new ResultCodeException(AccResultCode.REMOTE_SERVER_INVALID_CREDENTIAL, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
    } catch (IcServerNotFoundException e) {
        throw new ResultCodeException(AccResultCode.REMOTE_SERVER_NOT_FOUND, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
    } catch (IcCantConnectException e) {
        throw new ResultCodeException(AccResultCode.REMOTE_SERVER_CANT_CONNECT, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
    } catch (IcRemoteServerException e) {
        throw new ResultCodeException(AccResultCode.REMOTE_SERVER_UNEXPECTED_ERROR, ImmutableMap.of("server", e.getHost() + ":" + e.getPort()), e);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) IcRemoteServerException(eu.bcvsolutions.idm.ic.exception.IcRemoteServerException) Autowired(org.springframework.beans.factory.annotation.Autowired) Enabled(eu.bcvsolutions.idm.core.security.api.domain.Enabled) ApiParam(io.swagger.annotations.ApiParam) SysConnectorServerDto(eu.bcvsolutions.idm.acc.dto.SysConnectorServerDto) IcInvalidCredentialException(eu.bcvsolutions.idm.ic.exception.IcInvalidCredentialException) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) SysRemoteServerService(eu.bcvsolutions.idm.acc.service.api.SysRemoteServerService) Pageable(org.springframework.data.domain.Pageable) AuthorizationScope(io.swagger.annotations.AuthorizationScope) IcCantConnectException(eu.bcvsolutions.idm.ic.exception.IcCantConnectException) IcConfigurationFacade(eu.bcvsolutions.idm.ic.service.api.IcConfigurationFacade) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) ImmutableMap(com.google.common.collect.ImmutableMap) MediaType(org.springframework.http.MediaType) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) List(java.util.List) ConnectorManager(eu.bcvsolutions.idm.acc.service.api.ConnectorManager) IcConnectorInfo(eu.bcvsolutions.idm.ic.api.IcConnectorInfo) SysRemoteServerFilter(eu.bcvsolutions.idm.acc.dto.filter.SysRemoteServerFilter) AccResultCode(eu.bcvsolutions.idm.acc.domain.AccResultCode) ResultModels(eu.bcvsolutions.idm.core.api.dto.ResultModels) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) CollectionUtils(org.apache.commons.collections4.CollectionUtils) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) AbstractReadWriteDtoController(eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoController) SwaggerConfig(eu.bcvsolutions.idm.core.api.config.swagger.SwaggerConfig) AccGroupPermission(eu.bcvsolutions.idm.acc.domain.AccGroupPermission) IcConfigurationService(eu.bcvsolutions.idm.ic.service.api.IcConfigurationService) ConnectorTypeDto(eu.bcvsolutions.idm.acc.dto.ConnectorTypeDto) Api(io.swagger.annotations.Api) AccModuleDescriptor(eu.bcvsolutions.idm.acc.AccModuleDescriptor) IcServerNotFoundException(eu.bcvsolutions.idm.ic.exception.IcServerNotFoundException) MultiValueMap(org.springframework.util.MultiValueMap) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpStatus(org.springframework.http.HttpStatus) IdmBulkActionDto(eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto) BaseController(eu.bcvsolutions.idm.core.api.rest.BaseController) BaseDtoController(eu.bcvsolutions.idm.core.api.rest.BaseDtoController) PageableDefault(org.springframework.data.web.PageableDefault) Resources(org.springframework.hateoas.Resources) ResponseEntity(org.springframework.http.ResponseEntity) Comparator(java.util.Comparator) Authorization(io.swagger.annotations.Authorization) IcServerNotFoundException(eu.bcvsolutions.idm.ic.exception.IcServerNotFoundException) IcInvalidCredentialException(eu.bcvsolutions.idm.ic.exception.IcInvalidCredentialException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) EntityNotFoundException(eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException) ConnectorTypeDto(eu.bcvsolutions.idm.acc.dto.ConnectorTypeDto) IcConnectorInfo(eu.bcvsolutions.idm.ic.api.IcConnectorInfo) IcConfigurationService(eu.bcvsolutions.idm.ic.service.api.IcConfigurationService) IcCantConnectException(eu.bcvsolutions.idm.ic.exception.IcCantConnectException) IcRemoteServerException(eu.bcvsolutions.idm.ic.exception.IcRemoteServerException) Resources(org.springframework.hateoas.Resources) SysConnectorServerDto(eu.bcvsolutions.idm.acc.dto.SysConnectorServerDto) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 28 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class AbstractGitPersistableService method findEntityState.

@NotNull
public T findEntityState(T1 gitPersistable, Supplier<T> stateSupplier) {
    T defaultState;
    if (gitPersistable.isNew()) {
        defaultState = stateSupplier.get();
        defaultState.setId(generateId(gitPersistable));
        getEntityStateRepository().save(defaultState);
        gitPersistable.setId(defaultState.getId());
        return defaultState;
    }
    T existingState = getEntityStateRepository().findOne(gitPersistable.getId());
    if (existingState == null) {
        defaultState = stateSupplier.get();
        defaultState.setId(gitPersistable.getId());
        getEntityStateRepository().save(defaultState);
        return defaultState;
    }
    return existingState;
}
Also used : DRAFT(org.obiba.mica.core.domain.RevisionStatus.DRAFT) NotNull(javax.validation.constraints.NotNull)

Example 29 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class UserProfileService method currentUserIs.

public boolean currentUserIs(@NotNull String role) {
    org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
    if (subject == null || subject.getPrincipal() == null) {
        return false;
    }
    String username = subject.getPrincipal().toString();
    if (username.equals("administrator")) {
        return true;
    }
    ObibaRealm.Subject profile = getProfile(username);
    return profile != null && profile.getGroups() != null && profile.getGroups().stream().filter(g -> g.equals(role)).count() > 0;
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) MicaConfig(org.obiba.mica.micaConfig.domain.MicaConfig) ESAPI(org.owasp.esapi.ESAPI) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) Subject(org.obiba.shiro.realm.ObibaRealm.Subject) Service(org.springframework.stereotype.Service) Map(java.util.Map) Nullable(javax.annotation.Nullable) DateTimeFormat(org.joda.time.format.DateTimeFormat) org.springframework.web.client(org.springframework.web.client) MailService(org.obiba.mica.core.service.MailService) Logger(org.slf4j.Logger) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) HttpHeaders(org.springframework.http.HttpHeaders) HttpMethod(org.springframework.http.HttpMethod) NotNull(javax.validation.constraints.NotNull) Maps(com.google.common.collect.Maps) ObibaRealm(org.obiba.shiro.realm.ObibaRealm) TimeUnit(java.util.concurrent.TimeUnit) HttpEntity(org.springframework.http.HttpEntity) URLEncoder(java.net.URLEncoder) List(java.util.List) MicaConfigService(org.obiba.mica.micaConfig.service.MicaConfigService) ResponseEntity(org.springframework.http.ResponseEntity) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) SecurityUtils(org.apache.shiro.SecurityUtils) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AgateRestService(org.obiba.mica.core.service.AgateRestService) Assert(org.springframework.util.Assert) ObibaRealm(org.obiba.shiro.realm.ObibaRealm) Subject(org.obiba.shiro.realm.ObibaRealm.Subject)

Example 30 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class AttachmentDtos method asFileDto.

@NotNull
Mica.FileDto asFileDto(AttachmentState state, boolean publishedFileSystem, boolean detailed) {
    Mica.FileDto.Builder builder = asFileDto(state).toBuilder();
    if (publishedFileSystem) {
        builder.clearRevisionStatus();
        Attachment attachment = state.getAttachment();
        if (!Strings.isNullOrEmpty(attachment.getType()))
            builder.setMediaType(attachment.getType());
        if (attachment.getDescription() != null)
            builder.addAllDescription(localizedStringDtos.asDto(attachment.getDescription()));
    } else {
        builder.setState(asDto(state, detailed));
        builder.setPermissions(permissionsDtos.asDto(state));
    }
    if (builder.getType() == Mica.FileType.FOLDER) {
        // get the number of files in the folder
        builder.setSize(fileSystemService.countAttachmentStates(state.getPath(), publishedFileSystem));
    }
    return builder.build();
}
Also used : Attachment(org.obiba.mica.file.Attachment) NotNull(javax.validation.constraints.NotNull)

Aggregations

NotNull (javax.validation.constraints.NotNull)76 List (java.util.List)24 Map (java.util.Map)18 Collectors (java.util.stream.Collectors)15 Inject (javax.inject.Inject)15 Logger (org.slf4j.Logger)14 ArrayList (java.util.ArrayList)13 LoggerFactory (org.slf4j.LoggerFactory)13 HashMap (java.util.HashMap)11 Set (java.util.Set)10 Optional (java.util.Optional)9 Response (javax.ws.rs.core.Response)9 Strings (com.google.common.base.Strings)8 Lists (com.google.common.collect.Lists)8 Api (io.swagger.annotations.Api)7 ApiParam (io.swagger.annotations.ApiParam)7 IOException (java.io.IOException)7 Collection (java.util.Collection)7 Nullable (javax.annotation.Nullable)7 Valid (javax.validation.Valid)7