Example usage for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

Introduction

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

Prototype

public LinkedMultiValueMap(Map<K, List<V>> otherMap) 

Source Link

Document

Copy constructor: Create a new LinkedMultiValueMap with the same mappings as the specified Map.

Usage

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest(
        UploadApplicationPayload application, CloudResources knownRemoteResources) throws IOException {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2);
    body.add("application", application);
    ObjectMapper mapper = new ObjectMapper();
    String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
    body.add("resources", knownRemoteResourcesPayload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return new HttpEntity<MultiValueMap<String, ?>>(body, headers);
}

From source file:io.lavagna.web.security.HSTSFilter.java

private static void sendRedirectAbsolute(String baseApplicationUrl, HttpServletResponse resp, String page,
        Map<String, List<String>> params) throws IOException {
    UriComponents urlToRedirect = UriComponentsBuilder.fromHttpUrl(baseApplicationUrl).path(page)
            .queryParams(new LinkedMultiValueMap<>(params)).build();
    resp.sendRedirect(urlToRedirect.toUriString());
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;//  ww w .j  av  a 2s  .  c  om
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        if (!addNew) {
            throw new LoginSAMLException("SAML user does not exist. "
                    + "You can correct this by creating a shadow user for the SAML user.", e);
        }
        // Register new users automatically
        publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
        try {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException(
                    "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;//w w w  . ja v  a  2s  . c o  m
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        UaaUser uaaUser = userDatabase.retrieveUserByEmail(userWithSamlAttributes.getEmail(),
                samlPrincipal.getOrigin());
        if (uaaUser != null) {
            user = uaaUser.modifyUsername(samlPrincipal.getName());
        } else {
            if (!addNew) {
                throw new LoginSAMLException("SAML user does not exist. "
                        + "You can correct this by creating a shadow user for the SAML user.", e);
            }
            // Register new users automatically
            publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
            try {
                user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
            } catch (UsernameNotFoundException ex) {
                throw new BadCredentialsException(
                        "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
            }
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Upload a file to the Genologics file store. This always uses the HTTP
 * protocol with the {@code file/id/upload} end point.
 *
 * @param fileURLResource The URL resource of the file on the local machine.
 * @param targetFile The GenologicsFile object that holds the reference to the
 * uploaded file, which was newly created using the API.
 *
 * @throws GenologicsException if the server reports a problem with the upload.
 * @throws IllegalStateException if {@code targetFile} does not have a LIMS id.
 * @throws IOException if there is a problem with the transfer.
 *///from   w  w w  .j a  v  a  2  s  .c  o  m
protected void uploadViaHTTP(URLInputStreamResource fileURLResource, GenologicsFile targetFile)
        throws IOException {
    GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class);

    if (targetFile.getLimsid() == null) {
        // Need to post the file back to the LIMS to obtain a URI and LIMS
        // id for the file object.

        String filesUrl = getServerApiAddress() + entityAnno.uriSection();

        ResponseEntity<GenologicsFile> response = restClient.postForEntity(filesUrl, targetFile,
                GenologicsFile.class);

        reflectiveUpdate(targetFile, response.getBody());

        assert targetFile.getLimsid() != null : "Still no LIMS id on GenologicsFile object.";
    }

    boolean uploadedOk = false;
    try {
        URI uploadURI;
        try {
            uploadURI = new URI(
                    getServerApiAddress() + entityAnno.uriSection() + "/" + targetFile.getLimsid() + "/upload");
        } catch (URISyntaxException e) {
            throw new IOException(
                    "File LIMS id " + targetFile.getLimsid() + " produces an invalid URI for upload.", e);
        }

        logger.info("Uploading {} over {} to {} on {}", fileURLResource.getURL().getPath(),
                uploadURI.getScheme().toUpperCase(), targetFile.getContentLocation().getPath(),
                targetFile.getContentLocation().getHost());

        HttpEntity<MultiValueMap<String, Resource>> requestEntity = new HttpEntity<MultiValueMap<String, Resource>>(
                new LinkedMultiValueMap<String, Resource>(1));

        requestEntity.getBody().add("file", fileURLResource);

        ResponseEntity<String> uploadEntity = fileUploadClient.exchange(uploadURI, HttpMethod.POST,
                requestEntity, String.class);

        uploadedOk = true;

        if (logger.isDebugEnabled()) {
            if (uploadEntity.hasBody()) {
                logger.debug("Upload of file returned a {}: {}",
                        ClassUtils.getShortClassName(uploadEntity.getBody().getClass()),
                        uploadEntity.getBody());
            } else {
                logger.debug("Upload of file succeeded but returned nothing.");
            }
        }
    } finally {
        if (!uploadedOk) {
            try {
                delete(targetFile);
            } catch (Exception e) {
                logger.warn("Failed to clean up GenologicsFile object {} after upload failure:",
                        targetFile.getLimsid(), e);
            }
        }
    }

    if (!uploadedOk) {
        // I don't think the code can get here as other exceptions should
        // have been thrown. To make sure though...

        throw new GenologicsUpdateException("Failed to upload " + fileURLResource.getURL());
    }
}

From source file:org.dspace.app.rest.utils.RestRepositoryUtils.java

public Object executeQueryMethod(DSpaceRestRepository repository, MultiValueMap<String, Object> parameters,
        Method method, Pageable pageable, Sort sort, PagedResourcesAssembler assembler) {

    MultiValueMap<String, Object> result = new LinkedMultiValueMap<String, Object>(parameters);
    MethodParameters methodParameters = new MethodParameters(method, new AnnotationAttribute(Param.class));

    for (Entry<String, List<Object>> entry : parameters.entrySet()) {

        MethodParameter parameter = methodParameters.getParameter(entry.getKey());

        if (parameter == null) {
            continue;
        }/*w ww . ja v  a 2  s  . co  m*/

        result.put(parameter.getParameterName(), entry.getValue());
    }

    return invokeQueryMethod(repository, method, result, pageable, sort);
}

From source file:org.encuestame.social.api.templates.FacebookAPITemplate.java

public TweetPublishedMetadata publish(String object, String connection, MultiValueMap<String, String> data) {
    final MultiValueMap<String, String> requestData = new LinkedMultiValueMap<String, String>(data);
    log.debug("before facebookResponse:{" + requestData);
    final Map facebookResponse = getRestTemplate().postForObject(CONNECTION_URL, requestData, Map.class, object,
            connection);/*ww w  .  j av  a  2s  .com*/
    log.debug("facebookResponse:{" + facebookResponse);
    final TweetPublishedMetadata status = createStatus(data.get("message").toString());
    status.setTweetId(facebookResponse.get("id").toString());
    return status;
}

From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java

private Integer putZipAsURL(String zip) throws Exception {
    MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", "");
    assertEquals(201, resp.getStatus());
    assertNotNull(resp.getHeader("Location"));

    String[] split = resp.getHeader("Location").split("/");
    Integer id = Integer.parseInt(split[split.length - 1]);
    ImportContext context = importer.getContext(id);

    MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/");
    MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>(1);
    form.add("url", new File(zip).getAbsoluteFile().toURI().toString());
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final HttpHeaders headers = new HttpHeaders();
    new FormHttpMessageConverter().write(form, MediaType.APPLICATION_FORM_URLENCODED, new HttpOutputMessage() {
        @Override//from  w w w. jav a 2 s.  c o  m
        public OutputStream getBody() throws IOException {
            return stream;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    });
    req.setContent(stream.toByteArray());
    req.setMethod("POST");
    req.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    req.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    resp = dispatch(req);

    assertEquals(201, resp.getStatus());

    context = importer.getContext(context.getId());
    assertNull(context.getData());
    assertEquals(1, context.getTasks().size());

    ImportTask task = context.getTasks().get(0);
    assertTrue(task.getData() instanceof SpatialFile);

    return id;
}