Example usage for org.springframework.util MultiValueMap getFirst

List of usage examples for org.springframework.util MultiValueMap getFirst

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap getFirst.

Prototype

@Nullable
V getFirst(K key);

Source Link

Document

Return the first value for the given key.

Usage

From source file:com.smallpay.workflow.service.api.model.ModelSaveRestResource.java

@RequestMapping(value = "/service/model/{modelId}/save", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseStatus(value = HttpStatus.OK)// w  w w .j a va  2  s.  c o  m
public void saveModel(@PathVariable String modelId, @RequestParam MultiValueMap<String, String> values) {
    try {

        Model model = repositoryService.getModel(modelId);

        ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

        modelJson.put(MODEL_NAME, values.getFirst("name"));
        modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
        model.setMetaInfo(modelJson.toString());
        model.setName(values.getFirst("name"));

        repositoryService.saveModel(model);

        repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes("utf-8"));

        InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
        TranscoderInput input = new TranscoderInput(svgStream);

        PNGTranscoder transcoder = new PNGTranscoder();
        // Setup output
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(outStream);

        // Do the transformation
        transcoder.transcode(input, output);
        final byte[] result = outStream.toByteArray();
        repositoryService.addModelEditorSourceExtra(model.getId(), result);
        outStream.close();

    } catch (Exception e) {
        LOGGER.error("Error saving model", e);
        throw new ActivitiException("Error saving model", e);
    }
}

From source file:org.pf9.pangu.app.act.rest.editor.model.ModelSaveRestResource.java

@RequiresPermissions("act:model:edit")
@RequestMapping(value = "/act/service/model/{modelId}/save", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)/*ww  w  .j  a v  a  2s.  c o m*/
public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
    try {

        Model model = repositoryService.getModel(modelId);

        ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

        modelJson.put(MODEL_NAME, values.getFirst("name"));
        modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
        model.setMetaInfo(modelJson.toString());
        model.setName(values.getFirst("name"));

        repositoryService.saveModel(model);

        repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes("utf-8"));

        InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
        TranscoderInput input = new TranscoderInput(svgStream);

        PNGTranscoder transcoder = new PNGTranscoder();
        // Setup output
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(outStream);

        // Do the transformation
        transcoder.transcode(input, output);
        final byte[] result = outStream.toByteArray();
        repositoryService.addModelEditorSourceExtra(model.getId(), result);
        outStream.close();

    } catch (Exception e) {
        LOGGER.error("Error saving model", e);
        throw new ActivitiException("Error saving model", e);
    }
}

From source file:info.joseluismartin.gtc.WmsCache.java

/**
 * {@inheritDoc}//from w  w w.  ja va  2 s .  c  om
 * @throws IOException 
 */
@Override
public InputStream parseResponse(InputStream serverStream, String remoteUri, String localUri)
        throws IOException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(remoteUri);
    UriComponents remoteComponents = builder.build();
    String localUrl = localUri + "/" + getPath();

    InputStream is = serverStream;
    MultiValueMap<String, String> params = remoteComponents.getQueryParams();

    if (GET_CAPABILITIES.equals(params.getFirst(REQUEST))) {
        String response = IOUtils.toString(serverStream);

        Document doc = XMLUtils.newDocument(response);

        if (log.isDebugEnabled())
            XMLUtils.prettyDocumentToString(doc);

        // Fix GetMapUrl
        Element getMapElement = (Element) doc.getElementsByTagName(GET_MAP).item(0);
        if (getMapElement != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found GetMapUrl: " + this.getMapUrl);
            }

            NodeList nl = getMapElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT);
            if (nl.getLength() > 0) {
                Element resource = (Element) nl.item(0);
                if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) {
                    this.getMapUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", "");
                    resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl);
                }
            }
        }

        // Fix GetFeatureInfoUrl
        Element getFeatureElement = (Element) doc.getElementsByTagName(GET_FEATURE_INFO).item(0);
        if (getFeatureElement != null) {
            if (log.isDebugEnabled()) {
                log.debug("Found GetFeatureInfoUrl: " + this.getFeatureInfoUrl);
            }

            NodeList nl = getFeatureElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT);
            if (nl.getLength() > 0) {
                Element resource = (Element) nl.item(0);
                if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) {
                    this.getFeatureInfoUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", "");
                    resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl);
                }
            }
        }

        response = XMLUtils.documentToString(doc);
        response = response.replaceAll(getServerUrl(), localUrl);
        //   response = "<?xml version='1.0' encoding='UTF-8'>" + response; 

        is = IOUtils.toInputStream(response);
    }

    return is;
}

From source file:puma.application.evaluation.AdvancedDocumentController.java

/**
* Creates an document with the given attributes. Retrus the identifier of the document
* @param params All attributes of the document. 'name', 'date' (in long format), 'tenant'
* @return Identifier of the created document
*//*ww w.j  av  a  2  s .c om*/
@ResponseBody
@RequestMapping(value = "/createDocument", method = RequestMethod.GET)
public String createDocument(@RequestParam MultiValueMap<String, String> params) {
    Document doc = new Document();
    if (params.containsKey("tenant"))
        doc.setCreatingTenant(params.getFirst("tenant"));
    if (params.containsKey("name"))
        doc.setName(params.getFirst("name"));
    if (params.containsKey("origin"))
        doc.setOrigin(params.getFirst("origin"));
    if (params.containsKey("destination"))
        doc.setDestination(params.getFirst("destination"));
    if (params.containsKey("date"))
        doc.setDate(new Date(Long.parseLong(params.getFirst("date"))));
    this.docService.addDocument(doc);
    return doc.getId().toString();
}

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testDefaultScopes() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/oauth/authorize", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();/*w  ww. j  a v a2 s  .  c  o m*/
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:io.syndesis.runtime.credential.CredentialITCase.java

@Test
public void shouldInitiateCredentialFlow() throws UnsupportedEncodingException {
    final ResponseEntity<AcquisitionResponse> acquisitionResponse = post(
            "/api/v1/connectors/test-provider/credentials", Collections.singletonMap("returnUrl", "/ui#state"),
            AcquisitionResponse.class, tokenRule.validToken(), HttpStatus.ACCEPTED);

    assertThat(acquisitionResponse.hasBody()).as("Should present a acquisition response in the HTTP body")
            .isTrue();/*from  w w  w. ja  va2s.co  m*/

    final AcquisitionResponse response = acquisitionResponse.getBody();
    assertThat(response.getType()).isEqualTo(Type.OAUTH2);

    final String redirectUrl = response.getRedirectUrl();
    assertThat(redirectUrl).as("Should redirect to Salesforce and containthe correct callback URL")
            .startsWith("https://test/oauth2/authorize?client_id=testClientId&response_type=code&redirect_uri=")
            .contains(encode("/api/v1/credentials/callback", "ASCII"));

    final MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(redirectUrl).build()
            .getQueryParams();

    final String state = params.getFirst("state");

    assertThat(state).as("state parameter should be set").isNotEmpty();

    final State responseStateInstruction = response.state();
    assertThat(responseStateInstruction).as("acquisition response should contain the state instruction")
            .isNotNull();
    assertThat(responseStateInstruction.persist()).isEqualByComparingTo(State.Persist.COOKIE);
    assertThat(responseStateInstruction.spec()).isNotEmpty();

    final CredentialFlowState credentialFlowState = clientSideState
            .restoreFrom(Cookie.valueOf(responseStateInstruction.spec()), CredentialFlowState.class);

    final CredentialFlowState expected = new OAuth2CredentialFlowState.Builder().key("test-state")
            .providerId("test-provider").build();

    assertThat(credentialFlowState).as("The flow state should be as expected")
            .isEqualToIgnoringGivenFields(expected, "returnUrl");
    final URI returnUrl = credentialFlowState.getReturnUrl();
    assertThat(returnUrl).isNotNull();
    assertThat(returnUrl.isAbsolute()).isTrue();
    assertThat(returnUrl.getPath()).isEqualTo("/ui");
    assertThat(returnUrl.getFragment()).isEqualTo("state");
}

From source file:org.hekmatof.activiti.editor.ModelSaveRestResource.java

@RequestMapping(value = "/model/{modelId}/save", method = RequestMethod.PUT)
public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
    try {//from   w ww.  j  ava  2  s  . c  o m

        Model model = repositoryService.getModel(modelId);

        ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

        modelJson.put(MODEL_NAME, values.getFirst("name"));
        modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
        model.setMetaInfo(modelJson.toString());
        model.setName(values.getFirst("name"));

        repositoryService.saveModel(model);

        repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes("utf-8"));

        InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
        TranscoderInput input = new TranscoderInput(svgStream);

        PNGTranscoder transcoder = new PNGTranscoder();
        // Setup output
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        TranscoderOutput output = new TranscoderOutput(outStream);

        // Do the transformation
        transcoder.transcode(input, output);
        final byte[] result = outStream.toByteArray();
        repositoryService.addModelEditorSourceExtra(model.getId(), result);
        outStream.close();

    } catch (Exception e) {
        logger.error("Error saving model", e);
        throw new ActivitiException("Error saving model", e);
    }
}

From source file:org.jutge.joc.porra.controller.desktop.DesktopSignupController.java

@ReCaptchaConsumer
@EntityStashManaged//www  . ja v  a 2s.co m
@RequestMapping(value = "/apuntar-se", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.TEXT_HTML_VALUE)
public String signupPost(@RequestBody final MultiValueMap<String, String> dataMap, final Locale locale,
        final HttpServletRequest request) {
    this.logger.info("DesktopSignupController.signupPost");
    // handle params
    final String name = dataMap.getFirst("usr");
    final String email = dataMap.getFirst("mil");
    request.setAttribute("usr", name);
    request.setAttribute("mil", email);
    final Boolean validRecaptcha = (Boolean) request.getAttribute(ReCaptchaUtils.RECAPTCHA_IS_VALID);
    this.validateSignupParams(name, email, validRecaptcha, locale);
    // try saving new account
    final Account account = new Account();
    account.setName(name.trim());
    account.setEmail(email.trim());
    this.accountService.createAccount(account);
    this.emailService.sendActivationMail(account);
    return "/desktop/signup/signup-done";
}

From source file:puma.application.evaluation.AdvancedDocumentController.java

private String access(Action action, MultiValueMap<String, String> params, Environment environment) {
    if (!params.containsKey("user") || !params.containsKey("document")) {
        throw new IllegalArgumentException("Provide at least user and document ids");
    }//from  ww w.j a va 2 s .  c  o m
    User u = this.userService.byId(Long.parseLong(params.getFirst("user")));
    if (u == null)
        throw new IllegalArgumentException("Could not find user with specified id~!");
    Subject subject = new Subject(u.getId().toString());
    for (Attribute next : u.getAttributes())
        if (next.getFamily().getRetrievalStrategy().equals(RetrievalStrategy.PUSH))
            addAttribute(subject, next.getFamily().getXacmlIdentifier(), next.getValue());
    Document doc = this.docService.getDocumentById(Long.parseLong(params.getFirst("document")));
    if (doc == null)
        throw new IllegalArgumentException("Could not find document with specified id~!");
    params.remove("document");
    params.remove("user");
    puma.peputils.Object object = constructAuthzObject(doc, params);
    Boolean decision = ApplicationPEP.getInstance().isAuthorized(subject, object, action, environment);
    return decision.toString();
}

From source file:org.jutge.joc.porra.controller.desktop.DesktopSignupController.java

@ReCaptchaConsumer
@EntityStashManaged//from w w w . j a v  a2  s  .  c  om
@RequestMapping(value = "/nova-clau", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.TEXT_HTML_VALUE)
public String resetPassPost(@RequestBody final MultiValueMap<String, String> dataMap, final Model model,
        final HttpServletRequest request, final Locale locale) {
    this.logger.info("DesktopSignupController.resetPassPost");
    // validation first
    final String name = dataMap.getFirst("usr");
    final String email = dataMap.getFirst("mil");
    request.setAttribute("usr", name);
    request.setAttribute("mil", email);
    final Boolean recaptchaIsValid = (Boolean) request.getAttribute(ReCaptchaUtils.RECAPTCHA_IS_VALID);
    final Account account = validateResetPassParams(name, email, recaptchaIsValid, locale);
    // Do actual reset
    this.accountService.resetAccount(account);
    this.emailService.sendPasswordResetMail(account);
    return "/desktop/signup/reset-done";
}