Example usage for org.springframework.util MultiValueMap get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues,
        String parentParamName) {

    if (Map.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Map not supported");
    } else if (Collection.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Collection not supported");
    } else {// w  w w . j a  v a 2 s  .  co  m
        try {
            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
            if (constructor == null) {
                constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
            }
            Assert.notNull(constructor, "no default constructor or JsonCreator found");
            int parameterCount = constructor.getParameterTypes().length;
            Object[] args = new Object[parameterCount];
            if (parameterCount > 0) {
                Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();
                Class[] parameters = constructor.getParameterTypes();
                int paramIndex = 0;
                for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                    for (Annotation annotation : annotationsOnParameter) {
                        if (JsonProperty.class == annotation.annotationType()) {
                            JsonProperty jsonProperty = (JsonProperty) annotation;
                            String paramName = jsonProperty.value();
                            List<String> formValue = formValues.get(parentParamName + paramName);
                            Class<?> parameterType = parameters[paramIndex];
                            if (DataType.isSingleValueType(parameterType)) {
                                if (formValue != null) {
                                    if (formValue.size() == 1) {
                                        args[paramIndex++] = DataType.asType(parameterType, formValue.get(0));
                                    } else {
                                        //                                        // TODO create proper collection type
                                        throw new IllegalArgumentException("variable list not supported");
                                        //                                        List<Object> listValue = new ArrayList<Object>();
                                        //                                        for (String item : formValue) {
                                        //                                            listValue.add(DataType.asType(parameterType, formValue.get(0)));
                                        //                                        }
                                        //                                        args[paramIndex++] = listValue;
                                    }
                                } else {
                                    args[paramIndex++] = null;
                                }
                            } else {
                                args[paramIndex++] = recursivelyCreateObject(parameterType, formValues,
                                        parentParamName + paramName + ".");
                            }
                        }
                    }
                }
                Assert.isTrue(args.length == paramIndex,
                        "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty");
            }
            Object ret = constructor.newInstance(args);
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                String name = propertyDescriptor.getName();
                List<String> strings = formValues.get(name);
                if (writeMethod != null && strings != null && strings.size() == 1) {
                    writeMethod.invoke(ret,
                            DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor
                }
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e);
        }
    }
}

From source file:io.github.davejoyce.dao.composite.social.connect.jpa.JpaConnectionRepository.java

/**
 * {@inheritDoc}//from  w  w  w . j  a  v a2s  .c om
 */
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }
    StringBuilder providerUsersCriteriaJpaQl = new StringBuilder(QUERY_SELECT_FROM)
            .append("WHERE ausc.key.appUser.userId = :userId").append(" AND ");
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        providerUsersCriteriaJpaQl.append("ausc.key.providerId = :providerId_").append(providerId)
                .append("AND ausc.key.providerUserId IN (:providerUserIds_").append(providerId).append(")");
        if (it.hasNext()) {
            providerUsersCriteriaJpaQl.append(" OR ");
        }
    }
    providerUsersCriteriaJpaQl.append(" ORDER BY ausc.key.providerId, ausc.rank");
    TypedQuery<AppUserSocialConnection> query = entityManager
            .createQuery(providerUsersCriteriaJpaQl.toString(), AppUserSocialConnection.class)
            .setParameter("userId", userId);
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        query.setParameter(("providerId_" + providerId), providerId)
                .setParameter(("providerUserIds_" + providerId), entry.getValue());
    }
    List<Connection<?>> resultList = appUserSocialConnectionsToConnections(query.getResultList());
    MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>();
    for (Connection<?> connection : resultList) {
        String providerId = connection.getKey().getProviderId();
        List<String> userIds = providerUsers.get(providerId);
        List<Connection<?>> connections = connectionsForUsers.get(providerId);
        if (connections == null) {
            connections = new ArrayList<Connection<?>>(userIds.size());
            for (int i = 0; i < userIds.size(); i++) {
                connections.add(null);
            }
            connectionsForUsers.put(providerId, connections);
        }
        String providerUserId = connection.getKey().getProviderUserId();
        int connectionIndex = userIds.indexOf(providerUserId);
        connections.set(connectionIndex, connection);
    }
    return connectionsForUsers;
}

From source file:com.kabone.research.common.utils.FileUtil.java

/**
 * ?//from   www . j av  a  2 s  .  c  om
 * @param map
 * @param realPath
 * @param dirPath
 * @param thumbnail
 * @return
 * @throws IllegalStateException
 * @throws IOException
 */
public static List<Map<String, Object>> getFileInfo(MultiValueMap<String, MultipartFile> map, String realPath,
        String dirPath, boolean thumbnail) throws IllegalStateException, IOException {

    Date time = Calendar.getInstance().getTime();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssS");
    String formatDate = formatter.format(time);

    List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();

    Iterator<String> iterator = map.keySet().iterator();

    //  savePath ? /yyyy/mm/ ??   
    String savePath = dirPath + File.separator + StringUtils.substring(formatDate, 0, 4) + File.separator
            + StringUtils.substring(formatDate, 4, 6) + File.separator;

    String realFilePath = realPath + savePath;
    String logicalPath = savePath;

    if (File.separator.equalsIgnoreCase("\\")) {
        logicalPath = savePath.replaceAll("\\\\", "/");
    }

    while (iterator.hasNext()) {

        Map<String, Object> fileMap = new HashMap<String, Object>();

        String key = iterator.next();
        LinkedList<MultipartFile> df = (LinkedList<MultipartFile>) map.get(key);

        CommonsMultipartFile fileInfo = (CommonsMultipartFile) df.getFirst();
        if (fileInfo.getSize() > 0) {
            fileMap.put("key", key);

            int idx = fileInfo.getOriginalFilename().lastIndexOf(".");

            String extName = "";
            if (idx != -1) {
                extName = fileInfo.getOriginalFilename().substring(idx,
                        fileInfo.getOriginalFilename().length());
            }

            File fDir = new File(realFilePath);
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            File file1 = new File(realFilePath + formatDate + fileInfo.getName() + extName);
            fileInfo.transferTo(file1);

            logger.info("fileInfo.realFilePath() : " + realFilePath);
            logger.info("fileInfo.logicalPath() : " + logicalPath);
            logger.info("fileInfo.getOriginalFilename() : " + fileInfo.getOriginalFilename());
            logger.info("fileInfo.getName() : " + fileInfo.getName());
            logger.info("fileInfo.path() : " + logicalPath + formatDate + fileInfo.getName() + extName);

            fileMap.put("path", logicalPath + formatDate + fileInfo.getName() + extName);
            fileMap.put("name", fileInfo.getOriginalFilename());
            fileMap.put("size", "" + fileInfo.getSize());

            //??
            if (thumbnail) {
                int imageWidth = 0;
                int imageHeight = 0;
                //? ? ?? ?
                if ("mainImg".equals(fileInfo.getName())) {
                    logger.info("? ? ?? ?");
                    imageWidth = 645;
                    imageHeight = 485;
                } else if ("cardImg".equals(fileInfo.getName())) {
                    logger.info(" ? ?? ?");
                    imageWidth = 240;
                    imageHeight = 180;
                }

                if (imageWidth != 0 && imageHeight != 0) {
                    File originFileName = new File(realFilePath + formatDate + fileInfo.getName() + extName);
                    File thumbFileName = new File(
                            realFilePath + "thumbnail_" + formatDate + fileInfo.getName() + extName);

                    thumbnail(imageWidth, imageHeight, originFileName, thumbFileName);

                    fileMap.put("thumb",
                            logicalPath + "thumbnail_" + formatDate + fileInfo.getName() + extName);
                }
            }
            fileList.add(fileMap);
        }

    }

    return fileList;
}

From source file:com.kabone.research.common.utils.FileUtil.java

public static List<Map<String, Object>> getFileInfo2(String BUCKET_NAME, String S3_ENDPOINT, String ACCESS_KEY,
        String SECRET_KEY, MultiValueMap<String, MultipartFile> map, String realPath, String dirPath,
        boolean thumbnail) throws Exception {
    //public static List<Map<String,Object>> getFileInfo2(MultiValueMap<String, MultipartFile> map, String realPath, String dirPath, boolean thumbnail) throws Exception {

    Date time = Calendar.getInstance().getTime();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssS");
    String formatDate = formatter.format(time);

    List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
    Iterator<String> iterator = map.keySet().iterator();

    String savePath = dirPath + "/";

    String realFilePath = realPath + savePath;
    /*/*from ww  w.j a  va2  s .c  o  m*/
    String logicalPath = savePath;
            
    if(File.separator.equalsIgnoreCase("\\")) {
    logicalPath = savePath.replaceAll("\\\\", "/");
    }
    */
    File fDir = new File(realFilePath);
    if (!fDir.exists()) {
        fDir.mkdirs();
    }

    AWSUtil.s3MakeFolder(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY, dirPath);

    while (iterator.hasNext()) {

        Map<String, Object> fileMap = new HashMap<String, Object>();

        String key = iterator.next();
        LinkedList<MultipartFile> df = (LinkedList<MultipartFile>) map.get(key);

        CommonsMultipartFile fileInfo = (CommonsMultipartFile) df.getFirst();
        if (fileInfo.getSize() > 0) {
            fileMap.put("key", key);

            int idx = fileInfo.getOriginalFilename().lastIndexOf(".");

            String extName = "";
            if (idx != -1) {
                extName = fileInfo.getOriginalFilename().substring(idx,
                        fileInfo.getOriginalFilename().length());
            }
            String fileName = formatDate + fileInfo.getName() + extName;
            File file1 = new File(realFilePath + fileName);
            fileInfo.transferTo(file1);

            logger.info("fileInfo.getOriginalFilename() : " + fileInfo.getOriginalFilename());

            String filePath = AWSUtil.s3FileUpload(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY,
                    savePath + fileName, realFilePath + fileName);

            logger.info("filePath : " + filePath);

            fileMap.put("path", filePath);
            fileMap.put("name", fileInfo.getOriginalFilename());
            fileMap.put("size", "" + fileInfo.getSize());

            //??
            if (thumbnail) {
                int imageWidth = 0;
                int imageHeight = 0;
                //? ? ?? ?
                if ("mainImg".equals(fileInfo.getName())) {
                    //??
                    imageWidth = 645;
                    imageHeight = 485;
                } else if ("cardImg".equals(fileInfo.getName())) {
                    //?
                    imageWidth = 224;
                    imageHeight = 180;
                } else if ("storyImg".equals(fileInfo.getName())) {
                    //
                    imageWidth = 148;
                    imageHeight = 98;
                } else if ("ftypeMainImg".equals(fileInfo.getName())) {
                    // ??
                    imageWidth = 980;
                    imageHeight = 400;
                } else if ("choiceImg".equals(fileInfo.getName())) {
                    // Editor's Choice ?
                    imageWidth = 160;
                    imageHeight = 70;
                }

                if (imageWidth != 0 && imageHeight != 0) {
                    File originFileName = new File(realFilePath + fileName);
                    File thumbFileName = new File(realFilePath + "thumbnail_" + fileName);

                    boolean result = thumbnail(imageWidth, imageHeight, originFileName, thumbFileName);
                    String filePath2 = "";
                    if (result) {
                        filePath2 = AWSUtil.s3FileUpload(S3_ENDPOINT, BUCKET_NAME, ACCESS_KEY, SECRET_KEY,
                                savePath + "thumbnail_" + fileName, realFilePath + "thumbnail_" + fileName);
                    }

                    if (thumbFileName.exists()) {
                        thumbFileName.delete();
                    }

                    fileMap.put("thumbPath", filePath2);
                }
            }

            if (file1.exists()) {
                file1.delete();
            }

            fileList.add(fileMap);
        }

    }

    return fileList;
}

From source file:com.yunmel.syncretic.core.BaseController.java

protected void uploadFile(HttpServletRequest request, String field, File file) {
    try {/*from w  ww.j a v  a  2  s  . co m*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            List<MultipartFile> files = map.get(field);
            MultipartFile _file = files.get(0);
            IOUtils.copyInputStreamToFile(_file.getInputStream(), file);
        }
    } catch (IOException e) {
        LOG.error("upload file error.", e);
    }
}

From source file:com.yunmel.syncretic.core.BaseController.java

protected File uploadFile(HttpServletRequest request, String field) {
    try {/* w  ww .  ja  v a 2s  .  c o m*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            List<MultipartFile> files = map.get(field);
            MultipartFile _file = files.get(0);
            File file = new File(RandomUtils.genRandom32Hex());
            IOUtils.copyInputStreamToFile(_file.getInputStream(), file);
            return file;
        }
    } catch (IOException e) {
        LOG.error("upload file error.", e);
    }

    return null;
}

From source file:com.yunmel.syncretic.core.BaseController.java

protected MultipartFile getMultipartFile(HttpServletRequest request, String field) {
    try {/*  w w w  .j  av a2  s  .co  m*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            List<MultipartFile> files = map.get(field);
            return files.get(0);
        }
    } catch (Exception e) {
        LOG.error("upload file error.", e);
    }

    return null;
}

From source file:com.yunmel.syncretic.core.BaseController.java

protected List<MultipartFile> getMultipartFiles(HttpServletRequest request, String field) {
    try {/*w w  w.  ja  v  a2  s.c  o m*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            return map.get(field);
        }
    } catch (Exception e) {
        LOG.error("upload file error.", e);
    }

    return null;
}

From source file:de.blizzy.documentr.markdown.macro.impl.GoogleDocsMacro.java

@Override
public String getHtml(IMacroContext macroContext) {
    String macroParams = macroContext.getParameters();
    String googleUrl = StringUtils.substringBefore(macroParams, " ").trim(); //$NON-NLS-1$
    String width = StringUtils.substringAfter(macroParams, " ").trim(); //$NON-NLS-1$

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(googleUrl).build();
    String path = uriComponents.getPath();
    MultiValueMap<String, String> params = uriComponents.getQueryParams();
    if (path.startsWith("/spreadsheet/")) { //$NON-NLS-1$
        String key = params.get("key").get(0); //$NON-NLS-1$
        UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/spreadsheet/pub") //$NON-NLS-1$
                .queryParam("key", key) //$NON-NLS-1$
                .queryParam("output", "html") //$NON-NLS-1$ //$NON-NLS-2$
                .queryParam("widget", "true") //$NON-NLS-1$ //$NON-NLS-2$
                .build();//from  w ww .j  a v a 2 s  .  c  o  m
        return buildIframe(components);
    } else if (path.startsWith("/document/")) { //$NON-NLS-1$
        String id = params.get("id").get(0); //$NON-NLS-1$
        UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/document/pub") //$NON-NLS-1$
                .queryParam("id", id) //$NON-NLS-1$
                .queryParam("embedded", "true") //$NON-NLS-1$ //$NON-NLS-2$
                .build();
        return buildIframe(components);
    } else if (path.startsWith("/presentation/")) { //$NON-NLS-1$
        String id = params.get("id").get(0); //$NON-NLS-1$
        UriComponents components = UriComponentsBuilder
                .fromHttpUrl("https://docs.google.com/presentation/embed") //$NON-NLS-1$
                .queryParam("id", id) //$NON-NLS-1$
                .queryParam("start", "false") //$NON-NLS-1$ //$NON-NLS-2$
                .queryParam("loop", "false") //$NON-NLS-1$ //$NON-NLS-2$
                .queryParam("delayms", String.valueOf(TimeUnit.MILLISECONDS.convert(3, TimeUnit.SECONDS))) //$NON-NLS-1$
                .build();
        return buildIframe(components);
    } else if (path.startsWith("/drawings/")) { //$NON-NLS-1$
        String id = params.get("id").get(0); //$NON-NLS-1$
        if (StringUtils.isBlank(width)) {
            width = "960"; //$NON-NLS-1$
        }
        UriComponents components = UriComponentsBuilder.fromHttpUrl("https://docs.google.com/drawings/pub") //$NON-NLS-1$
                .queryParam("id", id) //$NON-NLS-1$
                .queryParam("w", width) //$NON-NLS-1$
                .build();
        return buildImg(components);
    } else {
        return null;
    }
}

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

/**
 * Check whether there is only 1 file and 1 schema available and their xml schemas match.
 *
 * @param xmlFiles   xml files// w  ww.  j av  a 2  s  .c om
 * @param webForms   web forms
 * @param parameters request parameters
 * @return true iff there are only 1 file and schema with equal xml schema
 */
private boolean hasOnlyOneFileAndWebFormForSameSchema(MultiValueMap<String, XmlFile> xmlFiles,
        Collection<ProjectFile> webForms, CdrRequest parameters) {
    if (webForms.size() == 1 && !parameters.isNewFormCreationAllowed()) {
        List<XmlFile> filesForSchema = xmlFiles.get(webForms.iterator().next().getXmlSchema());
        if (filesForSchema != null && filesForSchema.size() == 1) {
            return true;
        }
    }
    return false;
}