Java Code Examples for org.springframework.util.MultiValueMap#getFirst()

The following examples show how to use org.springframework.util.MultiValueMap#getFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebAuth.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
/**
 * Get user object from ws message header
 * @param headers
 * @return User object
 * @exception AuthenticationException if Token header is missing or invalid token
 */
public User validate(MessageHeaders headers) {
    MultiValueMap<String, String> map = headers.get(StompHeaderAccessor.NATIVE_HEADERS, MultiValueMap.class);
    if (Objects.isNull(map)) {
        throw new AuthenticationException("Invalid token");
    }

    String token = map.getFirst(HeaderToken);
    if (!StringHelper.hasValue(token)) {
        throw new AuthenticationException("Invalid token");
    }

    Optional<User> user = authService.get(token);
    if (!user.isPresent()) {
        throw new AuthenticationException("Invalid token");
    }

    return user.get();
}
 
Example 2
Source File: CookieWebSessionIdResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cookieInitializer() {
	this.resolver.addCookieInitializer(builder -> builder.domain("example.org"));
	this.resolver.addCookieInitializer(builder -> builder.sameSite("Strict"));
	this.resolver.addCookieInitializer(builder -> builder.secure(false));

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.org/path").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	this.resolver.setSessionId(exchange, "123");

	MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
	assertEquals(1, cookies.size());
	ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
	assertNotNull(cookie);
	assertEquals("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict", cookie.toString());
}
 
Example 3
Source File: TunnelSocketFrameHandler.java    From arthas with Apache License 2.0 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HandshakeComplete) {
        HandshakeComplete handshake = (HandshakeComplete) evt;
        // http request uri
        String uri = handshake.requestUri();
        logger.info("websocket handshake complete, uri: {}", uri);

        MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(uri).build().getQueryParams();
        String method = parameters.getFirst("method");

        if ("connectArthas".equals(method)) { // form browser
            connectArthas(ctx, parameters);
        } else if ("agentRegister".equals(method)) { // form arthas agent, register
            agentRegister(ctx, uri);
        }
        if ("openTunnel".equals(method)) { // from arthas agent open tunnel
            String clientConnectionId = parameters.getFirst("clientConnectionId");
            openTunnel(ctx, clientConnectionId);
        }
    } else {
        ctx.fireUserEventTriggered(evt);
    }
}
 
Example 4
Source File: SynchronossPartHttpMessageReaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-16545
public void transferTo() {
	ServerHttpRequest request = generateMultipartRequest();
	ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
	MultiValueMap<String, Part> parts = this.reader.readMono(elementType, request, emptyMap()).block();

	assertNotNull(parts);
	FilePart part = (FilePart) parts.getFirst("fooPart");
	assertNotNull(part);

	File dest = new File(System.getProperty("java.io.tmpdir") + "/" + part.filename());
	part.transferTo(dest).block(Duration.ofSeconds(5));

	assertTrue(dest.exists());
	assertEquals(12, dest.length());
	assertTrue(dest.delete());
}
 
Example 5
Source File: SynchronossPartHttpMessageReaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveParts() {
	ServerHttpRequest request = generateMultipartRequest();
	ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
	MultiValueMap<String, Part> parts = this.reader.readMono(elementType, request, emptyMap()).block();
	assertEquals(2, parts.size());

	assertTrue(parts.containsKey("fooPart"));
	Part part = parts.getFirst("fooPart");
	assertTrue(part instanceof FilePart);
	assertEquals("fooPart", part.name());
	assertEquals("foo.txt", ((FilePart) part).filename());
	DataBuffer buffer = DataBufferUtils.join(part.content()).block();
	assertEquals(12, buffer.readableByteCount());
	byte[] byteContent = new byte[12];
	buffer.read(byteContent);
	assertEquals("Lorem Ipsum.", new String(byteContent));

	assertTrue(parts.containsKey("barPart"));
	part = parts.getFirst("barPart");
	assertTrue(part instanceof FormFieldPart);
	assertEquals("barPart", part.name());
	assertEquals("bar", ((FormFieldPart) part).value());
}
 
Example 6
Source File: AbstractHttpSendingTransportHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected final String getCallbackParam(ServerHttpRequest request) {
	String query = request.getURI().getQuery();
	MultiValueMap<String, String> params = UriComponentsBuilder.newInstance().query(query).build().getQueryParams();
	String value = params.getFirst("c");
	if (StringUtils.isEmpty(value)) {
		return null;
	}
	try {
		String result = UriUtils.decode(value, "UTF-8");
		return (CALLBACK_PARAM_PATTERN.matcher(result).matches() ? result : null);
	}
	catch (UnsupportedEncodingException ex) {
		// should never happen
		throw new SockJsException("Unable to decode callback query parameter", null, ex);
	}
}
 
Example 7
Source File: CookieWebSessionIdResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setSessionId() {
	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.org/path").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	this.resolver.setSessionId(exchange, "123");

	MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
	assertEquals(1, cookies.size());
	ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
	assertNotNull(cookie);
	assertEquals("SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax", cookie.toString());
}
 
Example 8
Source File: JsonpReceivingTransportHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected String[] readMessages(ServerHttpRequest request) throws IOException {
	SockJsMessageCodec messageCodec = getServiceConfig().getMessageCodec();
	MediaType contentType = request.getHeaders().getContentType();
	if (contentType != null && MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
		MultiValueMap<String, String> map = this.formConverter.read(null, request);
		String d = map.getFirst("d");
		return (StringUtils.hasText(d) ? messageCodec.decode(d) : null);
	}
	else {
		return messageCodec.decodeInputStream(request.getBody());
	}
}
 
Example 9
Source File: ApiModelResource.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected ModelRepresentation updateModel(Model model, MultiValueMap<String, String> values, boolean forceNewVersion) {

        String name = values.getFirst("name");
        String key = values.getFirst("key");
        String description = values.getFirst("description");
        String isNewVersionString = values.getFirst("newversion");
        String newVersionComment = null;

        ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(), key);
        if (modelKeyInfo.isKeyAlreadyExists()) {
            throw new BadRequestException("Model with provided key already exists " + key);
        }

        boolean newVersion = false;
        if (forceNewVersion) {
            newVersion = true;
            newVersionComment = values.getFirst("comment");
        } else {
            if (isNewVersionString != null) {
                newVersion = "true".equals(isNewVersionString);
                newVersionComment = values.getFirst("comment");
            }
        }

        String json = values.getFirst("json_xml");

        try {
            model = modelService.saveModel(model.getId(), name, key, description, json, newVersion,
                    newVersionComment, SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(model);

        } catch (Exception e) {
            LOGGER.error("Error saving model {}", model.getId(), e);
            throw new BadRequestException("Process model could not be saved " + model.getId());
        }
    }
 
Example 10
Source File: RestFileManager.java    From sdk-rest with MIT License 5 votes vote down vote up
public void deleteTempResume(MultiValueMap<String, Object> multiValueMap) {
    // clean up file
    FileSystemResource fileSystemResource = (FileSystemResource) multiValueMap.getFirst(formFileName);

    File file = fileSystemResource.getFile();

    if (!file.delete()) {
        log.info("Unable to delete temp resume " + file.getAbsolutePath());
    }
}
 
Example 11
Source File: AbstractHttpSendingTransportHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
protected final String getCallbackParam(ServerHttpRequest request) {
	String query = request.getURI().getQuery();
	MultiValueMap<String, String> params = UriComponentsBuilder.newInstance().query(query).build().getQueryParams();
	String value = params.getFirst("c");
	if (StringUtils.isEmpty(value)) {
		return null;
	}
	String result = UriUtils.decode(value, StandardCharsets.UTF_8);
	return (CALLBACK_PARAM_PATTERN.matcher(result).matches() ? result : null);
}
 
Example 12
Source File: RestFileManager.java    From sdk-rest with MIT License 5 votes vote down vote up
public void deleteTempFile(MultiValueMap<String, Object> multiValueMap) {
    // clean up file
    FileSystemResource fileSystemResource = (FileSystemResource) multiValueMap.getFirst("file");

    String filePath = fileSystemResource.getPath();
    String newFolderPath = StringUtils.substringBeforeLast(filePath, "/");
    File newFolder = new File(newFolderPath);
    try {
        FileUtils.deleteDirectory(newFolder);
    } catch (IOException e) {
        log.info("Unable to delete temp file " + filePath);
    }

}
 
Example 13
Source File: AbstractPagingController.java    From taskana with Apache License 2.0 5 votes vote down vote up
private long getPage(MultiValueMap<String, String> params) throws InvalidArgumentException {
  String param = params.getFirst(PAGING_PAGE);
  params.remove(PAGING_PAGE);
  try {
    return Long.parseLong(param != null ? param : "1");
  } catch (NumberFormatException e) {
    throw new InvalidArgumentException("page must be a integer value.", e.getCause());
  }
}
 
Example 14
Source File: ValidateCodeFilter.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 校验验证码
 *
 * @param serverHttpRequest serverHttpRequest
 * @param loginType         loginType
 * @throws InvalidValidateCodeException
 */
private void checkCode(ServerHttpRequest serverHttpRequest, LoginTypeEnum loginType) throws InvalidValidateCodeException {
    MultiValueMap<String, String> params = serverHttpRequest.getQueryParams();
    // 验证码
    String code = params.getFirst("code");
    if (StrUtil.isBlank(code))
        throw new InvalidValidateCodeException("请输入验证码.");
    // 获取随机码
    String randomStr = params.getFirst("randomStr");
    // 随机数为空,则获取手机号
    if (StrUtil.isBlank(randomStr))
        randomStr = params.getFirst("mobile");
    String key = CommonConstant.DEFAULT_CODE_KEY + loginType.getType() + "@" + randomStr;
    // 验证码过期
    if (!redisTemplate.hasKey(key))
        throw new ValidateCodeExpiredException(GatewayConstant.EXPIRED_ERROR);
    Object codeObj = redisTemplate.opsForValue().get(key);
    if (codeObj == null)
        throw new ValidateCodeExpiredException(GatewayConstant.EXPIRED_ERROR);
    String saveCode = codeObj.toString();
    if (StrUtil.isBlank(saveCode)) {
        redisTemplate.delete(key);
        throw new ValidateCodeExpiredException(GatewayConstant.EXPIRED_ERROR);
    }
    if (!StrUtil.equals(saveCode, code)) {
        redisTemplate.delete(key);
        throw new InvalidValidateCodeException("验证码错误.");
    }
    redisTemplate.delete(key);
}
 
Example 15
Source File: StreamController.java    From proxylive with MIT License 5 votes vote down vote up
private boolean authenticate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(ProxyLiveUtils.getURL(request)).build().getQueryParams();

    String token = parameters.getFirst("token");
    String username = parameters.getFirst("user");
    if(token!=null){
        return validateToken(token);
    }else{
        return validateUser(username,parameters.getFirst("pass"));
    }
}
 
Example 16
Source File: LinkMap.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public static LinkMap buildLinkMap(List<Node> nodeList, TraceState traceState, long collectorAcceptTime, ServiceTypeRegistryService serviceTypeRegistryService) {
    final MultiValueMap<LongPair, Node> spanToLinkMap = new LinkedMultiValueMap<>();

    // for performance & remove duplicate span
    final List<Node> duplicatedNodeList = new ArrayList<>();
    for (Node node : nodeList) {
        final SpanBo span = node.getSpanBo();
        final LongPair spanIdPairKey = new LongPair(span.getParentSpanId(), span.getSpanId());
        // check duplicated span
        Node firstNode = spanToLinkMap.getFirst(spanIdPairKey);
        if (firstNode == null) {
            spanToLinkMap.add(spanIdPairKey, node);
        } else {
            ServiceType serviceType = serviceTypeRegistryService.findServiceType(span.getServiceType());
            if (serviceType.isQueue() && firstNode.getSpanBo().getServiceType() == serviceType.getCode()) {
                spanToLinkMap.add(spanIdPairKey, node);
            } else {
                traceState.progress();
                // duplicated span, choose focus span
                if (span.getCollectorAcceptTime() == collectorAcceptTime) {
                    // replace value
                    spanToLinkMap.put(spanIdPairKey, Collections.singletonList(node));
                    duplicatedNodeList.add(node);
                    logger.warn("Duplicated span - choose focus {}", node);
                } else {
                    // add remove list
                    duplicatedNodeList.add(node);
                    logger.warn("Duplicated span - ignored second {}", node);
                }
            }
        }
    }

    // clean duplicated node
    nodeList.removeAll(duplicatedNodeList);
    return new LinkMap(spanToLinkMap, duplicatedNodeList);
}
 
Example 17
Source File: CookieWebSessionIdResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setSessionId() {
	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.org/path").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	this.resolver.setSessionId(exchange, "123");

	MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
	assertEquals(1, cookies.size());
	ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
	assertNotNull(cookie);
	assertEquals("SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax", cookie.toString());
}
 
Example 18
Source File: ModelResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * POST /rest/models/{modelId}/editor/json -> save the JSON model
 */
@PostMapping(value = "/rest/models/{modelId}/editor/json")
public ModelRepresentation saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {

    // Validation: see if there was another update in the meantime
    long lastUpdated = -1L;
    String lastUpdatedString = values.getFirst("lastUpdated");
    if (lastUpdatedString == null) {
        throw new BadRequestException("Missing lastUpdated date");
    }
    try {
        Date readValue = objectMapper.getDeserializationConfig().getDateFormat().parse(lastUpdatedString);
        lastUpdated = readValue.getTime();
    } catch (ParseException e) {
        throw new BadRequestException("Invalid lastUpdated date: '" + lastUpdatedString + "'");
    }

    Model model = modelService.getModel(modelId);
    User currentUser = SecurityUtils.getCurrentUserObject();
    boolean currentUserIsOwner = model.getLastUpdatedBy().equals(currentUser.getId());
    String resolveAction = values.getFirst("conflictResolveAction");

    // If timestamps differ, there is a conflict or a conflict has been resolved by the user
    if (model.getLastUpdated().getTime() != lastUpdated) {

        if (RESOLVE_ACTION_SAVE_AS.equals(resolveAction)) {

            String saveAs = values.getFirst("saveAs");
            String json = values.getFirst("json_xml");
            return createNewModel(saveAs, model.getDescription(), model.getModelType(), json);

        } else if (RESOLVE_ACTION_OVERWRITE.equals(resolveAction)) {
            return updateModel(model, values, false);
        } else if (RESOLVE_ACTION_NEW_VERSION.equals(resolveAction)) {
            return updateModel(model, values, true);
        } else {

            // Exception case: the user is the owner and selected to create a new version
            String isNewVersionString = values.getFirst("newversion");
            if (currentUserIsOwner && "true".equals(isNewVersionString)) {
                return updateModel(model, values, true);
            } else {
                // Tried everything, this is really a conflict, return 409
                ConflictingRequestException exception = new ConflictingRequestException("Process model was updated in the meantime");
                exception.addCustomData("userFullName", model.getLastUpdatedBy());
                exception.addCustomData("newVersionAllowed", currentUserIsOwner);
                throw exception;
            }
        }

    } else {

        // Actual, regular, update
        return updateModel(model, values, false);

    }
}
 
Example 19
Source File: TaskHistoryEventController.java    From taskana with Apache License 2.0 4 votes vote down vote up
@GetMapping
@Transactional(readOnly = true, rollbackFor = Exception.class)
public ResponseEntity<TaskHistoryEventListResource> getTaskHistoryEvents(
    @RequestParam MultiValueMap<String, String> params) throws InvalidArgumentException {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Entry to getTaskHistoryEvents(params= {})", params);
  }

  HistoryQuery query = simpleHistoryService.createHistoryQuery();
  query = applySortingParams(query, params);
  applyFilterParams(query, params);

  PageMetadata pageMetadata = null;
  List<HistoryEventImpl> historyEvents;
  final String page = params.getFirst(PAGING_PAGE);
  final String pageSize = params.getFirst(PAGING_PAGE_SIZE);
  params.remove(PAGING_PAGE);
  params.remove(PAGING_PAGE_SIZE);
  validateNoInvalidParameterIsLeft(params);
  if (page != null && pageSize != null) {
    long totalElements = query.count();
    pageMetadata = initPageMetadata(pageSize, page, totalElements);
    historyEvents = query.listPage((int) pageMetadata.getNumber(), (int) pageMetadata.getSize());
  } else if (page == null && pageSize == null) {
    historyEvents = query.list();
  } else {
    throw new InvalidArgumentException("Paging information is incomplete.");
  }

  TaskHistoryEventListResourceAssembler assembler = new TaskHistoryEventListResourceAssembler();
  TaskHistoryEventListResource pagedResources =
      assembler.toResources(historyEvents, pageMetadata);

  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(
        "Exit from getTaskHistoryEvents(), returning {}",
        new ResponseEntity<>(pagedResources, HttpStatus.OK));
  }

  return new ResponseEntity<>(pagedResources, HttpStatus.OK);
}
 
Example 20
Source File: ModelResource.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected ModelRepresentation updateModel(Model model, MultiValueMap<String, String> values, boolean forceNewVersion) {
     String name = values.getFirst("name");
     String key = values.getFirst("key").replaceAll(" ", "");
     String description = values.getFirst("description");
     String isNewVersionString = values.getFirst("newversion");
     String newVersionComment = null;

     ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(), key);
     if (modelKeyInfo.isKeyAlreadyExists()) {
         throw new BadRequestException("Model with provided key already exists " + key);
     }

     boolean newVersion = false;
     if (forceNewVersion) {
         newVersion = true;
         newVersionComment = values.getFirst("comment");
     } else {
         if (isNewVersionString != null) {
             newVersion = "true".equals(isNewVersionString);
             newVersionComment = values.getFirst("comment");
         }
     }

     String json = values.getFirst("json_xml");

     try {
ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(json);

ObjectNode propertiesNode = (ObjectNode) editorJsonNode.get("properties");
String processId = key;
propertiesNode.put("process_id", processId);
propertiesNode.put("name", name);
if (StringUtils.isNotEmpty(description)) {
	propertiesNode.put("documentation", description);
}
editorJsonNode.set("properties", propertiesNode);
         model = modelService.saveModel(model.getId(), name, key, description, editorJsonNode.toString(), newVersion,
                 newVersionComment, SecurityUtils.getCurrentUserObject());
         return new ModelRepresentation(model);

     } catch (Exception e) {
         LOGGER.error("Error saving model {}", model.getId(), e);
         throw new BadRequestException("Process model could not be saved " + model.getId());
     }
 }