Example usage for org.springframework.web.servlet.support ServletUriComponentsBuilder fromCurrentRequest

List of usage examples for org.springframework.web.servlet.support ServletUriComponentsBuilder fromCurrentRequest

Introduction

In this page you can find the example usage for org.springframework.web.servlet.support ServletUriComponentsBuilder fromCurrentRequest.

Prototype

public static ServletUriComponentsBuilder fromCurrentRequest() 

Source Link

Document

Same as #fromRequest(HttpServletRequest) except the request is obtained through RequestContextHolder .

Usage

From source file:org.moserp.infrastructure.gateway.filter.ResponseLinksMapper.java

Object fixLink(Object value) {
    if (!(value instanceof String)) {
        return value;
    }//from w ww .  j  a  v a2  s . com
    String href = (String) value;
    Matcher urlWithServiceNameMatcher = urlWithServiceNamePattern.matcher(href);
    Matcher standardUrlMatcher = standardUrlPattern.matcher(href);
    if (!standardUrlMatcher.matches() && urlWithServiceNameMatcher.matches()) {
        String possibleServiceName = urlWithServiceNameMatcher.group(1);
        log.debug("Possible service name: " + possibleServiceName);
        if (services.contains(possibleServiceName)) {
            log.debug("Service found");
            String gatewayPath = serviceRouteMapper.apply(possibleServiceName);
            String originalRestPath = urlWithServiceNameMatcher.group(2);
            ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder
                    .fromCurrentRequest();
            UriComponents uriComponents = servletUriComponentsBuilder.replacePath(gatewayPath)
                    .path(originalRestPath).build();
            log.debug("Mapping " + value + " to " + uriComponents);
            return uriComponents.toString();
        }
    }
    return href;
}

From source file:ch.wisv.areafiftylan.teams.controller.TeamRestController.java

/**
 * The method to handle POST requests on the /teams endpoint. This creates a new team. Users can only create new
 * Teams with themselves as Captain. Admins can also create Teams with other Users as Captain.
 *
 * @param teamDTO Object containing the Team name and Captain username. When coming from a user, username should
 *                equal their own username.
 * @param auth    Authentication object from Spring Security
 *
 * @return Return status message of the operation
 *//*ww w.  j a  va2 s  .c om*/
@PreAuthorize("isAuthenticated() and @currentUserServiceImpl.hasAnyTicket(principal)")
@JsonView(View.Public.class)
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> add(@Validated @RequestBody TeamDTO teamDTO, Authentication auth) {
    if (teamService.teamnameUsed(teamDTO.getTeamName())) {
        return createResponseEntity(HttpStatus.CONFLICT,
                "Team with name \"" + teamDTO.getTeamName() + "\" already exists.");
    }

    Team team;
    // Users can only create teams with themselves as Captain
    if (auth.getAuthorities().contains(Role.ROLE_ADMIN)) {
        team = teamService.create(teamDTO.getCaptainUsername(), teamDTO.getTeamName());
    } else {
        // If the DTO contains another username as the the current user, return an error.
        if (!auth.getName().equalsIgnoreCase(teamDTO.getCaptainUsername())) {
            return createResponseEntity(HttpStatus.BAD_REQUEST,
                    "Can not create team with another user as Captain");
        }
        team = teamService.create(auth.getName(), teamDTO.getTeamName());
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(team.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, httpHeaders,
            "Team successfully created at " + httpHeaders.getLocation(), team);
}

From source file:com.netflix.genie.web.controllers.ApplicationRestController.java

/**
 * Create an Application.//from  w w w  .  ja  va  2  s  .c om
 *
 * @param app The application to create
 * @return The created application configuration
 * @throws GenieException For any error
 */
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> createApplication(@RequestBody final Application app) throws GenieException {
    log.debug("Called to create new application");
    final String id = this.applicationService.createApplication(app);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri());
    return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}

From source file:com.netflix.genie.web.controllers.ClusterRestController.java

/**
 * Create cluster configuration./*w w  w  .  ja v  a  2s .  c o  m*/
 *
 * @param cluster contains the cluster information to create
 * @return The created cluster
 * @throws GenieException For any error
 */
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> createCluster(@RequestBody final Cluster cluster) throws GenieException {
    log.debug("Called to create new cluster {}", cluster);
    final String id = this.clusterService.createCluster(cluster);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri());
    return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}

From source file:eu.supersede.dm.rest.RequirementRest.java

/**
 * Create a new requirement.//from  w w w.  j  ava2  s  . com
 * 
 * @param r
 */
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createRequirement(@RequestBody Requirement r) {
    r.setRequirementId(null);
    DMGame.get().getJpa().requirements.save(r);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(r.getRequirementId()).toUri());
    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}

From source file:com.gazbert.bxbot.rest.api.StrategyConfigController.java

/**
 * Creates a new Strategy configuration.
 *
 * @param user the authenticated user.//  w  w w  .jav  a 2 s .  c om
 * @param strategyId id of the Strategy config to create.
 * @param config the new Strategy config.
 * @return 201 'Created' HTTP status code if create successful, 409 'Conflict' HTTP status code if Strategy config already exists.
 */
@RequestMapping(value = "/strategy/{strategyId}", method = RequestMethod.POST)
ResponseEntity<?> createStrategy(@AuthenticationPrincipal User user, @PathVariable String strategyId,
        @RequestBody StrategyConfig config) {

    if (config == null || config.getId() == null || !strategyId.equals(config.getId())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    final StrategyConfig createdConfig = strategyConfigService.createStrategy(config);
    if (createdConfig.getId() != null) {
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{strategyId}")
                .buildAndExpand(createdConfig.getId()).toUri());
        return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);

    } else {
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }
}

From source file:com.netflix.genie.web.controllers.CommandRestController.java

/**
 * Create a Command configuration./*ww  w.j a  v a  2s. com*/
 *
 * @param command The command configuration to create
 * @return The command created
 * @throws GenieException For any error
 */
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Void> createCommand(@RequestBody final Command command) throws GenieException {
    log.debug("called to create new command configuration {}", command);
    final String id = this.commandService.createCommand(command);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri());
    return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}

From source file:org.appverse.web.framework.backend.frontfacade.mvc.swagger.provider.EurekaSwaggerResourcesProvider.java

public List<SwaggerResource> get() {
    List<SwaggerResource> resources = new ArrayList<SwaggerResource>();
    if (discoveryClient != null) {
        //eureka discovery cliend found
        List<String> services = discoveryClient.getServices();
        if (services != null && !services.isEmpty()) {
            //there are some services
            UriComponents current = null;
            if (swaggerHost == null || swaggerHost.length() == 0) {
                //obtain current uri from request
                current = ServletUriComponentsBuilder.fromCurrentRequest().build();
            }//w ww . j  a  va  2  s.  com
            for (String service : services) {
                if (eurekaSkipServices != null && eurekaSkipServices.size() != 0) {
                    if (eurekaSkipServices.contains(service)) {
                        continue;
                    }

                }
                List<ServiceInstance> instances = discoveryClient.getInstances(service);
                if (instances.size() != 0) {
                    ServiceInstance instance = instances.get(0);
                    //filters metadata called swagger
                    if (!metadataFilter || instance.getMetadata().containsKey("swagger")) {
                        String urlLocation = obtainUrlLocation(instance, current, baseSwaggerDefaultUrl,
                                swaggerHost);
                        resources.add(createResource(service, urlLocation, baseSwaggerDefaultVersion));
                    }
                }

            }
        }
    } else {
        //return default swagger group
        resources.add(
                createResource(baseSwaggerDefaultGroup, baseSwaggerDefaultGroup, baseSwaggerDefaultVersion));
    }
    Collections.sort(resources);
    return resources;

}

From source file:com.netflix.genie.web.controllers.JobRestController.java

private ResponseEntity<Void> handleSubmitJob(final JobRequest jobRequest, final MultipartFile[] attachments,
        final String clientHost, final String userAgent, final HttpServletRequest httpServletRequest)
        throws GenieException {
    if (jobRequest == null) {
        throw new GeniePreconditionException("No job request entered. Unable to submit.");
    }/*from   ww  w .  j ava  2 s  . co m*/

    // get client's host from the context
    final String localClientHost;
    if (StringUtils.isNotBlank(clientHost)) {
        localClientHost = clientHost.split(",")[0];
    } else {
        localClientHost = httpServletRequest.getRemoteAddr();
    }

    final JobRequest jobRequestWithId;
    // If the job request does not contain an id create one else use the one provided.
    final String jobId;
    final Optional<String> jobIdOptional = jobRequest.getId();
    if (jobIdOptional.isPresent() && StringUtils.isNotBlank(jobIdOptional.get())) {
        jobId = jobIdOptional.get();
        jobRequestWithId = jobRequest;
    } else {
        jobId = UUID.randomUUID().toString();
        final JobRequest.Builder builder = new JobRequest.Builder(jobRequest.getName(), jobRequest.getUser(),
                jobRequest.getVersion(), jobRequest.getCommandArgs(), jobRequest.getClusterCriterias(),
                jobRequest.getCommandCriteria()).withId(jobId)
                        .withDisableLogArchival(jobRequest.isDisableLogArchival())
                        .withTags(jobRequest.getTags()).withDependencies(jobRequest.getDependencies())
                        .withApplications(jobRequest.getApplications());

        jobRequest.getCpu().ifPresent(builder::withCpu);
        jobRequest.getMemory().ifPresent(builder::withMemory);
        jobRequest.getGroup().ifPresent(builder::withGroup);
        jobRequest.getSetupFile().ifPresent(builder::withSetupFile);
        jobRequest.getDescription().ifPresent(builder::withDescription);
        jobRequest.getEmail().ifPresent(builder::withEmail);
        jobRequest.getTimeout().ifPresent(builder::withTimeout);

        jobRequestWithId = builder.build();
    }

    // Download attachments
    int numAttachments = 0;
    long totalSizeOfAttachments = 0L;
    if (attachments != null) {
        log.info("Saving attachments for job {}", jobId);
        numAttachments = attachments.length;
        for (final MultipartFile attachment : attachments) {
            totalSizeOfAttachments += attachment.getSize();
            log.debug("Attachment name: {} Size: {}", attachment.getOriginalFilename(), attachment.getSize());
            try {
                this.attachmentService.save(jobId, attachment.getOriginalFilename(),
                        attachment.getInputStream());
            } catch (final IOException ioe) {
                throw new GenieServerException(ioe);
            }
        }
    }

    final JobMetadata metadata = new JobMetadata.Builder().withClientHost(localClientHost)
            .withUserAgent(userAgent).withNumAttachments(numAttachments)
            .withTotalSizeOfAttachments(totalSizeOfAttachments).build();

    this.jobCoordinatorService.coordinateJob(jobRequestWithId, metadata);

    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(
            ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(jobId).toUri());

    return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED);
}