Example usage for org.springframework.http HttpHeaders setLocation

List of usage examples for org.springframework.http HttpHeaders setLocation

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setLocation.

Prototype

public void setLocation(@Nullable URI location) 

Source Link

Document

Set the (new) location of a resource, as specified by the Location header.

Usage

From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json", value = "driveradd")
@ResponseStatus(HttpStatus.CREATED)//from   w w  w.j a  va2s. c  o m
@ResponseBody
public ResponseEntity<Driver> createDriver(@RequestBody Driver driver, UriComponentsBuilder builder) {

    marketPlaceController.registerDriver(driver);

    HttpHeaders headers = new HttpHeaders();

    URI newDriverLocation = builder.path("/aggregators/dvla/drivers/{license}")
            .buildAndExpand(driver.getDriversLicense()).toUri();

    LOG.info("REST CREATE DRIVER - new driver @ " + newDriverLocation.toString());

    headers.setLocation(newDriverLocation);

    Driver newDriver = marketPlaceController.getDriverDetails(driver.getDriversLicense());

    return new ResponseEntity<Driver>(newDriver, headers, HttpStatus.CREATED);
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Creates the exceuction.//from w  w w.j  a v a 2s.c  o  m
 *
 * @param request the request
 * @param startDate the start date
 * @param endDate the end date
 * @return the object
 * @throws Exception the exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/executor/executions", method = RequestMethod.POST)
public synchronized Object createExceuction(HttpServletRequest request,
        final @RequestParam(required = true) String startDate,
        final @RequestParam(required = true) String endDate,
        final @RequestParam(required = false) String valueSetDefinitions) throws Exception {
    //For now, don't validate the date. This requirement may
    //come back at some point.
    //this.dateValidator.validateDate(startDate, DateType.START);
    //this.dateValidator.validateDate(endDate, DateType.END);

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new IllegalStateException("ServletRequest expected to be of type MultipartHttpServletRequest");
    }

    final Map<String, String> valueSetDefinitionsMap = valueSetDefinitions != null
            ? new ObjectMapper().readValue(valueSetDefinitions, HashMap.class)
            : Collections.EMPTY_MAP;

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile multipartFile = multipartRequest.getFile("file");

    final String id = this.idGenerator.getId();

    final FileSystemResult result = this.fileSystemResolver.getNewFiles(id);
    FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), result.getInputQdmXml());

    String xmlFileName = multipartFile.getOriginalFilename();

    final ExecutionInfo info = new ExecutionInfo();
    info.setId(id);
    info.setStatus(Status.PROCESSING);
    info.setStart(new Date());
    info.setParameters(new Parameters(startDate, endDate, xmlFileName));

    this.fileSystemResolver.setExecutionInfo(id, info);

    this.executorService.submit(new Runnable() {

        @Override
        public void run() {
            ExecutionResult translatorResult = null;
            try {

                translatorResult = launcher.launchTranslator(IOUtils.toString(multipartFile.getInputStream()),
                        dateValidator.parse(startDate), dateValidator.parse(endDate), valueSetDefinitionsMap);

                info.setStatus(Status.COMPLETE);
                info.setFinish(new Date());
                fileSystemResolver.setExecutionInfo(id, info);

                FileUtils.writeStringToFile(result.getOuptutResultXml(), translatorResult.getXml());
            } catch (Exception e) {
                info.setStatus(Status.FAILED);
                info.setFinish(new Date());

                info.setError(ExceptionUtils.getFullStackTrace(e));
                fileSystemResolver.setExecutionInfo(id, info);

                log.warn(e);
                throw new RuntimeException(e);
            }
        }

    });

    if (this.isHtmlRequest(multipartRequest)) {
        return new ModelAndView("redirect:/executor/executions");
    } else {
        String locationUrl = "executor/execution/" + id;

        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(locationUrl));

        return new ResponseEntity(headers, HttpStatus.CREATED);
    }

}

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

/**
 * Create an Application.//from  w  ww  .ja  va2s .  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.sothawo.taboo2.Taboo2Service.java

/**
 * creates a new bookmark in the repository.
 *
 * @param bookmark//from w w w  . j a  v a 2  s. c  om
 *         new bookmark to be created
 * @param ucb
 *         uri component builder to build the created uri
 * @return the created bookmark
 * @throws IllegalArgumentException
 *         when bookmark is null or has it's id set or one of the tags is an empty string
 */
@RequestMapping(value = MAPPING_BOOKMARKS, method = RequestMethod.POST)
public final ResponseEntity<Bookmark> createBookmark(@RequestBody final Bookmark bookmark,
        final UriComponentsBuilder ucb) {
    if (null == bookmark) {
        throw new IllegalArgumentException("bookmark must not be null");
    }
    if (null != bookmark.getId()) {
        throw new IllegalArgumentException("id must not be set");
    }
    if (bookmark.getTags().stream().filter(String::isEmpty).findFirst().isPresent()) {
        throw new IllegalArgumentException("tags must not be empty");
    }

    Bookmark createdBookmark = repository.createBookmark(bookmark);
    HttpHeaders headers = new HttpHeaders();
    URI locationUri = ucb.path(MAPPING_TABOO2 + MAPPING_BOOKMARKS + '/')
            .path(String.valueOf(createdBookmark.getId())).build().toUri();
    headers.setLocation(locationUri);
    LOG.info("created bookmark {}", createdBookmark);
    return new ResponseEntity<>(createdBookmark, headers, HttpStatus.CREATED);
}

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

/**
 * Create cluster configuration./*from  w w  w .  ja v a  2 s .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:com.netflix.genie.web.controllers.CommandRestController.java

/**
 * Create a Command configuration./*from   w w  w  .  jav a  2s. co m*/
 *
 * @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:eu.supersede.gr.rest.GameRest.java

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<?> createGame(Authentication auth, @RequestBody HAHPGame game,
        @RequestParam(required = true) String criteriaValues, @RequestParam Long processId)
        throws JsonParseException, JsonMappingException, IOException {
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };/*  www. jav  a 2  s .co m*/

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Map<String, Integer>> cvs = mapper.readValue(criteriaValues, typeRef);
    game.setStartTime(new Date());
    // re-attach detached requirements
    List<Requirement> rs = game.getRequirements();

    //        if( System.currentTimeMillis() > 0 )
    //           throw new RuntimeException("");

    for (int i = 0; i < rs.size(); i++) {
        rs.set(i, requirements.findOne(rs.get(i).getRequirementId()));
    }
    // re-attach detached users
    List<User> us = game.getPlayers();

    for (int i = 0; i < us.size(); i++) {
        us.set(i, users.findOne(us.get(i).getUserId()));
    }
    // re-attach detached criterias
    List<ValutationCriteria> cs = game.getCriterias();

    for (int i = 0; i < cs.size(); i++) {
        cs.set(i, criterias.findOne(cs.get(i).getCriteriaId()));
    }

    Object user = auth.getPrincipal();

    if (user instanceof DatabaseUser) {
        DatabaseUser dbUser = (DatabaseUser) user;
        User u = users.getOne(dbUser.getUserId());
        game.setCreator(u);

        // add points for the creation of a game
        pointsLogic.addPoint(u, -3l, -1l);
    }

    if (cs.size() < 2) {
        throw new RuntimeException("Not enough criteria");
    }
    if (us.size() < 1) {
        throw new RuntimeException("Not enough players");
    }
    if (rs.size() < 2) {
        throw new RuntimeException("Not enough requirements");
    }

    game.setFinished(false);
    game = games.save(game);

    ProcessManager mgr = DMGame.get().getProcessManager(processId);
    {
        HActivity a = mgr.createActivity(AHPPlayerMethod.NAME,
                ((DatabaseUser) auth.getPrincipal()).getUserId());
        a.setUserId(null); // do this to avoid showing it in the supervisor pending activities list
        PropertyBag bag = mgr.getProperties(a);
        bag.set("gameId", "" + game.getGameId());
    }

    for (int i = 0; i < cs.size() - 1; i++) {
        for (int j = i + 1; j < cs.size(); j++) {
            HAHPCriteriasMatrixData cmd = new HAHPCriteriasMatrixData();
            cmd.setGame(game);
            cmd.setRowCriteria(cs.get(j));
            cmd.setColumnCriteria(cs.get(i));
            String c1Id = cs.get(j).getCriteriaId().toString();
            String c2Id = cs.get(i).getCriteriaId().toString();

            if (cvs.containsKey(c1Id) && cvs.get(c1Id).containsKey(c2Id)) {
                cmd.setValue(new Long(cvs.get(c1Id).get(c2Id)));
            } else {
                cmd.setValue(new Long(cvs.get(c2Id).get(c1Id)));
            }

            criteriasMatricesData.save(cmd);
        }
    }

    for (int c = 0; c < cs.size(); c++) {
        for (int i = 0; i < rs.size() - 1; i++) {
            for (int j = i + 1; j < rs.size(); j++) {
                HAHPRequirementsMatrixData rmd = new HAHPRequirementsMatrixData();
                rmd.setGame(game);
                rmd.setRowRequirement(rs.get(j));
                rmd.setColumnRequirement(rs.get(i));
                rmd.setCriteria(cs.get(c));
                rmd.setValue(-1l);
                requirementsMatricesData.save(rmd);

                for (int p = 0; p < us.size(); p++) {
                    HAHPPlayerMove pm = new HAHPPlayerMove();
                    pm.setPlayer(us.get(p));
                    pm.setRequirementsMatrixData(rmd);
                    pm.setPlayed(false);
                    playerMoves.save(pm);
                }

                HAHPJudgeAct ja = new HAHPJudgeAct();
                ja.setVoted(false);
                ja.setRequirementsMatrixData(rmd);
                judgeActs.save(ja);
            }
        }
    }

    DatabaseUser currentUser = (DatabaseUser) auth.getPrincipal();

    for (User u : us) {
        eu.supersede.integration.api.datastore.fe.types.User proxyUser = proxy.getFEDataStoreProxy()
                .getUser(currentUser.getTenantId(), u.getUserId().intValue(), true, currentUser.getToken());
        // creation of email for the players when a game is started
        supersedeMailSender.sendEmail("New Decision Making Process",
                "Hi " + proxyUser.getFirst_name() + " " + proxyUser.getLast_name()
                        + ", this is an automatically generated mail. You have just been invited to "
                        + "participate in a prioritization process.",
                proxyUser.getEmail());

        notificationUtil.createNotificationForUser(proxyUser.getEmail(),
                "A new decision making process has been created, are you ready to vote?",
                "supersede-dm-app/ahprp/player_games");

        // create a GamePlayerPoint for this game and for all the players in the game
        HAHPGamePlayerPoint gpp = new HAHPGamePlayerPoint();
        gpp.setGame(game);
        gpp.setUser(u);
        gpp.setPoints(0l);
        gamesPlayersPoints.save(gpp);

        HActivity a = mgr.createActivity(AHPPlayerMethod.NAME, u.getUserId());
        PropertyBag bag = mgr.getProperties(a);
        bag.set("gameId", "" + game.getGameId());
    }

    // FIXME
    //        notificationUtil.createNotificationsForProfile("OPINION_NEGOTIATOR",
    //                "A new decision making process has been created, you are in charge to take decisions",
    //                "supersede-dm-app/ahprp/judge_games");

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

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates/{templateid}", method = RequestMethod.PUT)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> updateTemplateById(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "informat", required=false) String
        // informat,
        // @RequestParam(value = "f", required=false) String f,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        @RequestParam(value = "owner", required = false) String ownerName,
        @PathVariable("templateid") long templateId, @RequestParam Map<String, String> allParams,
        @RequestBody String postBody) {

    try {//  w  ww.j  av a2  s .  c om
        // NOTE: informat was defaulted to JSON before! Now it is TURTLE.
        // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*"
        // and informat==null, otherwise to JSON. Now it is TURTLE.
        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                true);

        // validateTemplateID(templateId);
        // check read access
        Template template = templateDAO.findOneById(templateId);

        // Was the nif-input empty?
        if (nifParameters.getInput() != null) {
            if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) {
                JSONObject jsonObj = new JSONObject(nifParameters.getInput());
                template.update(jsonObj);
            } else {
                Model model = rdfConversionService.unserializeRDF(nifParameters.getInput(),
                        nifParameters.getInformat());
                template.setTemplateWithModel(model);
            }
        }

        template = templateDAO.save(template);

        if (!Strings.isNullOrEmpty(ownerName)) {
            User owner = userDAO.getRepository().findOneByName(ownerName);
            if (owner == null)
                throw new BadRequestException(
                        "Can not change owner of the template. User \"" + ownerName + "\" does not exist.");
            template = templateDAO.updateOwner(template, owner);
        }

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        URI location = new URI("/e-link/templates/" + template.getId());
        responseHeaders.setLocation(location);
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (URISyntaxException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException();
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (OwnedResourceNotFoundException ex) {
        logger.error(ex.getMessage(), ex);
        throw new TemplateNotFoundException("Template not found. " + ex.getMessage());
    } catch (org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(
                "The JSON object is incorrectly formatted. Problem description: " + ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
    throw new InternalServerErrorException("Unknown problem. Please contact us.");
}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/templates", method = RequestMethod.POST)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> createTemplate(
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        // @RequestParam(value = "informat", required=false) String
        // informat,
        // @RequestParam(value = "f", required=false) String f,
        // @RequestParam(value = "outformat", required=false) String
        // outformat,
        // @RequestParam(value = "o", required=false) String o,
        // Type was moved as endpoint-type field of the template.
        // @RequestParam(value = "visibility", required=false) String
        // visibility,
        // Type was moved as endpoint-type field of the template.
        // @RequestParam(value = "type", required=false) String type,
        @RequestParam Map<String, String> allParams, @RequestBody String postBody) {

    try {// w w  w. j a v  a  2s  .co  m

        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                false);

        // NOTE: informat was defaulted to JSON before! Now it is TURTLE.
        // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*"
        // and informat==null, otherwise to JSON. Now it is TURTLE.
        // NOTE: switched back to JSON since we use MySQL and RDF is no
        // longer supported, but JSON only.
        nifParameters.setInformat(RDFSerialization.JSON);
        nifParameters.setOutformat(RDFSerialization.JSON);

        Template template;
        if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) {
            JSONObject jsonObj = new JSONObject(nifParameters.getInput());
            templateValidator.validateTemplateEndpoint(jsonObj.getString("endpoint"));

            // AccessDeniedException can be thrown, if current
            // authentication is the anonymousUser
            template = new Template(jsonObj);
        } else {
            throw new BadRequestException("Other formats then JSON are no longer supported for templates.");
            // Model model =
            // rdfConversionService.unserializeRDF(nifParameters.getInput(),
            // nifParameters.getInformat());
            // template = new Template(
            // OwnedResource.Visibility.getByString(visibility),
            // Template.Type.getByString(jsonObj.getString("endpoint-type")),
            // model);
            // templateValidator.validateTemplateEndpoint(template.getEndpoint());
        }

        template = templateDAO.save(template);

        String serialization;
        if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) {
            ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
            serialization = ow.writeValueAsString(template);
        } else {
            // Should never fail to.
            serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat());
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        URI location = new URI("/e-link/templates/" + template.getId());
        responseHeaders.setLocation(location);
        responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType());
        // String serialization =
        // rdfConversionService.serializeRDF(template.getRDF(),
        // nifParameters.getOutformat());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException(ex.getMessage());
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (URISyntaxException | org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(ex.getMessage());
    } catch (InvalidTemplateEndpointException ex) {
        logger.error(ex.getMessage(), ex);
        throw new InvalidTemplateEndpointException(ex.getMessage());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new InternalServerErrorException(ex.getMessage());
    }
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.ApplicationResource.java

@RequestMapping(value = Routes.APPLICATIONS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@RolesAllowed({ AuthoritiesConstants.USER, AuthoritiesConstants.STAFF, AuthoritiesConstants.ADMIN })
@Timed/*w w  w  .j  a  va 2 s . co  m*/
public ResponseEntity<Application> createApplication(@RequestBody CreateApplicationDTO requestBody) {
    authorizationChecker.checkCanCreateApplication(requestBody);

    // FIXME MLDS-308 it is an error to try to create an extension application without a target member.
    Member member = (requestBody.getMemberKey() != null)
            ? memberRepository.findOneByKey(requestBody.getMemberKey())
            : userMembershipAccessor.getMemberAssociatedWithUser();

    Application application = applicationService.startNewApplication(requestBody.getApplicationType(), member);

    applicationAuditEvents.logCreationOf(application);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(routeLinkBuilder.toURLWithKeyValues(Routes.APPLICATION, "applicationId",
            application.getApplicationId()));
    ResponseEntity<Application> result = new ResponseEntity<Application>(application, headers,
            HttpStatus.CREATED);
    return result;
}