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() 

Source Link

Document

Create a new LinkedMultiValueMap that wraps a LinkedHashMap .

Usage

From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.client.TaxeUserInfoFetcher.java

public UserInfo loadUserInfo(final OIDCAuthenticationToken token) {

    ServerConfiguration serverConfiguration = token.getServerConfiguration();

    if (serverConfiguration == null) {
        logger.warn("No server configuration found.");
        return null;
    }// w  w  w . j  a  va 2s  .c  om

    if (Strings.isNullOrEmpty(serverConfiguration.getUserInfoUri())) {
        logger.warn("No userinfo endpoint, not fetching.");
        return null;
    }

    try {

        // if we got this far, try to actually get the userinfo
        HttpClient httpClient = new SystemDefaultHttpClient();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        String userInfoString = null;

        if (serverConfiguration.getUserInfoTokenMethod() == null
                || serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.HEADER)) {
            RestTemplate restTemplate = new RestTemplate(factory) {

                @Override
                protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
                    ClientHttpRequest httpRequest = super.createRequest(url, method);
                    httpRequest.getHeaders().add("Authorization",
                            String.format("Bearer %s", token.getAccessTokenValue()));
                    return httpRequest;
                }
            };

            userInfoString = restTemplate.getForObject(serverConfiguration.getUserInfoUri(), String.class);

        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.FORM)) {
            MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
            form.add("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form,
                    String.class);
        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.QUERY)) {
            URIBuilder builder = new URIBuilder(serverConfiguration.getUserInfoUri());
            builder.setParameter("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.getForObject(builder.toString(), String.class);
        }

        if (!Strings.isNullOrEmpty(userInfoString)) {

            JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject();

            UserInfo userInfo = TaxeUserInfo.fromJson(userInfoJson);

            return userInfo;
        } else {
            // didn't get anything, return null
            return null;
        }
    } catch (Exception e) {
        logger.warn("Error fetching taxeuserinfo", e);
        return null;
    }

}

From source file:com.sojw.ahnchangho.core.util.UriUtils.java

/**
 * Multi value map./*w w  w  .  ja  v a2 s .co m*/
 *
 * @param map the map
 * @return the multi value map
 */
public static MultiValueMap<String, String> multiValueMap(Map<String, String> map) {
    if (MapUtils.isEmpty(map)) {
        return null;
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        params.add(entry.getKey(), entry.getValue());
    }
    return params;
}

From source file:com.sojw.ahnchangho.core.util.UriUtils.java

/**
 * Multi value map./*from w  w  w.  j a va 2s.  c  o m*/
 *
 * @param <T> the generic type
 * @param request the request
 * @return the string
 */
public static <T> MultiValueMap<String, String> multiValueMap(final T request) {
    if (request == null) {
        return null;
    }

    Map<String, Object> requestMap = JsonUtils.convertValue(request, new TypeReference<Map<String, Object>>() {
    });
    if (MapUtils.isEmpty(requestMap)) {
        return null;
    }

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    for (Entry<String, Object> entry : requestMap.entrySet()) {
        if (entry.getValue() instanceof List) {
            ((List) entry.getValue()).forEach(each -> {
                parameters.add(entry.getKey(), each.toString());
            });
        } else {
            parameters.add(entry.getKey(), entry.getValue().toString());
        }
    }

    return parameters;
}

From source file:com.thoughtworks.go.server.domain.AgentInstances.java

public LinkedMultiValueMap<String, ElasticAgentMetadata> allElasticAgentsGroupedByPluginId() {
    LinkedMultiValueMap<String, ElasticAgentMetadata> map = new LinkedMultiValueMap<>();

    for (Map.Entry<String, AgentInstance> entry : agentInstances.entrySet()) {
        AgentInstance agentInstance = entry.getValue();
        if (agentInstance.isElastic()) {
            ElasticAgentMetadata metadata = agentInstance.elasticAgentMetadata();
            map.add(metadata.elasticPluginId(), metadata);
        }//from   w ww  . j  a v a 2s . c o  m
    }

    return map;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Orders the job given by its jobid. Pay is per assigment, which is by default 5 units.
 *
 * @param job as CrowdJob/*from w  w w .j  a  v  a  2 s .  c o  m*/
 * @param channels : a vector of channels, in which the job should be made available
 * @param units : number of units to order
 * @param payPerAssigment : pay in (dollar) cents for each assignments
 * @return JsonNode that Crowdflower returns
 */

JsonNode orderJob(CrowdJob job, Vector<String> channels, int units, int payPerAssigment) {
    Log LOG = LogFactory.getLog(getClass());

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    MultiValueMap<String, String> argumentMap = new LinkedMultiValueMap<String, String>();

    argumentMap.add(debitKey, String.valueOf(units));
    for (String channel : channels) {
        argumentMap.add(channelKey + "[]", channel);
    }

    updateVariable(job, jobPaymentKey, String.valueOf(payPerAssigment));

    LOG.info("Order Job: #" + job.getId() + " with " + units + " judgments for " + payPerAssigment
            + " cents (dollar) per assigment.");
    JsonNode result = restTemplate.postForObject(orderJobURL, argumentMap, JsonNode.class, job.getId(), apiKey);

    return result;
}

From source file:egovframework.asadal.asapro.com.cmm.web.AsaproEgovMultipartResolver.java

/**
 * multipart?  parsing? .//  w  w w.ja v a2s . c om
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (!AsaproEgovWebUtil.checkAllowUploadFileExt(file.getOriginalFilename()))
                    throw new MultipartException(" ? ? .");

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:egovframework.com.cmm.web.EgovMultipartResolver.java

/**
 * multipart?  parsing? .//from  w  w w.  ja v  a 2  s  .  c om
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:eionet.webq.service.CDREnvelopeServiceImpl.java

/**
 * Prepares parameters for saveXml remote method.
 *
 * @param file file to be saved./*from  ww w  . j  a  va  2s .  c o m*/
 * @return http entity representing request
 */
HttpEntity<MultiValueMap<String, Object>> prepareXmlSaveRequestParameters(UserFile file) {

    HttpHeaders authorization = getAuthorizationHeader(file);

    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", file.getName());
    fileHeaders.setContentType(MediaType.TEXT_XML);

    MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
    byte[] content = file.getContent();
    if (StringUtils.isNotEmpty(file.getConversionId())) {
        content = conversionService.convert(file, file.getConversionId()).getBody();
    }
    request.add("file", new HttpEntity<byte[]>(content, fileHeaders));
    request.add("file_id", new HttpEntity<String>(file.getName()));
    request.add("title", new HttpEntity<String>(StringUtils.defaultString(file.getTitle())));
    if (file.isApplyRestriction()) {
        request.add("applyRestriction", new HttpEntity<String>("1"));
        request.add("restricted", new HttpEntity<String>(file.isRestricted() ? "1" : "0"));
    }

    return new HttpEntity<MultiValueMap<String, Object>>(request, authorization);
}

From source file:eionet.webq.service.CDREnvelopeServiceImpl.java

/**
 * Transform raw envelope service response to usable form.
 *
 * @param response service response//from w  ww .  jav a 2  s .  c  o m
 * @return {@link XmlFile} grouped by xml schema.
 */
@SuppressWarnings("unchecked")
private MultiValueMap<String, XmlFile> transformGetXmlFilesResponse(Object response) {
    LinkedMultiValueMap<String, XmlFile> result = new LinkedMultiValueMap<String, XmlFile>();
    if (response != null) {
        try {
            for (Map.Entry<String, Object[]> entry : ((Map<String, Object[]>) response).entrySet()) {
                String xmlSchema = entry.getKey();
                for (Object values : entry.getValue()) {
                    Object[] xmlFileData = (Object[]) values;
                    result.add(xmlSchema, new XmlFile(xmlFileData[0].toString(), xmlFileData[1].toString()));
                }
            }
        } catch (ClassCastException e) {
            LOGGER.error("received response=" + response);
            throw new CDREnvelopeException("unexpected response format from CDR envelope service.", e);
        }
    } else {
        LOGGER.warn("expected not null response from envelope service");
    }
    LOGGER.info("Xml files received=" + result);
    return result;
}

From source file:eionet.webq.web.controller.cdr.IntegrationWithCDRController.java

/**
 * WebQEdit request handler.//from   w  ww. ja v a  2  s. c o m
 *
 * @param request current request
 * @param model   model
 * @return view name
 * @throws FileNotAvailableException if remote file not available.
 */
@RequestMapping("/WebQEdit")
public String webQEdit(HttpServletRequest request, Model model) throws FileNotAvailableException {
    CdrRequest parameters = convertAndPutResultIntoSession(request);

    LOGGER.info("Received WebQEdit request with parameters:" + parameters.toString());

    String schema = parameters.getSchema();
    if (StringUtils.isEmpty(schema)) {
        throw new IllegalArgumentException("schema parameter is required");
    }

    Collection<ProjectFile> webForms = webFormService.findWebFormsForSchemas(Arrays.asList(schema));
    if (webForms.isEmpty()) {
        throw new IllegalArgumentException("no web forms for '" + schema + "' schema found");
    }
    String instanceUrl = parameters.getInstanceUrl();
    String fileName = parameters.getInstanceName();
    if (webForms.size() > 1) {
        LinkedMultiValueMap<String, XmlFile> xmlFiles = new LinkedMultiValueMap<String, XmlFile>();
        xmlFiles.add(schema, new XmlFile(instanceUrl, fileName));
        return deliverMenu(webForms, xmlFiles, parameters, model);
    }
    return editFile(webForms.iterator().next(), fileName, instanceUrl, parameters);
}