Java Code Examples for javax.ws.rs.core.MultivaluedMap#remove()

The following examples show how to use javax.ws.rs.core.MultivaluedMap#remove() . 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: QueryExecutorBeanTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testBeginDateAfterEndDate() throws Exception {
    final Date beginDate = new Date(2018, 1, 2);
    final Date endDate = new Date(2018, 1, 1);
    
    final MultivaluedMap<String,String> queryParameters = createNewQueryParameterMap();
    queryParameters.remove(QueryParameters.QUERY_BEGIN);
    queryParameters.remove(QueryParameters.QUERY_END);
    queryParameters.putSingle(QueryParameters.QUERY_BEGIN, QueryParametersImpl.formatDate(beginDate));
    queryParameters.putSingle(QueryParameters.QUERY_END, QueryParametersImpl.formatDate(endDate));
    
    try {
        queryParameters.putSingle(QueryParameters.QUERY_LOGIC_NAME, "EventQueryLogic");
        bean.createQuery("EventQueryLogic", queryParameters);
        fail(); // If doesn't throw exception, should fail
    } catch (BadRequestException e) {
        assertEquals(DatawaveErrorCode.BEGIN_DATE_AFTER_END_DATE.toString(), e.getCause().getMessage());
    }
}
 
Example 2
Source File: LimitParamTest.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPage () {
    MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
    params.add("page", "1");
    assertEquals(LimitParam.valueOf(params, 25).getLimit(), 25);
    assertEquals(LimitParam.valueOf(params, 25).getStart(), 0);

    params.remove("page");
    params.add("page", "2");
    assertEquals(LimitParam.valueOf(params, 25).getLimit(), 25);
    assertEquals(LimitParam.valueOf(params, 25).getStart(), 25);

    params.remove("page");
    params.add("page", "foo");
    assertEquals(LimitParam.valueOf(params, 25).getLimit(), 25);
    assertEquals(LimitParam.valueOf(params, 25).getStart(), 0);

    params.remove("page");
    params.add("page", "4");
    assertEquals(LimitParam.valueOf(params, 100).getLimit(), 100);
    assertEquals(LimitParam.valueOf(params, 100).getStart(), 300);
}
 
Example 3
Source File: ReplaceES419LanguageFilter.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
  MultivaluedMap<String, String> headers = request.getHeaders();
  if (headers.containsKey(HttpHeaders.ACCEPT_LANGUAGE)) {
    List<String> acceptLanguageValues = headers.remove(HttpHeaders.ACCEPT_LANGUAGE);

    for (int i = 0; i < acceptLanguageValues.size(); i++) {
      final String acceptLanguageValue = acceptLanguageValues.get(i);

      // replace es-419 (invalid) with es_ES (valid, hopefully good enough.)
      if (acceptLanguageValue.contains(ES_419)) {
        acceptLanguageValues.set(i, acceptLanguageValue.replace(ES_419, ES_ES));
      }
    }

    headers.put(HttpHeaders.ACCEPT_LANGUAGE, acceptLanguageValues);
  }
}
 
Example 4
Source File: UtilsTest.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testOrderParam () {
    MultivaluedMap<String, String> formParams = new MultivaluedHashMap<>();
    assertEquals(OrderParam.valueOf(formParams).toString(), "id ASC");

    assertThrows(IllegalArgumentException.class, () -> {
        formParams.add("dir", "KKK");
        OrderParam.valueOf(formParams).toString(); // throw Exception!
    });

    assertThrows(IllegalArgumentException.class, () -> {
        formParams.add("dir", "DESC");
        assertEquals(OrderParam.valueOf(formParams).toString(), "id ASC");
    });

    assertThrows(IllegalArgumentException.class, () -> {
        formParams.add("sort", "kkk");
        assertEquals(OrderParam.valueOf(formParams).toString(), "kkk DESC");
    });

    formParams.remove("dir");
    assertEquals(OrderParam.valueOf(formParams).toString(), "kkk ASC");
}
 
Example 5
Source File: QueryExecutorBeanTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
private void nullDateTestRunner(boolean nullStart, boolean nullEnd) throws Exception {
    QueryImpl q = createNewQuery();
    MultivaluedMap p = createNewQueryParameterMap();
    
    if (nullStart) {
        q.setBeginDate(null);
        p.remove(QueryParameters.QUERY_BEGIN);
        p.putSingle(QueryParameters.QUERY_BEGIN, null);
    }
    
    if (nullEnd) {
        q.setEndDate(null);
        p.remove(QueryParameters.QUERY_END);
        p.putSingle(QueryParameters.QUERY_END, null);
    }
    
    defineTestRunner(q, p);
}
 
Example 6
Source File: ResourceUtils.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String popQueryParamValue(String parameter, MultivaluedMap<String, String> queryParameters) {
	List<String> values = queryParameters.remove(parameter);
	if (values != null && values.iterator().hasNext()) {
		return values.iterator().next();
	}
	return null;
}
 
Example 7
Source File: GZIPWriterInterceptor.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException {


    MultivaluedMap<String, Object> responseHeaders = context.getHeaders();
    Object rangeHeader = responseHeaders.getFirst("Content-Range");

    // Use a custom header here
    // Some clients needs to know the content length in response headers in order to display a loading state
    // Browsers don't let programmers to change the default "Accept-Encoding" header, then we use a custom one.
    String acceptEncoding = requestHeaders.getHeaderString("x-accept-encoding");

    GZIPOutputStream gzipOutputStream = null;

    if (acceptEncoding != null && acceptEncoding.equals("identity")) {
        responseHeaders.add("Content-Encoding", "identity");
    } else if (rangeHeader == null) {
        responseHeaders.add("Content-Encoding", "gzip");
        responseHeaders.remove("Content-Length");
        gzipOutputStream = new GZIPOutputStream(context.getOutputStream(), DEFAULT_BUFFER_SIZE);
        context.setOutputStream(gzipOutputStream);
    }

    try {
        context.proceed();
    } finally {
        if (gzipOutputStream != null) {
            gzipOutputStream.finish();
        }
    }
}
 
Example 8
Source File: MCRRemoveMsgBodyFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> headers = requestContext.getHeaders();
    if (headers.containsKey(IGNORE_MESSAGE_BODY_HEADER)) {
        LOGGER.info("Found {} header. Remove request message body.", IGNORE_MESSAGE_BODY_HEADER);
        headers.remove(IGNORE_MESSAGE_BODY_HEADER);
        headers.remove(HttpHeaders.CONTENT_LENGTH);
        headers.remove("Transfer-Encoding");
        requestContext.setEntityStream(null);
    }
}
 
Example 9
Source File: WorkflowVariablesTransformer.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public Map<String, String> getWorkflowVariablesFromPathSegment(PathSegment pathSegment) {
    Map<String, String> variables = null;
    MultivaluedMap<String, String> matrixParams = pathSegment.getMatrixParameters();
    if (matrixParams != null && !matrixParams.isEmpty()) {
        // Remove any empty keys that might be mistakenly sent to the scheduler to prevent bad behaviour
        matrixParams.remove("");
        variables = Maps.newHashMap();
        for (String key : matrixParams.keySet()) {
            String value = matrixParams.getFirst(key) == null ? "" : matrixParams.getFirst(key);
            variables.put(key, value);
        }
    }
    return variables;
}
 
Example 10
Source File: Pager.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Pager instance to access the API through the specified path and query parameters.
 *
 * @param api          the AbstractApi implementation to communicate through
 * @param type         the GitLab4J type that will be contained in the List
 * @param itemsPerPage items per page
 * @param queryParams  HTTP query params
 * @param pathArgs     HTTP path arguments
 * @throws GitLabApiException if any error occurs
 */
Pager(AbstractApi api, Class<T> type, int itemsPerPage, MultivaluedMap<String, String> queryParams, Object... pathArgs) throws GitLabApiException {

    javaType = mapper.getTypeFactory().constructCollectionType(List.class, type);

    // Make sure the per_page parameter is present
    if (queryParams == null) {
        queryParams = new GitLabApiForm().withParam(PER_PAGE_PARAM, itemsPerPage).asMap();
    } else {
        queryParams.remove(PER_PAGE_PARAM);
        queryParams.add(PER_PAGE_PARAM, Integer.toString(itemsPerPage));
    }

    // Set the page param to 1
    pageParam = new ArrayList<>();
    pageParam.add("1");
    queryParams.put(PAGE_PARAM, pageParam);
    Response response = api.get(Response.Status.OK, queryParams, pathArgs);

    try {
        currentItems = mapper.readValue((InputStream) response.getEntity(), javaType);
    } catch (IOException e) {
        throw new GitLabApiException(e);
    }

    this.api = api;
    this.queryParams = queryParams;
    this.pathArgs = pathArgs;
    this.itemsPerPage = getHeaderValue(response, PER_PAGE);
    totalPages = getHeaderValue(response, TOTAL_PAGES_HEADER);
    totalItems = getHeaderValue(response, TOTAL_HEADER);
}
 
Example 11
Source File: NamespaceCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/namespaces")
@Timed
public Response listNamespaces(@Context UriInfo uriInfo,
                               @Context SecurityContext securityContext) {
  List<QueryParam> queryParams = new ArrayList<>();
  MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
  Collection<Namespace> namespaces;
  Boolean detail = false;

  if (params.isEmpty()) {
    namespaces = environmentService.listNamespaces();
  } else {
    MultivaluedMap<String, String> copiedParams = new MultivaluedHashMap<>();
    copiedParams.putAll(params);
    List<String> detailOption = copiedParams.remove("detail");
    if (detailOption != null && !detailOption.isEmpty()) {
      detail = BooleanUtils.toBooleanObject(detailOption.get(0));
    }

    queryParams = WSUtils.buildQueryParameters(copiedParams);
    namespaces = environmentService.listNamespaces(queryParams);
  }
  if (namespaces != null) {
    boolean environmentUser = SecurityUtil.hasRole(authorizer, securityContext, Roles.ROLE_ENVIRONMENT_USER);
    if (environmentUser) {
      LOG.debug("Returning all environments since user has role: {}", Roles.ROLE_ENVIRONMENT_USER);
    } else {
      namespaces = SecurityUtil.filter(authorizer, securityContext, Namespace.NAMESPACE, namespaces, READ);
    }
    return buildNamespacesGetResponse(namespaces, detail);
  }

  throw EntityNotFoundException.byFilter(queryParams.toString());
}
 
Example 12
Source File: ClusterCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * List ALL clusters or the ones matching specific query params.
 */
@GET
@Path("/clusters")
@Timed
public Response listClusters(@Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    List<QueryParam> queryParams = new ArrayList<>();
    MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
    Collection<Cluster> clusters;
    Boolean detail = false;

    if (params.isEmpty()) {
        clusters = environmentService.listClusters();
    } else {
        MultivaluedMap<String, String> copiedParams = new MultivaluedHashMap<>();
        copiedParams.putAll(params);
        List<String> detailOption = copiedParams.remove("detail");
        if (detailOption != null && !detailOption.isEmpty()) {
            detail = BooleanUtils.toBooleanObject(detailOption.get(0));
        }

        queryParams = WSUtils.buildQueryParameters(copiedParams);
        clusters = environmentService.listClusters(queryParams);
    }

    if (clusters != null) {
        boolean servicePoolUser = SecurityUtil.hasRole(authorizer, securityContext, Roles.ROLE_SERVICE_POOL_USER);
        if (servicePoolUser) {
            LOG.debug("Returning all service pools since user has role: {}", Roles.ROLE_SERVICE_POOL_USER);
        } else {
            clusters = SecurityUtil.filter(authorizer, securityContext, NAMESPACE, clusters, READ);
        }
        return buildClustersGetResponse(clusters, detail);
    }

    throw EntityNotFoundException.byFilter(queryParams.toString());
}
 
Example 13
Source File: RegistrationRecaptcha.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(ValidationContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    List<FormMessage> errors = new ArrayList<>();
    boolean success = false;
    context.getEvent().detail(Details.REGISTER_METHOD, "form");

    String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE);
    if (!Validation.isBlank(captcha)) {
        AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
        String secret = captchaConfig.getConfig().get(SITE_SECRET);

        success = validateRecaptcha(context, success, captcha, secret);
    }
    if (success) {
        context.success();
    } else {
        errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED));
        formData.remove(G_RECAPTCHA_RESPONSE);
        context.error(Errors.INVALID_REGISTRATION);
        context.validationError(formData, errors);
        context.excludeOtherErrors();
        return;


    }
}
 
Example 14
Source File: Saml2BearerAuthHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();
    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertionType = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_TYPE);
    String decodedAssertionType = assertionType != null ? HttpUtils.urlDecode(assertionType) : null;
    if (decodedAssertionType == null || !Constants.CLIENT_AUTH_SAML2_BEARER.equals(decodedAssertionType)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    String assertion = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_PARAM);

    Element token = readToken(message, assertion);
    String clientId = formData.getFirst(OAuthConstants.CLIENT_ID);
    validateToken(message, token, clientId);


    formData.remove(OAuthConstants.CLIENT_ID);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_TYPE);

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example 15
Source File: SamlFormInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();

    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertion = formData.getFirst(SAML_ELEMENT);

    handleToken(message, assertion);

    // redirect if needed
    String samlRequestURI = formData.getFirst(SAML_RELAY_STATE);
    if (samlRequestURI != null) {
        // RelayState may actually represent a reference to a transient local state
        // containing the actual REQUEST URI client was using before being redirected
        // back to IDP - at the moment assume it's URI
        UriInfoImpl ui = new UriInfoImpl(message);
        if (!samlRequestURI.startsWith(ui.getBaseUri().toString())) {
            context.abortWith(Response.status(302).location(URI.create(samlRequestURI)).build());
            return;
        }
    }
    formData.remove(SAML_ELEMENT);
    formData.remove(SAML_RELAY_STATE);

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throwFault(ex.getMessage(), ex);
    }
}
 
Example 16
Source File: WebClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces the header value with the new values.
 * @param headerName headerValues
 * @param value new values, null is equivalent to removing the header
 * @return updated WebClient
 */
public WebClient replaceHeader(String headerName, Object value) {
    MultivaluedMap<String, String> headers = getState().getRequestHeaders();
    headers.remove(headerName);
    if (value != null) {
        super.header(headerName, value);
    }
    return this;
}
 
Example 17
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
	if (logger.isDebugEnabled()) {
		logger.debug("action(AuthenticationFlowContext) - start");
	}
	MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
	List<FormMessage> errors = new ArrayList<>();
	boolean success = false;
	context.getEvent().detail(Details.AUTH_METHOD, "auth_method");

	String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE);
	if (!Validation.isBlank(captcha)) {
		AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
		String secret = captchaConfig.getConfig().get(SITE_SECRET);

		success = validateRecaptcha(context, success, captcha, secret);
	}
	if (success) {
		super.action(context);
	} else {
		errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED));
		formData.remove(G_RECAPTCHA_RESPONSE);
		// context.error(Errors.INVALID_REGISTRATION);
		// context.validationError(formData, errors);
		// context.excludeOtherErrors();
		return;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("action(AuthenticationFlowContext) - end");
	}
}
 
Example 18
Source File: LimitParamTest.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIncorrect () {
    MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
    params.add("limit", "-1");
    assertDefault(LimitParam.valueOf(params));

    params.remove("limit");
    params.add("limit", "foo");
    assertDefault(LimitParam.valueOf(params));

    params.add("offset", "-1");
    assertDefault(LimitParam.valueOf(params));

    params.remove("offset");
    params.add("offset", "foo");
    assertDefault(LimitParam.valueOf(params));

    /* with an invalid limit, the offset is still the default */
    params.remove("offset");
    params.add("offset", "10");
    assertDefault(LimitParam.valueOf(params));

    /* with an invalid offset, limit works and offset is default */
    params = new MultivaluedHashMap<>();
    params.add("limit", "10");
    params.add("offset", "foo");
    assertEquals(LimitParam.valueOf(params).getLimit(), 10);
    assertEquals(LimitParam.valueOf(params).getStart(), 0);

    /* if the limit is too big */
    params.clear();
    params.add("limit", "1001");
    assertEquals(LimitParam.valueOf(params).getLimit(), 1000);
}
 
Example 19
Source File: RegistrationUserCreation.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void validate(ValidationContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    List<FormMessage> errors = new ArrayList<>();
    context.getEvent().detail(Details.REGISTER_METHOD, "form");

    String email = formData.getFirst(Validation.FIELD_EMAIL);
    String username = formData.getFirst(RegistrationPage.FIELD_USERNAME);
    context.getEvent().detail(Details.USERNAME, username);
    context.getEvent().detail(Details.EMAIL, email);

    String usernameField = RegistrationPage.FIELD_USERNAME;
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        context.getEvent().detail(Details.USERNAME, email);

        if (Validation.isBlank(email)) {
            errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.MISSING_EMAIL));
        } else if (!Validation.isEmailValid(email)) {
            errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.INVALID_EMAIL));
            formData.remove(Validation.FIELD_EMAIL);
        }
        if (errors.size() > 0) {
            context.error(Errors.INVALID_REGISTRATION);
            context.validationError(formData, errors);
            return;
        }
        if (email != null && !context.getRealm().isDuplicateEmailsAllowed() && context.getSession().users().getUserByEmail(email, context.getRealm()) != null) {
            context.error(Errors.EMAIL_IN_USE);
            formData.remove(Validation.FIELD_EMAIL);
            errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.EMAIL_EXISTS));
            context.validationError(formData, errors);
            return;
        }
    } else {
        if (Validation.isBlank(username)) {
            context.error(Errors.INVALID_REGISTRATION);
            errors.add(new FormMessage(RegistrationPage.FIELD_USERNAME, Messages.MISSING_USERNAME));
            context.validationError(formData, errors);
            return;
        }

        if (context.getSession().users().getUserByUsername(username, context.getRealm()) != null) {
            context.error(Errors.USERNAME_IN_USE);
            errors.add(new FormMessage(usernameField, Messages.USERNAME_EXISTS));
            formData.remove(Validation.FIELD_USERNAME);
            context.validationError(formData, errors);
            return;
        }

    }
    context.success();
}
 
Example 20
Source File: JwtBearerAuthHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();
    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertionType = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_TYPE);
    String decodedAssertionType = assertionType != null ? HttpUtils.urlDecode(assertionType) : null;
    if (decodedAssertionType == null || !Constants.CLIENT_AUTH_JWT_BEARER.equals(decodedAssertionType)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    String assertion = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    if (assertion == null) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    String clientId = formData.getFirst(OAuthConstants.CLIENT_ID);

    Client client = null;
    if (clientId != null && clientProvider != null) {
        client = clientProvider.getClient(clientId);
        if (client == null) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
        message.put(Client.class, client);
    }
    JwtToken token = super.getJwtToken(assertion, client);

    String subjectName = (String)token.getClaim(JwtConstants.CLAIM_SUBJECT);
    if (clientId != null && !clientId.equals(subjectName)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    message.put(OAuthConstants.CLIENT_ID, subjectName);

    formData.remove(OAuthConstants.CLIENT_ID);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_TYPE);

    SecurityContext securityContext = configureSecurityContext(token);
    if (securityContext != null) {
        JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
    }

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}