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

The following examples show how to use javax.ws.rs.core.MultivaluedMap#keySet() . 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: Pair.java    From everrest with Eclipse Public License 2.0 7 votes vote down vote up
public static Pair[] fromMap(MultivaluedMap<String, Object> source) {
    if (!(source == null || source.isEmpty())) {
        final List<Pair> list = new ArrayList<>();
        for (String key : source.keySet()) {
            List<Object> values = source.get(key);
            if (!(values == null || values.isEmpty())) {
                for (Object v : values) {
                    list.add(Pair.of(key, HeaderHelper.getHeaderAsString(v)));
                }
            } else {
                list.add(Pair.of(key, null));
            }
        }
        return list.toArray(new Pair[list.size()]);
    }
    return new Pair[0];
}
 
Example 2
Source File: CaselessMultivaluedMap.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean equalsIgnoreValueOrder(MultivaluedMap<String, T> otherMap) {
    if (this == otherMap) {
        return true;
    }
    Set<String> myKeys = keySet();
    Set<String> otherKeys = otherMap.keySet();
    if (!myKeys.equals(otherKeys)) {
        return false;
    }
    for (Entry<String, List<T>> e : entrySet()) {
        List<T> myValues = e.getValue();
        List<T> otherValues = otherMap.get(e.getKey());
        if (myValues != null || otherValues != null) {
            if (myValues != null) {
                if (myValues.size() != otherValues.size()) {
                    return false;
                }
                for (T value : myValues) {
                    if (!otherValues.contains(value)) {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
    }
    return true;
}
 
Example 3
Source File: HttpHeadersMethodsResource.java    From tomee with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/requestheaders")
public String getHeaders(@Context HttpHeaders headers, @QueryParam("name") String headerName) {
    final MultivaluedMap<String, String> requestHeaders = headers.getRequestHeaders();
    final List<String> keys = new ArrayList<String>(requestHeaders.keySet());
    Collections.sort(keys);
    final StringBuilder sb = new StringBuilder("requestheaders:");
    for (final String k : keys) {
        sb.append(k).append("=");
        List<String> values = requestHeaders.get(k);
        if (values != null) {
            values = new ArrayList<String>(values);
            Collections.sort(values);
            sb.append(values).append(":");
        }
    }
    return sb.toString();
}
 
Example 4
Source File: RestResponse.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get the values of a response header.
 * It returns null if no header is found with the provided name.
 *
 * @param name the header name.
 *  It is case-insensitive according to HTTP/1.1 specification (rfc2616#sec4.2)
 * @return the header values
 */
@PublicAtsApi
public String[] getHeaderValues( String name ) {

    MultivaluedMap<String, Object> respHeaders = response.getHeaders();
    for (String hName : respHeaders.keySet()) {
        if (hName.equalsIgnoreCase(name)) {
            List<String> values = new ArrayList<String>();
            for (Object valueObject : respHeaders.get(name)) {
                values.add(valueObject.toString());
            }
            return values.toArray(new String[values.size()]);
        }
    }

    return null;
}
 
Example 5
Source File: Tracing.java    From opentracing-tutorial with Apache License 2.0 6 votes vote down vote up
public static Span startServerSpan(Tracer tracer, javax.ws.rs.core.HttpHeaders httpHeaders, String operationName) {
    // format the headers for extraction
    MultivaluedMap<String, String> rawHeaders = httpHeaders.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<String, String>();
    for (String key : rawHeaders.keySet()) {
        headers.put(key, rawHeaders.get(key).get(0));
    }

    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(headers));
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(operationName);
        } else {
            spanBuilder = tracer.buildSpan(operationName).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(operationName);
    }
    // TODO could add more tags like http.url
    return spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start();
}
 
Example 6
Source File: RestUtil.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> extractRequestHeaders(final javax.ws.rs.core.HttpHeaders httpHeaders) {
  final MultivaluedMap<String, String> headers = httpHeaders.getRequestHeaders();
  Map<String, String> headerMap = new HashMap<String, String>();

  for (final String key : headers.keySet()) {
    List<String> header = httpHeaders.getRequestHeader(key);
    if (header != null && !header.isEmpty()) {
      /*
       * consider first header value only
       * avoid using jax-rs 2.0 (getHeaderString())
       */
      String value = header.get(0);
      if (value != null && !"".equals(value)) {
        headerMap.put(key, value);
      }
    }

  }
  return headerMap;
}
 
Example 7
Source File: QueryParametersImpl.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public MultivaluedMap<String,String> getUnknownParameters(MultivaluedMap<String,String> allQueryParameters) {
    MultivaluedMap<String,String> p = new MultivaluedMapImpl<String,String>();
    for (String key : allQueryParameters.keySet()) {
        if (!KNOWN_PARAMS.contains(key)) {
            for (String value : allQueryParameters.get(key)) {
                p.add(key, value);
            }
        }
    }
    return p;
}
 
Example 8
Source File: InvocationBuilderImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}*/
@Override
public void filter(ClientRequestContext context) throws IOException {
    MultivaluedMap<String, Object> headers = context.getHeaders();
    StringBuilder entity = new StringBuilder();
    for (String key : headers.keySet()) {
        entity.append(key).append('=').append(headers.getFirst(key)).append(';');
    }
    context.abortWith(Response.ok(entity.toString()).build());
}
 
Example 9
Source File: JwtRequestCodeGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getRequest() {
    MultivaluedMap<String, String> map = super.toMap();
    JwtClaims claims = new JwtClaims();
    if (issuer != null) {
        claims.setIssuer(issuer);
    }
    for (String key : map.keySet()) {
        claims.setClaim(key, map.getFirst(key));
    }
    return joseProducer.processJwt(new JwtToken(claims), clientSecret);
}
 
Example 10
Source File: RestService.java    From dexter with Apache License 2.0 5 votes vote down vote up
private DexterLocalParams getLocalParams(UriInfo ui) {
	MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
	DexterLocalParams params = new DexterLocalParams();
	for (String key : queryParams.keySet()) {
		params.addParam(key, queryParams.getFirst(key));
	}
	return params;
}
 
Example 11
Source File: AuditLogFilter.java    From helix with Apache License 2.0 5 votes vote down vote up
private List<String> getHeaders(MultivaluedMap<String, String> headersMap) {
  List<String> headers = new ArrayList<>();
  for (String key : headersMap.keySet()) {
    headers.add(key + ":" + headersMap.get(key));
  }

  return headers;
}
 
Example 12
Source File: RestUtil.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> convertToSinglevaluedMap(final MultivaluedMap<String, String> multi) {
  final Map<String, String> single = new HashMap<String, String>();

  for (final String key : multi.keySet()) {
    final String value = multi.getFirst(key);
    single.put(key, value);
  }

  return single;
}
 
Example 13
Source File: TestApplicationResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML_UTF_8)
@Path("/{action}")
public String post(@PathParam("action") String action, MultivaluedMap<String, String> formParams) {
    String title = "APP_REQUEST";
    if (action.equals("auth")) {
        title = "AUTH_RESPONSE";
    } else if (action.equals("logout")) {
        title = "LOGOUT_REQUEST";
    }

    StringBuilder sb = new StringBuilder();
    sb.append("<html><head><title>" + title + "</title></head><body>");

    sb.append("<b>Form parameters: </b><br>");
    for (String paramName : formParams.keySet()) {
        sb.append(paramName).append(": ").append("<span id=\"")
                .append(paramName).append("\">")
                .append(HtmlUtils.escapeAttribute(formParams.getFirst(paramName)))
                .append("</span><br>");
    }
    sb.append("<br>");

    UriBuilder base = UriBuilder.fromUri("/auth");
    sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>");

    sb.append("</body></html>");
    return sb.toString();
}
 
Example 14
Source File: TestSamlApplicationResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@POST
@Produces(MediaType.TEXT_HTML_UTF_8)
@Path("/{action}")
public String post(@PathParam("action") String action) {
    String title = "APP_REQUEST";
    if (action.equals("auth")) {
        title = "AUTH_RESPONSE";
    } else if (action.equals("logout")) {
        title = "LOGOUT_REQUEST";
    }

    StringBuilder sb = new StringBuilder();
    sb.append("<html><head><title>" + title + "</title></head><body>");

    sb.append("<b>Form parameters: </b><br>");
    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    MultivaluedMap<String, String> formParams = request.getDecodedFormParameters();
    for (String paramName : formParams.keySet()) {
        sb.append(paramName).append(": ").append("<span id=\"").append(paramName).append("\">").append(formParams.getFirst(paramName)).append("</span><br>");
    }
    sb.append("<br>");

    UriBuilder base = UriBuilder.fromUri("/auth");
    sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>");

    sb.append("</body></html>");
    return sb.toString();
}
 
Example 15
Source File: ProfileBean.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ProfileBean(UpdateProfileContext user, MultivaluedMap<String, String> formData) {
    this.user = user;
    this.formData = formData;

    Map<String, List<String>> modelAttrs = user.getAttributes();
    if (modelAttrs != null) {
        for (Map.Entry<String, List<String>> attr : modelAttrs.entrySet()) {
            List<String> attrValue = attr.getValue();
            if (attrValue != null && attrValue.size() > 0) {
                attributes.put(attr.getKey(), attrValue.get(0));
            }

            if (attrValue != null && attrValue.size() > 1) {
                logger.warnf("There are more values for attribute '%s' of user '%s' . Will display just first value", attr.getKey(), user.getUsername());
            }
        }
    }
    if (formData != null) {
        for (String key : formData.keySet()) {
            if (key.startsWith("user.attributes.")) {
                String attribute = key.substring("user.attributes.".length());
                attributes.put(attribute, formData.getFirst(key));
            }
        }
    }

}
 
Example 16
Source File: WSUtils.java    From streamline with Apache License 2.0 5 votes vote down vote up
public static List<QueryParam> buildQueryParameters(MultivaluedMap<String, String> params) {
    if (params == null || params.isEmpty()) {
        return Collections.emptyList();
    }

    List<QueryParam> queryParams = new ArrayList<>();
    for (String param : params.keySet()) {
        queryParams.add(new QueryParam(param, params.getFirst(param)));
    }
    return queryParams;
}
 
Example 17
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 18
Source File: AmforeasUtils.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates a HashMap with the first value of a MultivaluedMap because working with this "maps" is a PITA.
 * @param mv the MultivaluedMap with the keys and values
 * @return a Map (Hash) with the first value corresponding to the key.
 */
public static Map<String, String> hashMapOf (final MultivaluedMap<String, String> mv) {
    if (mv == null)
        throw new IllegalArgumentException("Invalid null argument");

    Map<String, String> map = new HashMap<String, String>();
    for (String k : mv.keySet()) {
        String v = mv.getFirst(k);
        if (StringUtils.isNotEmpty(v))
            map.put(k, v);
    }
    return map;
}
 
Example 19
Source File: QueryParams.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
public void setParams(final MultivaluedMap<String, String> formParams) {
    this.params = new HashMap<String,String>(); // clear the params first.
    for(String k : formParams.keySet()){
        String v = formParams.getFirst(k);
        if(v != null)
            this.params.put(k, v);
    }
}
 
Example 20
Source File: ElastistorUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public Object executeCommand(String command, MultivaluedMap<String, String> params, Object responeObj) throws Throwable {

            if (!initialized) {
                throw new IllegalStateException("Error : ElastiCenterClient is not initialized.");
            }

            if (command == null || command.trim().isEmpty()) {
                throw new InvalidParameterException("No command to execute.");
            }

            try {
                ClientConfig config = new DefaultClientConfig();
                Client client = Client.create(config);
                WebResource webResource = client.resource(UriBuilder.fromUri(restprotocol + elastiCenterAddress + restpath).build());

                MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
                queryParams.add(queryparamapikey, apiKey);
                queryParams.add(queryparamresponse, responseType);

                queryParams.add(queryparamcommand, command);

                if (null != params) {
                    for (String key : params.keySet()) {
                        queryParams.add(key, params.getFirst(key));
                    }
                }
                if (debug) {
                    System.out.println("Command Sent " + command + " : " + queryParams);
                }
                ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

                if (response.getStatus() >= 300) {
                    if (debug)
                        System.out.println("ElastiCenter returned error code : " + response.getStatus());
                    if (401 == response.getStatus()) {
                        throw new InvalidCredentialsException("Please specify a valid API Key.");
                    } else if (431 == response.getStatus()) {
                        throw new InvalidParameterException(response.getHeaders().getFirst("X-Description"));
                    } else if (432 == response.getStatus()) {
                        throw new InvalidParameterException(command + " does not exist on the ElastiCenter server.  Please specify a valid command or contact your ElastiCenter Administrator.");
                    } else {
                        throw new ServiceUnavailableException("Internal Error. Please contact your ElastiCenter Administrator.");
                    }
                } else if (null != responeObj) {
                    String jsonResponse = response.getEntity(String.class);
                    if (debug) {
                        System.out.println("Command Response : " + jsonResponse);
                    }
                    Gson gson = new Gson();
                    return gson.fromJson(jsonResponse, responeObj.getClass());
                } else {
                    return "Success";
                }
            } catch (Throwable t) {
                throw t;
            }
        }