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:org.n52.io.request.IoParameters.java

protected static MultiValueMap<String, JsonNode> convertValuesToJsonNodes(
        MultiValueMap<String, String> queryParameters) {
    MultiValueMap<String, JsonNode> parameters = new LinkedMultiValueMap<>();
    final Set<Entry<String, List<String>>> entrySet = queryParameters.entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        for (String value : entry.getValue()) {
            final String key = entry.getKey().toLowerCase();
            parameters.add(key, getJsonNodeFrom(value));
        }//from w  w w .  j a  v  a 2  s. c  om
    }
    return parameters;
}

From source file:org.n52.io.request.IoParameters.java

public IoParameters extendWith(String key, String... values) {
    MultiValueMap<String, String> newValues = new LinkedMultiValueMap<>();
    newValues.put(key.toLowerCase(), Arrays.asList(values));

    MultiValueMap<String, JsonNode> mergedValues = new LinkedMultiValueMap<>(query);
    mergedValues.putAll(convertValuesToJsonNodes(newValues));
    return new IoParameters(mergedValues);
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Parse the given string with matrix variables. An example string would look
 * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain
 * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and
 * {@code ["a","b","c"]} respectively./*  w w  w  .j a  v a 2  s  . co  m*/
 *
 * @param matrixVariables the unparsed matrix variables string
 * @return a map with matrix variable names and values, never {@code null}
 */
public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables) {
    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
    if (!StringUtils.hasText(matrixVariables)) {
        return result;
    }
    StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
    while (pairs.hasMoreTokens()) {
        String pair = pairs.nextToken();
        int index = pair.indexOf('=');
        if (index != -1) {
            String name = pair.substring(0, index);
            String rawValue = pair.substring(index + 1);
            for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
                result.add(name, value);
            }
        } else {
            result.add(pair, "");
        }
    }
    return result;
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private BufferedImage createFloorImage(HmFolder floor, double scale, int floorWidth, int floorHeight,
        Map<Long, Integer> channelMap, Map<Long, Integer> colorMap, int borderX, int borderY, double gridSize)
        throws Exception {
    BufferedImage image = new BufferedImage(floorWidth + borderX + 1, floorHeight + borderY + 1,
            BufferedImage.TYPE_INT_ARGB);
    if (floor == null) {
        return image;
    }//from   w  ww  . jav a 2 s. c o m
    double metricWidth = 0.0, metricHeight = 0.0, offsetX = 0.0, offsetY = 0.0;
    int imageWidth = 0;
    LengthUnit lengthUnit = LengthUnit.METERS;

    if (null != floor.getMetricWidth()) {
        metricWidth = floor.getMetricWidth().doubleValue();
    }
    if (null != floor.getMetricHeight()) {
        metricHeight = floor.getMetricHeight().doubleValue();
    }
    if (null != floor.getImageWidth()) {
        imageWidth = floor.getImageWidth().intValue();
    }
    if (null != floor.getOffsetX()) {
        offsetX = floor.getOffsetX().doubleValue();
    }
    if (null != floor.getOffsetY()) {
        offsetY = floor.getOffsetY().doubleValue();
    }
    if (null != floor.getLengthUnit()) {
        lengthUnit = floor.getLengthUnit();
    }

    Graphics2D g2 = image.createGraphics();
    g2.setStroke(new BasicStroke(1));
    if (getDistanceMetric(metricWidth, lengthUnit) == 0) {
        g2.setColor(new Color(255, 255, 255));
        g2.fillRect(borderX, 0, floorWidth + 1, borderY);
        g2.fillRect(0, 0, borderX, borderY + floorHeight + 1);
        g2.setColor(new Color(120, 120, 120));
        g2.drawLine(0, borderY, floorWidth + borderX, borderY);
        g2.drawLine(borderX, 0, borderX, floorHeight + borderY);
        g2.setColor(new Color(255, 255, 204));
        g2.fillRect(borderX + 2, borderY + 2, 162, 25);
        g2.setColor(new Color(0, 51, 102));
        g2.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 12));
        g2.drawString("Please size this floor plan.", borderX + 8, borderY + 19);
        return image;
    }
    double screenWidth = scale * getDistanceMetric(metricWidth, lengthUnit);
    double imageScale = screenWidth / imageWidth;
    int originX = (int) (getDistanceMetric(offsetX, lengthUnit) * scale);
    int originY = (int) (getDistanceMetric(offsetY, lengthUnit) * scale);
    g2.setColor(new Color(255, 255, 255));
    if (floor.getBackground() != null && floor.getBackground().length() > 0) {
        LinkedMultiValueMap<String, String> metadata = new LinkedMultiValueMap<>();
        String url = getImageBaseUrl(floor.getOwnerId()) + floor.getBackground();
        try {
            BufferedImage map = ImageIO.read(clientFileService.getFile(url, "AFS_TOKEN", metadata));
            AffineTransform transform = new AffineTransform();
            transform.scale(imageScale, imageScale);
            g2.drawImage(map, new AffineTransformOp(transform, null), getFloorX(0, borderX, originX),
                    getFloorY(0, borderY, originY));
        } catch (Exception e) {
            logger.error(String.format("image file not found with url: %s", url));
            double screenHeight = scale * getDistanceMetric(metricHeight, lengthUnit);
            g2.fillRect(getFloorX(0, borderX, originX), getFloorY(0, borderY, originY), (int) screenWidth,
                    (int) screenHeight);
        }
    } else {
        double screenHeight = scale * getDistanceMetric(metricHeight, lengthUnit);
        g2.fillRect(getFloorX(0, borderX, originX), getFloorY(0, borderY, originY), (int) screenWidth,
                (int) screenHeight);
    }
    g2.setColor(new Color(204, 204, 204));
    // Right edge border
    g2.drawLine(borderX + floorWidth, borderY + 1, borderX + floorWidth, borderY + floorHeight);
    // Left edge border (right of tick marks)
    g2.drawLine(borderX + 1, borderY + floorHeight, borderX + floorWidth, borderY + floorHeight);
    g2.setColor(new Color(255, 255, 255));
    g2.fillRect(borderX, 0, floorWidth + 1, borderY);
    g2.fillRect(0, 0, borderX, borderY + floorHeight + 1);
    g2.setColor(new Color(120, 120, 120));
    g2.drawLine(0, borderY, floorWidth + borderX, borderY);
    g2.drawLine(borderX, 0, borderX, floorHeight + borderY);

    Font font = new Font(Font.SANS_SERIF, Font.BOLD, 12);
    double actualWidth = floorWidth / scale;
    double actualHeight = floorHeight / scale;
    String firstLabel;
    double unitScale = scale;
    if (LengthUnit.FEET == lengthUnit) {
        firstLabel = "0 feet";
        actualWidth /= HmFolder.FEET_TO_METERS;
        actualHeight /= HmFolder.FEET_TO_METERS;
        unitScale *= HmFolder.FEET_TO_METERS;
    } else {
        firstLabel = "0 meters";
    }
    g2.drawString(firstLabel, borderX + 4, 12);
    double gridX = gridSize;
    while (gridX < actualWidth) {
        int x = (int) (gridX * unitScale) + borderX;
        g2.drawLine(x, 0, x, borderY);
        boolean label = true;
        if (gridX + gridSize >= actualWidth) {
            // Last mark
            if (x + getNumberPixelWidth(gridX) + 2 > floorWidth) {
                label = false;
            }
        }
        if (label) {
            g2.drawString("" + (int) gridX, x + 4, 12);
        }
        gridX += gridSize;
    }

    double gridY = 0;
    while (gridY < actualHeight) {
        int y = (int) (gridY * unitScale) + borderY;
        g2.drawLine(0, y, borderX, y);
        double lx = gridY;
        int dx = 1;
        for (int bx = borderX; bx >= 16; bx -= 7) {
            if (lx < 10) {
                dx += 7;
            } else {
                lx /= 10;
            }
        }
        boolean label = true;
        if (gridY + gridSize >= actualHeight) {
            // Last mark
            if (y - borderY + 13 > floorHeight) {
                label = false;
            }
        }
        if (label) {
            g2.drawString("" + (int) gridY, dx, y + 13);
        }
        gridY += gridSize;
    }

    double mapToImage = getMapToMetric(metricWidth, imageWidth, lengthUnit) * scale;
    if (floor.getPerimeter().size() > 0) {
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(2, 159, 245));
        int[] xPoints = new int[floor.getPerimeter().size()];
        int[] yPoints = new int[floor.getPerimeter().size()];
        int nPoints = 0;
        int perimId = floor.getPerimeter().get(0).getId();
        for (int i = 0; i < floor.getPerimeter().size(); i++) {
            HmVertex vertex = floor.getPerimeter().get(i);
            if (vertex.getId() != perimId) {
                g2.drawPolygon(xPoints, yPoints, nPoints);
                nPoints = 0;
                perimId = vertex.getId();
            }
            xPoints[nPoints] = getFloorX((int) (vertex.getX() * mapToImage), borderX, originX);
            yPoints[nPoints++] = getFloorY((int) (vertex.getY() * mapToImage), borderY, originY);
        }
        g2.drawPolygon(xPoints, yPoints, nPoints);
    }

    g2.setStroke(new BasicStroke(1));
    g2.setColor(new Color(0, 170, 0));
    g2.setFont(font.deriveFont(Font.BOLD, 11));

    List<HmDeviceLocationEx> devices = deviceLocationExRep.findAllHmDevices(floor.getId());
    if (null != devices && !devices.isEmpty()) {
        for (HmDeviceLocationEx device : devices) {
            double x = device.getX() * mapToImage;
            double y = device.getY() * mapToImage;
            createNodeImage(device.getId(), channelMap, colorMap, getFloorX((int) x, borderX, originX),
                    getFloorY((int) y, borderY, originY), g2);
        }
    } else {
        List<HmDevicePlanningEx> plannedDevices = devicePlanningExRep.findAllPlannedDevices(floor.getId());
        for (HmDevicePlanningEx plannedDevice : plannedDevices) {
            double x = plannedDevice.getX() * mapToImage;
            double y = plannedDevice.getY() * mapToImage;
            createNodeImage(plannedDevice.getId(), channelMap, colorMap, getFloorX((int) x, borderX, originX),
                    getFloorY((int) y, borderY, originY), g2);
        }
    }
    return image;
}

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

private InputStream getFileInputStream(DriveFile driveFile, String mimetype)
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    RestTemplate restTemplate = new RestTemplate();

    String url = getExportLink(driveFile, mimetype);
    log.debug("Google Export Format (mimetype) link: " + url);

    if (url == null) {
        throw new GoogleDocsServiceException("Google Docs Export Format not found.",
                HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*from  w w  w.j  a v a  2  s  . c  o  m*/

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + getConnection().getApi().getAccessToken());
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(body,
            headers);

    ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);

    return new ByteArrayInputStream(response.getBody());
}

From source file:com.muk.services.api.impl.PayPalPaymentService.java

private String getTokenHeader() {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache);
    final String token = "paypal";
    ValueWrapper valueWrapper = cache.get(token);
    String cachedHeader = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        try {/*  w ww.  jav a 2s. co  m*/
            final String value = securityCfgService.getPayPalClientId() + ":"
                    + keystoreService.getPBEKey(securityCfgService.getPayPalClientId());

            final HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.AUTHORIZATION,
                    "Basic " + nonceService.encode(value.getBytes(StandardCharsets.UTF_8)));

            final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
            body.add("grant_type", "client_credentials");

            final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                    body, headers);

            final ResponseEntity<JsonNode> response = restTemplate.postForEntity(
                    securityCfgService.getPayPalUri() + "/oauth2/token", request, JsonNode.class);

            cache.put(token, response.getBody().get("access_token").asText());
            valueWrapper = cache.get(token);
            cachedHeader = (String) valueWrapper.get();
        } catch (final IOException ioEx) {
            LOG.error("Failed read keystore", ioEx);
            cachedHeader = StringUtils.EMPTY;
        } catch (final GeneralSecurityException secEx) {
            LOG.error("Failed to get key", secEx);
            cachedHeader = StringUtils.EMPTY;
        }
    } else {
        cachedHeader = (String) valueWrapper.get();
    }

    return "Bearer " + cachedHeader;
}

From source file:com.muk.services.api.impl.StripePaymentService.java

private ResponseEntity<JsonNode> send(String path, JsonNode payload) {
    final HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader());

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    final Iterator<Entry<String, JsonNode>> nodes = payload.fields();

    while (nodes.hasNext()) {
        final Map.Entry<String, JsonNode> entry = nodes.next();

        if (entry.getValue().isObject()) {
            final String key = entry.getKey();
            final Iterator<Entry<String, JsonNode>> metadataNodes = entry.getValue().fields();

            while (metadataNodes.hasNext()) {
                final Map.Entry<String, JsonNode> element = metadataNodes.next();
                body.add(key + "[\"" + element.getKey() + "\"]", element.getValue().asText());
            }//from   ww w. jav  a 2 s. c om
        } else {
            body.add(entry.getKey(), entry.getValue().asText());
        }
    }

    return restTemplate.postForEntity(securityCfgService.getStripeUri() + path,
            new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@SuppressWarnings("unchecked")
@Override//from ww w . j a v  a 2s.  c  om
public Map<String, Object> loginForClient(String username, String password, String clientId,
        UriComponents inUrlComponents) {
    final Map<String, Object> responsePayload = new HashMap<String, Object>();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());

    // login for csrf
    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build();

    ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers,
            String.class);

    final List<String> cookies = new ArrayList<String>();
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", username);
    formData.add("password", password);
    formData.add(CSRF, getCsrf(cookies));

    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));
    headers.add(HttpHeaders.REFERER, loginUri.toUriString());

    // login.do
    response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(),
            HttpMethod.POST, formData, headers, String.class);

    if (response.getStatusCode() != HttpStatus.FOUND
            || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) {
        responsePayload.put("error", "bad credentials");
        return responsePayload;
    }

    removeCookie(cookies, "X-Uaa-Csrf");
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));
    removeExpiredCookies(cookies);
    headers.remove(HttpHeaders.REFERER);
    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));

    // authorize
    final ResponseEntity<JsonNode> authResponse = exchangeForType(
            uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
                    .queryParam("response_type", "code").queryParam("client_id", clientId)
                    .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(),
            HttpMethod.GET, null, headers, JsonNode.class);

    if (authResponse.getStatusCode() == HttpStatus.OK) {
        removeCookie(cookies, "X-Uaa-Csrf");
        cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE));
        // return approval data
        final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>();

        for (final String cookie : cookies) {
            parsedCookies.add(HttpCookie.parse(cookie).get(0));
        }

        responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>());

        for (final HttpCookie parsedCookie : parsedCookies) {
            if (!parsedCookie.getName().startsWith("Saved-Account")) {
                parsedCookie.setPath(inUrlComponents.getPath());
                ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE))
                        .add(httpCookieToString(parsedCookie));
            }
        }

        responsePayload.put("json", authResponse.getBody());
    } else {
        // get auth_code from Location Header
        responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]);
    }

    return responsePayload;
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }//ww  w  .  ja  v a  2 s  . co  m

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}

From source file:com.muk.services.util.GoogleOAuthService.java

private String requestAccessToken(String jwt) {
    final HttpHeaders headers = new HttpHeaders();
    String token = "error";

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    body.add("grant_type", TOKEN_GRANT);
    body.add("assertion", jwt);

    try {//from   w ww  .  ja va  2 s.c  o m
        final ResponseEntity<JsonNode> response = restTemplate.postForEntity(JWT_AUD,
                new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);

        token = response.getBody().get("access_token").asText();
    } catch (final HttpClientErrorException httpClientEx) {
        LOG.error("Failed to request token.", httpClientEx);
    }

    return token;
}