Search in sources :

Example 56 with Value

use of org.springframework.beans.factory.annotation.Value in project ArachneCentralAPI by OHDSI.

the class BaseAnalysisController method list.

@ApiOperation("List analyses.")
@RequestMapping(value = "/api/v1/analysis-management/analyses", method = GET)
public JsonResult<List<D>> list(Principal principal, @RequestParam("study-id") Long studyId) throws PermissionDeniedException, NotExistException {
    JsonResult<List<D>> result;
    IUser user = userService.getByUsername(principal.getName());
    if (user == null) {
        result = new JsonResult<>(PERMISSION_DENIED);
        return result;
    }
    Iterable<T> analyses = analysisService.list(user, studyId);
    result = new JsonResult<>(NO_ERROR);
    List<D> analysisDTOs = StreamSupport.stream(analyses.spliterator(), false).map(analysis -> conversionService.convert(analysis, getAnalysisDTOClass())).collect(Collectors.toList());
    result.setResult(analysisDTOs);
    return result;
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) UploadFilesDTO(com.odysseusinc.arachne.portal.api.v1.dto.UploadFilesDTO) Valid(javax.validation.Valid) CommentUtils.getRecentCommentables(com.odysseusinc.arachne.portal.util.CommentUtils.getRecentCommentables) AnalysisLockDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisLockDTO) Analysis(com.odysseusinc.arachne.portal.model.Analysis) Commentable(com.odysseusinc.arachne.portal.api.v1.dto.Commentable) Sort(org.springframework.data.domain.Sort) ImportedFile(com.odysseusinc.arachne.portal.util.ImportedFile) Resource(org.springframework.core.io.Resource) MessagingUtils(com.odysseusinc.arachne.portal.service.messaging.MessagingUtils) FieldError(org.springframework.validation.FieldError) Set(java.util.Set) AnalysisFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisFileDTO) Page(org.springframework.data.domain.Page) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) IUser(com.odysseusinc.arachne.portal.model.IUser) IOUtils(org.apache.commons.io.IOUtils) SimpMessagingTemplate(org.springframework.messaging.simp.SimpMessagingTemplate) Stream(java.util.stream.Stream) AnalysisFilesSavingService(com.odysseusinc.arachne.portal.service.analysis.AnalysisFilesSavingService) VALIDATION_ERROR(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.VALIDATION_ERROR) DataReference(com.odysseusinc.arachne.portal.model.DataReference) BindingResult(org.springframework.validation.BindingResult) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) SubmissionInsightDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionInsightDTO) NO_ERROR(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.NO_ERROR) StreamSupport(java.util.stream.StreamSupport) CommonEntityRequestDTO(com.odysseusinc.arachne.commons.api.v1.dto.CommonEntityRequestDTO) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) IOException(java.io.IOException) HttpUtils.putFileContentToResponse(com.odysseusinc.arachne.portal.util.HttpUtils.putFileContentToResponse) SubmissionInsightUpdateDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionInsightUpdateDTO) DataReferenceDTO(com.odysseusinc.arachne.portal.api.v1.dto.DataReferenceDTO) AnalysisFile(com.odysseusinc.arachne.portal.model.AnalysisFile) UpdateNotificationDTO(com.odysseusinc.arachne.portal.api.v1.dto.UpdateNotificationDTO) AnalysisUpdateDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisUpdateDTO) PathVariable(org.springframework.web.bind.annotation.PathVariable) AnalysisUnlockRequestDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisUnlockRequestDTO) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) LoggerFactory(org.slf4j.LoggerFactory) ValidationRuntimeException(com.odysseusinc.arachne.portal.exception.ValidationRuntimeException) ApiOperation(io.swagger.annotations.ApiOperation) PutMapping(org.springframework.web.bind.annotation.PutMapping) AnalysisUnlockRequest(com.odysseusinc.arachne.portal.model.AnalysisUnlockRequest) PERMISSION_DENIED(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.PERMISSION_DENIED) ToPdfConverter(com.odysseusinc.arachne.portal.service.ToPdfConverter) BaseSubmissionService(com.odysseusinc.arachne.portal.service.submission.BaseSubmissionService) BaseAnalysisService(com.odysseusinc.arachne.portal.service.analysis.BaseAnalysisService) AnalysisDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisDTO) AlreadyExistException(com.odysseusinc.arachne.portal.exception.AlreadyExistException) CommonAnalysisType(com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisType) UUID(java.util.UUID) ShortBaseAnalysisDTO(com.odysseusinc.arachne.portal.api.v1.dto.ShortBaseAnalysisDTO) JMSException(javax.jms.JMSException) Collectors(java.util.stream.Collectors) FileDTO(com.odysseusinc.arachne.portal.api.v1.dto.FileDTO) List(java.util.List) Principal(java.security.Principal) DataReferenceService(com.odysseusinc.arachne.portal.service.DataReferenceService) AnalysisCreateDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisCreateDTO) AnalysisUnlockRequestStatus(com.odysseusinc.arachne.portal.model.AnalysisUnlockRequestStatus) SubmissionGroupDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionGroupDTO) NotUniqueException(com.odysseusinc.arachne.portal.exception.NotUniqueException) FileDtoContentHandler(com.odysseusinc.arachne.portal.api.v1.dto.converters.FileDtoContentHandler) ClassPathResource(org.springframework.core.io.ClassPathResource) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ObjectMessage(javax.jms.ObjectMessage) GET(org.springframework.web.bind.annotation.RequestMethod.GET) Submission(com.odysseusinc.arachne.portal.model.Submission) SubmissionGroupSearch(com.odysseusinc.arachne.portal.model.search.SubmissionGroupSearch) ValidationException(com.odysseusinc.arachne.portal.exception.ValidationException) JsonResult(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) HeraclesAnalysisService(com.odysseusinc.arachne.portal.service.analysis.heracles.HeraclesAnalysisService) JmsTemplate(org.springframework.jms.core.JmsTemplate) ProducerConsumerTemplate(com.odysseusinc.arachne.commons.service.messaging.ProducerConsumerTemplate) SubmissionInsight(com.odysseusinc.arachne.portal.model.SubmissionInsight) POST(org.springframework.web.bind.annotation.RequestMethod.POST) UploadFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.UploadFileDTO) DestinationResolver(org.springframework.jms.support.destination.DestinationResolver) ServiceNotAvailableException(com.odysseusinc.arachne.portal.exception.ServiceNotAvailableException) CommentTopic(com.odysseusinc.arachne.portal.model.CommentTopic) Logger(org.slf4j.Logger) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) CommonFilenameUtils(com.odysseusinc.arachne.commons.utils.CommonFilenameUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) BaseDataNodeService(com.odysseusinc.arachne.portal.service.BaseDataNodeService) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) OptionDTO(com.odysseusinc.arachne.commons.api.v1.dto.OptionDTO) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) HeraclesAnalysisKind(com.odysseusinc.arachne.portal.service.analysis.heracles.HeraclesAnalysisKind) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) DataNode(com.odysseusinc.arachne.portal.model.DataNode) MultipartFile(org.springframework.web.multipart.MultipartFile) ImportService(com.odysseusinc.arachne.portal.service.ImportService) NotEmptyException(com.odysseusinc.arachne.portal.exception.NotEmptyException) SubmissionInsightService(com.odysseusinc.arachne.portal.service.submission.SubmissionInsightService) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) InputStream(java.io.InputStream) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) GET(org.springframework.web.bind.annotation.RequestMethod.GET) POST(org.springframework.web.bind.annotation.RequestMethod.POST) PERMISSION_DENIED(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.PERMISSION_DENIED) UUID(java.util.UUID) IUser(com.odysseusinc.arachne.portal.model.IUser) ArrayList(java.util.ArrayList) List(java.util.List) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 57 with Value

use of org.springframework.beans.factory.annotation.Value in project tephra by heisedebaise.

the class StatusImpl method setVersion.

private void setVersion(Map<String, Set<String>> map) {
    Set<String> set = new HashSet<>();
    map.forEach((key, value) -> {
        if (value.size() > 1)
            set.add(key);
    });
    set.forEach(map::remove);
    Map<String, String> versions = new HashMap<>();
    map.forEach((key, value) -> versions.put(key, value.iterator().next()));
    set.clear();
    versions.forEach((key, value) -> versions.forEach((k, v) -> {
        if (key.contains(k) && !key.equals(k) && value.equals(v))
            set.add(key);
    }));
    set.forEach(versions::remove);
    version = new JSONObject();
    versions.forEach((key, value) -> version.put(key.substring(1), value));
}
Also used : BeanFactory(org.lpw.tephra.bean.BeanFactory) Set(java.util.Set) HashMap(java.util.HashMap) Value(org.springframework.beans.factory.annotation.Value) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Service(org.springframework.stereotype.Service) ContextRefreshedListener(org.lpw.tephra.bean.ContextRefreshedListener) Map(java.util.Map) JSONObject(com.alibaba.fastjson.JSONObject) CodeSource(java.security.CodeSource) Logger(org.lpw.tephra.util.Logger) Validator(org.lpw.tephra.util.Validator) JSONObject(com.alibaba.fastjson.JSONObject) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 58 with Value

use of org.springframework.beans.factory.annotation.Value in project irida by phac-nml.

the class ProjectsController method exportProjectsToFile.

/**
 * Export Projects table as either an excel file or CSV
 *
 * @param type
 * 		of file to export (csv or excel)
 * @param isAdmin
 * 		if the currently logged in user is an administrator
 * @param response
 * 		{@link HttpServletResponse}
 * @param principal
 * 		{@link Principal}
 * @param locale
 * 		{@link Locale}
 *
 * @throws IOException
 * 		thrown if cannot open the {@link HttpServletResponse} {@link OutputStream}
 */
@RequestMapping("/projects/ajax/export")
public void exportProjectsToFile(@RequestParam(value = "dtf") String type, @RequestParam(required = false, defaultValue = "false", value = "admin") Boolean isAdmin, HttpServletResponse response, Principal principal, Locale locale) throws IOException {
    // Let's make sure the export type is set properly
    if (!(type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("csv"))) {
        throw new IllegalArgumentException("No file type sent for downloading all projects.  Expecting parameter 'dtf=' xlsx or csv");
    }
    List<Project> projects;
    // If viewing the admin projects page give the user all the projects.
    if (isAdmin) {
        projects = (List<Project>) projectService.findAll();
    } else // If on the users projects page, give the user their projects.
    {
        User user = userService.getUserByUsername(principal.getName());
        projects = projectService.getProjectsForUser(user).stream().map(Join::getSubject).collect(Collectors.toList());
    }
    List<DTProject> dtProjects = projects.stream().map(this::createDataTablesProject).collect(Collectors.toList());
    List<String> headers = ImmutableList.of("id", "name", "organism", "samples", "created", "modified").stream().map(h -> messageSource.getMessage("projects.table." + h, new Object[] {}, locale)).collect(Collectors.toList());
    // Create the filename
    Date date = new Date();
    DateFormat fileDateFormat = new SimpleDateFormat(messageSource.getMessage("date.iso-8601", null, locale));
    String filename = "IRIDA_projects_" + fileDateFormat.format(date);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "." + type + "\"");
    if (type.equals("xlsx")) {
        writeProjectsToExcelFile(headers, dtProjects, locale, response);
    } else {
        writeProjectsToCsvFile(headers, dtProjects, locale, response);
    }
}
Also used : ProjectRole(ca.corefacility.bioinformatics.irida.model.enums.ProjectRole) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ProjectService(ca.corefacility.bioinformatics.irida.service.ProjectService) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) TaxonomyService(ca.corefacility.bioinformatics.irida.service.TaxonomyService) Model(org.springframework.ui.Model) CSVFormat(org.apache.commons.csv.CSVFormat) DataTablesResponseModel(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.models.DataTablesResponseModel) Cell(org.apache.poi.ss.usermodel.Cell) DataTablesResponse(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesResponse) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) DTProject(ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTProject) ConstraintViolation(javax.validation.ConstraintViolation) DateFormat(java.text.DateFormat) PrintWriter(java.io.PrintWriter) HttpSession(javax.servlet.http.HttpSession) ProjectRemoteService(ca.corefacility.bioinformatics.irida.service.remote.ProjectRemoteService) ImmutableMap(com.google.common.collect.ImmutableMap) ProjectWithoutOwnerException(ca.corefacility.bioinformatics.irida.exceptions.ProjectWithoutOwnerException) IridaOAuthException(ca.corefacility.bioinformatics.irida.exceptions.IridaOAuthException) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) RemoteAPI(ca.corefacility.bioinformatics.irida.model.RemoteAPI) Page(org.springframework.data.domain.Page) ProjectSyncFrequency(ca.corefacility.bioinformatics.irida.model.project.ProjectSyncFrequency) Collectors(java.util.stream.Collectors) IridaRestApiWebConfig(ca.corefacility.bioinformatics.irida.config.web.IridaRestApiWebConfig) DateFormatter(org.springframework.format.datetime.DateFormatter) Principal(java.security.Principal) RemoteStatus(ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus) Entry(java.util.Map.Entry) User(ca.corefacility.bioinformatics.irida.model.user.User) SampleService(ca.corefacility.bioinformatics.irida.service.sample.SampleService) Authentication(org.springframework.security.core.Authentication) CSVPrinter(org.apache.commons.csv.CSVPrinter) java.util(java.util) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) Controller(org.springframework.stereotype.Controller) Join(ca.corefacility.bioinformatics.irida.model.joins.Join) Scope(org.springframework.context.annotation.Scope) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) UpdateSamplePermission(ca.corefacility.bioinformatics.irida.security.permissions.sample.UpdateSamplePermission) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) ImmutableList(com.google.common.collect.ImmutableList) Formatter(org.springframework.format.Formatter) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) TreeNode(ca.corefacility.bioinformatics.irida.util.TreeNode) MessageSource(org.springframework.context.MessageSource) OutputStream(java.io.OutputStream) RemoteAPIService(ca.corefacility.bioinformatics.irida.service.RemoteAPIService) Logger(org.slf4j.Logger) AnalysisState(ca.corefacility.bioinformatics.irida.model.enums.AnalysisState) Role(ca.corefacility.bioinformatics.irida.model.user.Role) DataTablesRequest(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.config.DataTablesRequest) CartController(ca.corefacility.bioinformatics.irida.ria.web.analysis.CartController) IridaWorkflowsService(ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Project(ca.corefacility.bioinformatics.irida.model.project.Project) HttpStatus(org.springframework.http.HttpStatus) FileSizeConverter(ca.corefacility.bioinformatics.irida.ria.utilities.converters.FileSizeConverter) ConstraintViolationException(javax.validation.ConstraintViolationException) UserService(ca.corefacility.bioinformatics.irida.service.user.UserService) XSSFSheet(org.apache.poi.xssf.usermodel.XSSFSheet) Row(org.apache.poi.ss.usermodel.Row) SyncStatus(ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus.SyncStatus) ResponseEntity(org.springframework.http.ResponseEntity) DataTablesParams(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesParams) User(ca.corefacility.bioinformatics.irida.model.user.User) Join(ca.corefacility.bioinformatics.irida.model.joins.Join) DTProject(ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTProject) DTProject(ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTProject) Project(ca.corefacility.bioinformatics.irida.model.project.Project) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 59 with Value

use of org.springframework.beans.factory.annotation.Value in project irida by phac-nml.

the class ProjectExportController method getUploadNcbiPage.

/**
 * Get the page for exporting a given {@link Project} and selected
 * {@link Sample}s
 *
 * @param projectId
 *            The ID of the project to export
 * @param sampleIds
 *            A List of sample ids to export
 * @param model
 *            model for the view to render
 * @return Name of the NCBI export page
 */
@RequestMapping(value = "/projects/{projectId}/export/ncbi", method = RequestMethod.GET)
public String getUploadNcbiPage(@PathVariable Long projectId, @RequestParam("ids[]") List<Long> sampleIds, Model model) {
    Project project = projectService.read(projectId);
    logger.trace("Reading " + sampleIds.size() + " samples");
    Iterable<Sample> samples = sampleService.readMultiple(sampleIds);
    logger.trace("Got samples");
    Set<Long> checkedSingles = new HashSet<>();
    Set<Long> checkedPairs = new HashSet<>();
    List<Map<String, Object>> sampleList = new ArrayList<>();
    for (Sample sample : samples) {
        Map<String, Object> sampleMap = new HashMap<>();
        sampleMap.put("name", sample.getLabel());
        sampleMap.put("id", sample.getId().toString());
        logger.trace("Doing sample " + sample.getId());
        Map<String, List<? extends Object>> files = new HashMap<>();
        Collection<SampleSequencingObjectJoin> singleEndFiles = sequencingObjectService.getSequencesForSampleOfType(sample, SingleEndSequenceFile.class);
        Collection<SampleSequencingObjectJoin> pairedEndFiles = sequencingObjectService.getSequencesForSampleOfType(sample, SequenceFilePair.class);
        List<SingleEndSequenceFile> singleEndFilesForSample = singleEndFiles.stream().map(j -> (SingleEndSequenceFile) j.getObject()).collect(Collectors.toList());
        List<SequenceFilePair> sequenceFilePairsForSample = pairedEndFiles.stream().map(j -> (SequenceFilePair) j.getObject()).collect(Collectors.toList());
        Optional<SequenceFilePair> newestPair = sequenceFilePairsForSample.stream().sorted((f1, f2) -> f2.getCreatedDate().compareTo(f1.getCreatedDate())).findFirst();
        Optional<SingleEndSequenceFile> newestSingle = singleEndFilesForSample.stream().sorted((f1, f2) -> f2.getCreatedDate().compareTo(f1.getCreatedDate())).findFirst();
        if (newestPair.isPresent() && newestSingle.isPresent()) {
            SequenceFilePair sequenceFilePair = newestPair.get();
            SingleEndSequenceFile join = newestSingle.get();
            if (sequenceFilePair.getCreatedDate().after(join.getCreatedDate())) {
                checkedPairs.add(newestPair.get().getId());
            } else {
                checkedSingles.add(newestSingle.get().getId());
            }
        } else {
            if (newestPair.isPresent()) {
                checkedPairs.add(newestPair.get().getId());
            } else if (newestSingle.isPresent()) {
                checkedSingles.add(newestSingle.get().getId());
            }
        }
        files.put("paired_end", sequenceFilePairsForSample);
        files.put("single_end", singleEndFilesForSample);
        sampleMap.put("files", files);
        sampleList.add(sampleMap);
    }
    sampleList.sort(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            String s1Name = (String) o1.get("name");
            String s2Name = (String) o2.get("name");
            return s1Name.compareTo(s2Name);
        }
    });
    model.addAttribute("project", project);
    model.addAttribute("samples", sampleList);
    model.addAttribute("newestSingles", checkedSingles);
    model.addAttribute("newestPairs", checkedPairs);
    model.addAttribute("instrument_model", NcbiInstrumentModel.values());
    model.addAttribute("library_selection", NcbiLibrarySelection.values());
    model.addAttribute("library_source", NcbiLibrarySource.values());
    model.addAttribute("library_strategy", NcbiLibraryStrategy.values());
    model.addAttribute("defaultNamespace", namespace);
    model.addAttribute("activeNav", "export");
    return NCBI_EXPORT_VIEW;
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Builder(ca.corefacility.bioinformatics.irida.model.export.NcbiBioSampleFiles.Builder) java.util(java.util) DTExportSubmission(ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTExportSubmission) NcbiExportSubmission(ca.corefacility.bioinformatics.irida.model.NcbiExportSubmission) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Controller(org.springframework.stereotype.Controller) ProjectService(ca.corefacility.bioinformatics.irida.service.ProjectService) Value(org.springframework.beans.factory.annotation.Value) Model(org.springframework.ui.Model) DataTablesResponseModel(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.models.DataTablesResponseModel) DataTablesResponse(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesResponse) Sort(org.springframework.data.domain.Sort) NcbiExportSubmissionService(ca.corefacility.bioinformatics.irida.service.export.NcbiExportSubmissionService) SequencingObjectService(ca.corefacility.bioinformatics.irida.service.SequencingObjectService) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) DataTablesRequest(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.config.DataTablesRequest) SequenceFilePair(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair) ca.corefacility.bioinformatics.irida.model.export(ca.corefacility.bioinformatics.irida.model.export) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) SampleSequencingObjectJoin(ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) Project(ca.corefacility.bioinformatics.irida.model.project.Project) Principal(java.security.Principal) UserService(ca.corefacility.bioinformatics.irida.service.user.UserService) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) User(ca.corefacility.bioinformatics.irida.model.user.User) SampleService(ca.corefacility.bioinformatics.irida.service.sample.SampleService) SingleEndSequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile) DataTablesParams(ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesParams) SingleEndSequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile) SequenceFilePair(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) Project(ca.corefacility.bioinformatics.irida.model.project.Project) ImmutableMap(com.google.common.collect.ImmutableMap) SampleSequencingObjectJoin(ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin)

Example 60 with Value

use of org.springframework.beans.factory.annotation.Value in project spring-security by spring-projects.

the class OAuth2ResourceServerSpecTests method getWhenUsingCustomAuthenticationManagerResolverThenUsesItAccordingly.

@Test
public void getWhenUsingCustomAuthenticationManagerResolverThenUsesItAccordingly() {
    this.spring.register(CustomAuthenticationManagerResolverConfig.class).autowire();
    ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver = this.spring.getContext().getBean(ReactiveAuthenticationManagerResolver.class);
    ReactiveAuthenticationManager authenticationManager = this.spring.getContext().getBean(ReactiveAuthenticationManager.class);
    given(authenticationManagerResolver.resolve(any(ServerWebExchange.class))).willReturn(Mono.just(authenticationManager));
    given(authenticationManager.authenticate(any(Authentication.class))).willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
    // @formatter:off
    this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus().isUnauthorized().expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
// @formatter:on
}
Also used : JwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) RSAPublicKey(java.security.interfaces.RSAPublicKey) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) MockWebServer(okhttp3.mockwebserver.MockWebServer) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) BigInteger(java.math.BigInteger) ReactiveAuthenticationManagerResolver(org.springframework.security.authentication.ReactiveAuthenticationManagerResolver) Jwt(org.springframework.security.oauth2.jwt.Jwt) HttpHeaders(org.apache.http.HttpHeaders) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) PostMapping(org.springframework.web.bind.annotation.PostMapping) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) PreDestroy(jakarta.annotation.PreDestroy) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) Stream(java.util.stream.Stream) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) MockResponse(okhttp3.mockwebserver.MockResponse) Authentication(org.springframework.security.core.Authentication) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ReactiveJwtAuthenticationConverterAdapter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) ReactiveJwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DispatcherHandler(org.springframework.web.reactive.DispatcherHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Value(org.springframework.beans.factory.annotation.Value) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) Dispatcher(okhttp3.mockwebserver.Dispatcher) BeanCreationException(org.springframework.beans.factory.BeanCreationException) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) GetMapping(org.springframework.web.bind.annotation.GetMapping) NoUniqueBeanDefinitionException(org.springframework.beans.factory.NoUniqueBeanDefinitionException) Converter(org.springframework.core.convert.converter.Converter) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) ApplicationContext(org.springframework.context.ApplicationContext) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) HttpStatusServerEntryPoint(org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint) SpringTestContext(org.springframework.security.config.test.SpringTestContext) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) HttpStatusServerAccessDeniedHandler(org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Bean(org.springframework.context.annotation.Bean) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) Authentication(org.springframework.security.core.Authentication) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Aggregations

Value (org.springframework.beans.factory.annotation.Value)77 Autowired (org.springframework.beans.factory.annotation.Autowired)36 Collectors (java.util.stream.Collectors)34 IOException (java.io.IOException)30 List (java.util.List)29 Logger (org.slf4j.Logger)23 LoggerFactory (org.slf4j.LoggerFactory)23 PathVariable (org.springframework.web.bind.annotation.PathVariable)23 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)23 ArrayList (java.util.ArrayList)21 Map (java.util.Map)21 RequestParam (org.springframework.web.bind.annotation.RequestParam)21 Optional (java.util.Optional)19 PostConstruct (javax.annotation.PostConstruct)19 RestController (org.springframework.web.bind.annotation.RestController)19 Set (java.util.Set)18 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)18 HttpStatus (org.springframework.http.HttpStatus)17 ApiOperation (io.swagger.annotations.ApiOperation)16 HttpServletResponse (javax.servlet.http.HttpServletResponse)16