Beispiel #1
0
  private static MultivaluedMap<ParameterType, Parameter> getParametersInfo(
      Method m, Object[] params, OperationResourceInfo ori) {
    MultivaluedMap<ParameterType, Parameter> map = new MetadataMap<ParameterType, Parameter>();

    List<Parameter> parameters = ori.getParameters();
    if (parameters.size() == 0) {
      return map;
    }
    int requestBodyParam = 0;
    int multipartParam = 0;
    for (Parameter p : parameters) {
      if (isIgnorableParameter(m, p)) {
        continue;
      }
      if (p.getType() == ParameterType.REQUEST_BODY) {
        requestBodyParam++;
        if (getMultipart(ori, p.getIndex()) != null) {
          multipartParam++;
        }
      }
      map.add(p.getType(), p);
    }

    if (map.containsKey(ParameterType.REQUEST_BODY)) {
      if (requestBodyParam > 1 && requestBodyParam != multipartParam) {
        reportInvalidResourceMethod(ori.getMethodToInvoke(), "SINGLE_BODY_ONLY");
      }
      if (map.containsKey(ParameterType.FORM)) {
        reportInvalidResourceMethod(ori.getMethodToInvoke(), "ONLY_FORM_ALLOWED");
      }
    }
    return map;
  }
Beispiel #2
0
 private void validate(final MultivaluedMap<String, String> data) throws NullPointerException {
   if (!data.containsKey("From")) {
     throw new NullPointerException("From can not be null.");
   } else if (!data.containsKey("To")) {
     throw new NullPointerException("To can not be null.");
   } else if (!data.containsKey("Url")) {
     throw new NullPointerException("Url can not be null.");
   }
 }
Beispiel #3
0
 public KeyRecoveryRequest(MultivaluedMap<String, String> form) {
   if (form.containsKey(KEY_ID)) {
     attributes.put(KEY_ID, form.getFirst(KEY_ID));
   }
   if (form.containsKey(REQUEST_ID)) {
     attributes.put(REQUEST_ID, form.getFirst(REQUEST_ID));
   }
   attributes.put(TRANS_WRAPPED_SESSION_KEY, form.getFirst(TRANS_WRAPPED_SESSION_KEY));
   attributes.put(SESSION_WRAPPED_PASSPHRASE, form.getFirst(SESSION_WRAPPED_PASSPHRASE));
   attributes.put(NONCE_DATA, form.getFirst(NONCE_DATA));
   attributes.put(CERTIFICATE, form.getFirst(CERTIFICATE));
   attributes.put(PASSPHRASE, form.getFirst(PASSPHRASE));
   setClassName(getClass().getName());
 }
Beispiel #4
0
 private void setResponseDate(MultivaluedMap<String, Object> headers, boolean firstTry) {
   if (!firstTry || headers.containsKey(HttpHeaders.DATE)) {
     return;
   }
   SimpleDateFormat format = HttpUtils.getHttpDateFormat();
   headers.putSingle(HttpHeaders.DATE, format.format(new Date()));
 }
Beispiel #5
0
  @Override
  public void writeTo(
      Object t,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    RenderingContext context = (RenderingContext) ctx.get();
    if (context instanceof WebRenderingContext) {
      ((WebRenderingContext) context).setup(requests.get());
    }

    ParsedTemplate template = cache.getTemplate(context, type);

    // FIXME: Should we really do this?
    httpHeaders.putSingle("Content-Type", "text/html; charset=utf-8");

    if (!httpHeaders.containsKey("Expires")) {
      httpHeaders.putSingle("Expires", -1);
    }

    TemplateOutputStream out = new HtmlTemplateOutput(entityStream);
    renderer.render(context, template, t, out);
    out.close();
  }
 private String getParamString(MultivaluedMap<String, String> params, String param) {
   if (params.containsKey(param)) {
     return params.getFirst(param);
   } else {
     return "";
   }
 }
  /**
   * Validates this descriptor based on the passed query parameters.
   *
   * @param queryParams parameters to validate against
   * @throws ParameterValidationException when a validation fails
   */
  public void validate(MultivaluedMap<String, String> queryParams)
      throws ParameterValidationException {
    if (!queryParams.containsKey(name)) {
      // Check for mandatory property
      if (isMandatory) {
        throw new ParameterValidationException(name, i18n.tr("Required parameter."));
      }
      // If this parameter was not specified and is
      // not mandatory there is nothing to validate.
      return;
    }

    if (this.mustBeInt) {
      validateInteger(queryParams.get(name));
    }

    if (this.dateFormat != null && !this.dateFormat.isEmpty()) {
      validateDate(queryParams.get(name));
    }

    if (this.mustBeTimeZone) {
      validateTimeZone(queryParams.get(name));
    }

    if (this.validators.size() > 0) {
      verifyValidatorsPass(queryParams.get(name));
    }

    verifyMustHaves(queryParams);
    verifyMustNotHaves(queryParams);
  }
 protected URI getUrl(final String name, final MultivaluedMap<String, String> data) {
   URI uri = null;
   if (data.containsKey(name)) {
     uri = URI.create(data.getFirst(name));
   }
   return uri;
 }
 protected Sid getSid(final String name, final MultivaluedMap<String, String> data) {
   Sid sid = null;
   if (data.containsKey(name)) {
     sid = new Sid(data.getFirst(name));
   }
   return sid;
 }
Beispiel #10
0
 protected String getMethod(final String name, final MultivaluedMap<String, String> data) {
   String method = "POST";
   if (data.containsKey(name)) {
     method = data.getFirst(name);
   }
   return method;
 }
Beispiel #11
0
 protected String getApiVersion(final MultivaluedMap<String, String> data) {
   String apiVersion = defaultApiVersion;
   if (data != null && data.containsKey("ApiVersion")) {
     apiVersion = data.getFirst("ApiVersion");
   }
   return apiVersion;
 }
Beispiel #12
0
 private Integer getTimeout(final MultivaluedMap<String, String> data) {
   Integer result = 60;
   if (data.containsKey("Timeout")) {
     result = Integer.parseInt(data.getFirst("Timeout"));
   }
   return result;
 }
 private void verifyMustHaves(MultivaluedMap<String, String> queryParams) {
   for (String paramToCheck : this.mustHaveParams) {
     if (!queryParams.containsKey(paramToCheck)) {
       throw new ParameterValidationException(
           name, i18n.tr("Parameter must be used with {0}.", paramToCheck));
     }
   }
 }
  /**
   * Mocks MultivaluedMap for post containin id
   *
   * @param id Id of post
   * @return Map containing id
   */
  protected static MultivaluedMap<String, String> createIdPost(String id) {
    @SuppressWarnings("unchecked")
    MultivaluedMap<String, String> map = mock(MultivaluedMap.class);

    when(map.containsKey(FORM_ID)).thenReturn(true);

    when(map.getFirst(FORM_ID)).thenReturn(id);
    return map;
  }
  @Test
  public void testParseQueryString() throws UnsupportedEncodingException {
    String input = "a=b&a=c%2F&z=&x";
    MultivaluedMap<String, String> map = interceptor.extractParameters(input);
    assertTrue(map.containsKey("a"));
    assertTrue(map.containsKey("x"));
    assertTrue(map.containsKey("z"));

    List<String> a = map.get("a");
    assertTrue(a.contains("b"));
    assertTrue(a.contains("c/"));

    List<String> x = map.get("x");
    assertTrue(x.contains(""));

    List<String> z = map.get("z");
    assertTrue(z.contains(""));
  }
  @PUT
  @Path("{enlaceId}")
  @Produces(MediaType.TEXT_XML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public ResponseMessage update(
      @PathParam("enlaceId") String enlaceId, MultivaluedMap<String, String> params)
      throws RegistroNoEncontradoException, ParametrosObligatoriosException {
    Enlace enlace = Enlace.getEnlace(Long.parseLong(enlaceId));

    enlace.setOrden(Long.parseLong(getParamString(params, "orden")));
    if (params.containsKey("ocw")) {
      enlace.setOcw(true);
    } else {
      enlace.setOcw(false);
    }

    Set<EnlaceIdioma> enlacesIdiomas = enlace.getEnlacesIdiomas();
    List<Idioma> idiomas = Idioma.getIdiomasEdicion();

    boolean exists = false;
    for (Idioma idioma : idiomas) {
      String url = getParamString(params, "url__" + idioma.getAcronimo().toLowerCase());
      String nombre = getParamString(params, "nombre__" + idioma.getAcronimo().toLowerCase());
      String descripcion =
          getParamString(params, "descripcion__" + idioma.getAcronimo().toLowerCase());

      for (EnlaceIdioma enlaceIdioma : enlacesIdiomas) {
        if (enlaceIdioma.getIdioma().getAcronimo().equals(idioma.getAcronimo())) {
          enlaceIdioma.setUrl(url);
          enlaceIdioma.setNombre(nombre);
          enlaceIdioma.setDescripcion(descripcion);
          exists = true;
          break;
        }
      }
      if (!exists) {
        if (!url.equals("") || !nombre.equals("") || !descripcion.equals("")) {
          EnlaceIdioma enlaceIdioma = new EnlaceIdioma();
          enlaceIdioma.setUrl(url);
          enlaceIdioma.setNombre(nombre);
          enlaceIdioma.setDescripcion(descripcion);
          enlaceIdioma.setIdioma(idioma);
          enlaceIdioma.setEnlace(enlace);
          enlacesIdiomas.add(enlaceIdioma);
        }
      }
      exists = false;
    }

    enlace.setEnlacesIdiomas(enlacesIdiomas);

    enlace.compruebaCamposObligatorios(idiomas.get(0).getAcronimo());

    enlace.update();

    return new ResponseMessage(true);
  }
Beispiel #17
0
 protected boolean getHasVoiceCallerIdLookup(final MultivaluedMap<String, String> data) {
   boolean hasVoiceCallerIdLookup = false;
   if (data.containsKey("VoiceCallerIdLookup")) {
     final String value = data.getFirst("VoiceCallerIdLookup");
     if ("true".equalsIgnoreCase(value)) {
       return true;
     }
   }
   return hasVoiceCallerIdLookup;
 }
Beispiel #18
0
 protected String removeParameter(
     final MultivaluedMap<java.lang.String, java.lang.String> params, final String key) {
   if (params.containsKey(key)) {
     final String value = params.getFirst(key);
     params.remove(key);
     return value;
   } else {
     return null;
   }
 }
Beispiel #19
0
 @Override
 public Identity identity() throws IOException {
   final MultivaluedMap<String, String> headers = this.resource.httpHeaders().getRequestHeaders();
   Identity identity = Identity.ANONYMOUS;
   if (headers.containsKey(Auth.HEADER_URN) && headers.containsKey(Auth.HEADER_TOKEN)) {
     final URN urn = URN.create(headers.getFirst(Auth.HEADER_URN));
     final User user = this.base.user(urn);
     if (!user.exists()) {
       throw new WebApplicationException(
           Response.status(HttpURLConnection.HTTP_UNAUTHORIZED).build());
     }
     final String token = headers.getFirst(Auth.HEADER_TOKEN);
     if (!user.token().equals(token)) {
       throw new WebApplicationException(
           Response.status(HttpURLConnection.HTTP_UNAUTHORIZED).build());
     }
     identity = new Identity.Simple(urn, "http", URI.create("#"));
   }
   return identity;
 }
  public Link getLocationLink() {
    if (location != null) return location;
    if (!headers.containsKey("Location")) return null;
    String header = headers.getFirst("Location");

    location = new Link();
    location.setHref(header);
    location.setExecutor(executor);

    return location;
  }
Beispiel #21
0
  @GET
  @Produces({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF})
  public Response get(final @Context UriInfo uriInfo) {
    MultivaluedMap<String, String> params = uriInfo.getQueryParameters();

    servlet.getMetrics().incrementRequests(1);
    try {
      CellSetModel model = new CellSetModel();
      for (String rk : params.get(ROW_KEYS_PARAM_NAME)) {
        RowSpec rowSpec = new RowSpec(rk);

        if (this.versions != null) {
          rowSpec.setMaxVersions(this.versions);
        }
        ResultGenerator generator =
            ResultGenerator.fromRowSpec(
                this.tableResource.getName(),
                rowSpec,
                null,
                !params.containsKey(NOCACHE_PARAM_NAME));
        Cell value = null;
        RowModel rowModel = new RowModel(rk);
        if (generator.hasNext()) {
          while ((value = generator.next()) != null) {
            rowModel.addCell(
                new CellModel(
                    CellUtil.cloneFamily(value),
                    CellUtil.cloneQualifier(value),
                    value.getTimestamp(),
                    CellUtil.cloneValue(value)));
          }
          model.addRow(rowModel);
        } else {
          LOG.trace("The row : " + rk + " not found in the table.");
        }
      }

      if (model.getRows().size() == 0) {
        // If no rows found.
        servlet.getMetrics().incrementFailedGetRequests(1);
        return Response.status(Response.Status.NOT_FOUND)
            .type(MIMETYPE_TEXT)
            .entity("No rows found." + CRLF)
            .build();
      } else {
        servlet.getMetrics().incrementSucessfulGetRequests(1);
        return Response.ok(model).build();
      }
    } catch (Exception e) {
      servlet.getMetrics().incrementFailedGetRequests(1);
      return processException(e);
    }
  }
 private void checkSecurityContextEnd(
     ContainerRequestContext rc, MultivaluedMap<String, String> requestParams) {
   String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
   SecurityContext sc = rc.getSecurityContext();
   if (sc == null || sc.getUserPrincipal() == null) {
     if (codeParam == null
         && requestParams.containsKey(OAuthConstants.ERROR_KEY)
         && !faultAccessDeniedResponses) {
       if (!applicationCanHandleAccessDenied) {
         String error = requestParams.getFirst(OAuthConstants.ERROR_KEY);
         rc.abortWith(Response.ok(new AccessDeniedResponse(error)).build());
       }
     } else {
       throw ExceptionUtils.toNotAuthorizedException(null, null);
     }
   }
 }
 public LinkHeader getLinkHeader() {
   if (linkHeader != null) return linkHeader;
   linkHeader = new LinkHeader();
   if (!headers.containsKey("Link")) {
     return linkHeader;
   }
   List<String> links = headers.get("Link");
   LinkHeaderDelegate delegate = new LinkHeaderDelegate();
   for (String link : links) {
     LinkHeader tmp = delegate.fromString(link);
     linkHeader.getLinks().addAll(tmp.getLinks());
     linkHeader.getLinksByRelationship().putAll(tmp.getLinksByRelationship());
     linkHeader.getLinksByTitle().putAll(tmp.getLinksByTitle());
   }
   for (Link link : linkHeader.getLinks()) {
     link.setExecutor(executor);
   }
   return linkHeader;
 }
  @POST
  @Produces(MediaType.TEXT_XML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public UIEntity insertEnlace(MultivaluedMap<String, String> params)
      throws ParametrosObligatoriosException {
    Enlace enlace = new Enlace();
    enlace.setOrden(Long.parseLong(getParamString(params, "orden")));
    if (params.containsKey("ocw")) {
      enlace.setOcw(true);
    }

    Set<EnlaceIdioma> enlacesIdiomas = new HashSet<EnlaceIdioma>();

    List<Idioma> idiomas = Idioma.getIdiomasEdicion();

    for (Idioma idioma : idiomas) {
      String url = getParamString(params, "url__" + idioma.getAcronimo().toLowerCase());
      String nombre = getParamString(params, "nombre__" + idioma.getAcronimo().toLowerCase());
      String descripcion =
          getParamString(params, "descripcion__" + idioma.getAcronimo().toLowerCase());

      if (!url.equals("") || !nombre.equals("") || !descripcion.equals("")) {
        EnlaceIdioma enlaceIdioma = new EnlaceIdioma();
        enlaceIdioma.setUrl(url);
        enlaceIdioma.setNombre(nombre);
        enlaceIdioma.setDescripcion(descripcion);
        enlaceIdioma.setIdioma(idioma);
        enlaceIdioma.setEnlace(enlace);
        enlacesIdiomas.add(enlaceIdioma);
      }
    }
    enlace.setEnlacesIdiomas(enlacesIdiomas);

    enlace.compruebaCamposObligatorios(idiomas.get(0).getAcronimo());

    enlace = enlace.insert();

    UIEntity entity = UIEntity.toUI(enlace);

    return entity;
  }
Beispiel #25
0
  /**
   * Obtain the specified action property. An action property can either contain a simple value or
   * reference a link property. If it is the latter it will obtain the referenced value stored in
   * the link property. e.g. GetEntities filter=myfilter and myfilter="CreditAcctNo eq '{Acc}'",
   * Acc="CreditAcctNo" => filter=CreditAcctNo eq '{CreditAcctNo}'
   *
   * @param propertyName Action property name
   * @param actionProperties Action properties
   * @param queryParameters Query parameters (keys)
   * @return Action property string
   */
  protected static String getActionProperty(
      String propertyName,
      Properties actionProperties,
      MultivaluedMap<String, String> queryParameters) {
    Object propObj = actionProperties.get(propertyName);
    if (propObj != null && propObj instanceof ActionPropertyReference) {
      ActionPropertyReference propRef = (ActionPropertyReference) propObj;
      Set<String> queryParamKeys = queryParameters.keySet();

      if (queryParameters.containsKey(propRef.getKey())) {
        return queryParameters.getFirst(propRef.getKey());
      }

      String key = "_";
      for (String queryParamKey : queryParamKeys) {
        if (!queryParamKey.startsWith("$")) { // Do not consider $filter, $select, etc.
          key += "_" + queryParamKey;
        }
      }
      return propRef.getProperty(key);
    } else {
      return actionProperties.get(propertyName).toString(); // e.g. fld eq '{code}'
    }
  }
 @Override
 public boolean containsKey(Object key) {
   return delegate.containsKey(key);
 }
  @POST
  @Path("/")
  @Consumes("application/x-www-form-urlencoded")
  @Produces("application/json")
  public Response issueAccessToken(
      @Context HttpServletRequest request, MultivaluedMap<String, String> paramMap)
      throws OAuthSystemException {

    try {
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
      carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
      carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

      HttpServletRequestWrapper httpRequest = new OAuthRequestWrapper(request, paramMap);

      if (log.isDebugEnabled()) {
        logAccessTokenRequest(httpRequest);
      }

      // extract the basic auth credentials if present in the request and use for
      // authentication.
      if (request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ) != null) {

        try {
          String[] clientCredentials =
              EndpointUtil.extractCredentialsFromAuthzHeader(
                  request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ));

          // The client MUST NOT use more than one authentication method in each request
          if (paramMap.containsKey(OAuth.OAUTH_CLIENT_ID)
              && paramMap.containsKey(OAuth.OAUTH_CLIENT_SECRET)) {
            return handleBasicAuthFailure();
          }

          // If a client sends an invalid base64 encoded clientid:clientsecret value, it results in
          // this
          // array to only contain 1 element. This happens on specific errors though.
          if (clientCredentials.length != 2) {
            return handleBasicAuthFailure();
          }

          // add the credentials available in Authorization header to the parameter map
          paramMap.add(OAuth.OAUTH_CLIENT_ID, clientCredentials[0]);
          paramMap.add(OAuth.OAUTH_CLIENT_SECRET, clientCredentials[1]);

        } catch (OAuthClientException e) {
          // malformed credential string is considered as an auth failure.
          log.error("Error while extracting credentials from authorization header", e);
          return handleBasicAuthFailure();
        }
      }

      try {
        CarbonOAuthTokenRequest oauthRequest = new CarbonOAuthTokenRequest(httpRequest);
        // exchange the access token for the authorization grant.
        OAuth2AccessTokenRespDTO oauth2AccessTokenResp = getAccessToken(oauthRequest);
        // if there BE has returned an error
        if (oauth2AccessTokenResp.getErrorMsg() != null) {
          // if there is an auth failure, HTTP 401 Status Code should be sent back to the client.
          if (OAuth2ErrorCodes.INVALID_CLIENT.equals(oauth2AccessTokenResp.getErrorCode())) {
            return handleBasicAuthFailure();
          } else if ("sql_error".equals(oauth2AccessTokenResp.getErrorCode())) {
            return handleSQLError();
          } else if (OAuth2ErrorCodes.SERVER_ERROR.equals(oauth2AccessTokenResp.getErrorCode())) {
            return handleServerError();
          } else {
            // Otherwise send back HTTP 400 Status Code
            OAuthResponse.OAuthErrorResponseBuilder oAuthErrorResponseBuilder =
                OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(oauth2AccessTokenResp.getErrorCode())
                    .setErrorDescription(oauth2AccessTokenResp.getErrorMsg());
            OAuthResponse response = oAuthErrorResponseBuilder.buildJSONMessage();

            ResponseHeader[] headers = oauth2AccessTokenResp.getResponseHeaders();
            ResponseBuilder respBuilder = Response.status(response.getResponseStatus());

            if (headers != null && headers.length > 0) {
              for (int i = 0; i < headers.length; i++) {
                if (headers[i] != null) {
                  respBuilder.header(headers[i].getKey(), headers[i].getValue());
                }
              }
            }

            return respBuilder.entity(response.getBody()).build();
          }
        } else {
          OAuthTokenResponseBuilder oAuthRespBuilder =
              OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                  .setAccessToken(oauth2AccessTokenResp.getAccessToken())
                  .setRefreshToken(oauth2AccessTokenResp.getRefreshToken())
                  .setExpiresIn(Long.toString(oauth2AccessTokenResp.getExpiresIn()))
                  .setTokenType(BEARER);
          oAuthRespBuilder.setScope(oauth2AccessTokenResp.getAuthorizedScopes());

          // OpenID Connect ID token
          if (oauth2AccessTokenResp.getIDToken() != null) {
            oAuthRespBuilder.setParam(OAuthConstants.ID_TOKEN, oauth2AccessTokenResp.getIDToken());
          }
          OAuthResponse response = oAuthRespBuilder.buildJSONMessage();
          ResponseHeader[] headers = oauth2AccessTokenResp.getResponseHeaders();
          ResponseBuilder respBuilder =
              Response.status(response.getResponseStatus())
                  .header(
                      OAuthConstants.HTTP_RESP_HEADER_CACHE_CONTROL,
                      OAuthConstants.HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE)
                  .header(
                      OAuthConstants.HTTP_RESP_HEADER_PRAGMA,
                      OAuthConstants.HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE);

          if (headers != null && headers.length > 0) {
            for (int i = 0; i < headers.length; i++) {
              if (headers[i] != null) {
                respBuilder.header(headers[i].getKey(), headers[i].getValue());
              }
            }
          }

          return respBuilder.entity(response.getBody()).build();
        }

      } catch (OAuthProblemException e) {
        log.error("Error while creating the Carbon OAuth token request", e);
        OAuthResponse res =
            OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .error(e)
                .buildJSONMessage();
        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
      }

    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }
  }
Beispiel #28
0
  /**
   * Updates the current state if Client method is invoked, otherwise does the remote invocation or
   * returns a new proxy if subresource method is invoked. Can throw an expected exception if
   * ResponseExceptionMapper is registered
   */
  public Object invoke(Object o, Method m, Object[] params) throws Throwable {

    Class<?> declaringClass = m.getDeclaringClass();
    if (Client.class == declaringClass
        || InvocationHandlerAware.class == declaringClass
        || Object.class == declaringClass) {
      return m.invoke(this, params);
    }
    resetResponse();
    OperationResourceInfo ori = cri.getMethodDispatcher().getOperationResourceInfo(m);
    if (ori == null) {
      reportInvalidResourceMethod(m, "INVALID_RESOURCE_METHOD");
    }

    MultivaluedMap<ParameterType, Parameter> types = getParametersInfo(m, params, ori);
    List<Parameter> beanParamsList = getParameters(types, ParameterType.BEAN);

    int bodyIndex = getBodyIndex(types, ori);

    List<Object> pathParams = getPathParamValues(m, params, types, beanParamsList, ori, bodyIndex);

    UriBuilder builder = getCurrentBuilder().clone();
    if (isRoot) {
      addNonEmptyPath(builder, ori.getClassResourceInfo().getURITemplate().getValue());
    }
    addNonEmptyPath(builder, ori.getURITemplate().getValue());

    handleMatrixes(m, params, types, beanParamsList, builder);
    handleQueries(m, params, types, beanParamsList, builder);

    URI uri = builder.buildFromEncoded(pathParams.toArray()).normalize();

    MultivaluedMap<String, String> headers = getHeaders();
    MultivaluedMap<String, String> paramHeaders = new MetadataMap<String, String>();
    handleHeaders(m, params, paramHeaders, beanParamsList, types);
    handleCookies(m, params, paramHeaders, beanParamsList, types);

    if (ori.isSubResourceLocator()) {
      ClassResourceInfo subCri = cri.getSubResource(m.getReturnType(), m.getReturnType());
      if (subCri == null) {
        reportInvalidResourceMethod(m, "INVALID_SUBRESOURCE");
      }

      MultivaluedMap<String, String> subHeaders = paramHeaders;
      if (inheritHeaders) {
        subHeaders.putAll(headers);
      }

      ClientState newState =
          getState()
              .newState(
                  uri, subHeaders, getTemplateParametersMap(ori.getURITemplate(), pathParams));
      ClientProxyImpl proxyImpl =
          new ClientProxyImpl(newState, proxyLoader, subCri, false, inheritHeaders);
      proxyImpl.setConfiguration(getConfiguration());
      return JAXRSClientFactory.createProxy(m.getReturnType(), proxyLoader, proxyImpl);
    }
    headers.putAll(paramHeaders);

    getState().setTemplates(getTemplateParametersMap(ori.getURITemplate(), pathParams));

    Object body = null;
    if (bodyIndex != -1) {
      body = params[bodyIndex];
      if (body == null) {
        bodyIndex = -1;
      }
    } else if (types.containsKey(ParameterType.FORM)) {
      body = handleForm(m, params, types, beanParamsList);
    } else if (types.containsKey(ParameterType.REQUEST_BODY)) {
      body = handleMultipart(types, ori, params);
    }

    setRequestHeaders(
        headers,
        ori,
        types.containsKey(ParameterType.FORM),
        body == null ? null : body.getClass(),
        m.getReturnType());

    return doChainedInvocation(uri, headers, ori, body, bodyIndex, null, null);
  }
Beispiel #29
0
  protected void applyQueryFilters(
      final MultivaluedMap<String, String> p, final CriteriaBuilder builder) {
    final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params.putAll(p);

    builder.distinct();
    builder.limit(DEFAULT_LIMIT);

    // not sure why we remove this, but that's what the old query filter code did, I presume there's
    // a reason  :)
    params.remove("_dc");

    if (params.containsKey("limit")) {
      builder.limit(Integer.valueOf(params.getFirst("limit")));
      params.remove("limit");
    }
    if (params.containsKey("offset")) {
      builder.offset(Integer.valueOf(params.getFirst("offset")));
      params.remove("offset");
    }
    // Is this necessary anymore? setLimitOffset() comments implies it's for Ext-JS.
    if (params.containsKey("start")) {
      builder.offset(Integer.valueOf(params.getFirst("start")));
      params.remove("start");
    }

    if (params.containsKey("orderBy")) {
      builder.orderBy(params.getFirst("orderBy"));
      params.remove("orderBy");

      if (params.containsKey("order")) {
        if ("desc".equalsIgnoreCase(params.getFirst("order"))) {
          builder.desc();
        } else {
          builder.asc();
        }
        params.remove("order");
      }
    }

    final String query = removeParameter(params, "query");
    if (query != null) builder.sql(query);

    final String matchType;
    final String match = removeParameter(params, "match");
    if (match == null) {
      matchType = "all";
    } else {
      matchType = match;
    }
    builder.match(matchType);

    final Class<?> criteriaClass = builder.toCriteria().getCriteriaClass();
    final BeanWrapper wrapper = getBeanWrapperForClass(criteriaClass);

    final String comparatorParam = removeParameter(params, "comparator", "eq").toLowerCase();
    final Criteria currentCriteria = builder.toCriteria();

    for (final String key : params.keySet()) {
      for (final String paramValue : params.get(key)) { // NOSONAR
        // NOSONAR the interface of MultivaluedMap.class declares List<String> as return value,
        // the actual implementation com.sun.jersey.core.util.MultivaluedMapImpl returns a String,
        // so this is fine in some way ...
        if ("null".equalsIgnoreCase(paramValue)) {
          builder.isNull(key);
        } else if ("notnull".equalsIgnoreCase(paramValue)) {
          builder.isNotNull(key);
        } else {
          Object value;
          Class<?> type = Object.class;
          try {
            type = currentCriteria.getType(key);
          } catch (final IntrospectionException e) {
            LOG.debug("Unable to determine type for key {}", key);
          }
          if (type == null) {
            type = Object.class;
          }
          LOG.warn("comparator = {}, key = {}, propertyType = {}", comparatorParam, key, type);

          if (comparatorParam.equals("contains")
              || comparatorParam.equals("iplike")
              || comparatorParam.equals("ilike")
              || comparatorParam.equals("like")) {
            value = paramValue;
          } else {
            LOG.debug("convertIfNecessary({}, {})", key, paramValue);
            try {
              value = wrapper.convertIfNecessary(paramValue, type);
            } catch (final Throwable t) {
              LOG.debug("failed to introspect (key = {}, value = {})", key, paramValue, t);
              value = paramValue;
            }
          }

          try {
            final Method m =
                builder.getClass().getMethod(comparatorParam, String.class, Object.class);
            m.invoke(builder, new Object[] {key, value});
          } catch (final Throwable t) {
            LOG.warn(
                "Unable to find method for comparator: {}, key: {}, value: {}",
                comparatorParam,
                key,
                value,
                t);
          }
        }
      }
    }
  }
Beispiel #30
0
  private String verifyResponse(
      Response resp, String content, int status, HashMap<String, String> expected_map)
      throws Exception {
    boolean pass = true;
    StringBuffer sb = new StringBuffer();

    sb.append("========== Verifying a Response with Map: " + newline);

    String entity = (String) resp.getEntity();

    if ((content == null) || (content == "")) {
      if (!(resp.getEntity() == null) || (resp.getEntity() == "")) {
        pass = false;
        sb.append(
            indent
                + "Entity verification failed: expecting no content, got "
                + (String) resp.getEntity()
                + newline);
      }
    } else if (!content.equals(((String) resp.getEntity()))) {
      pass = false;
      sb.append(
          indent
              + "Entity verification failed: expecting "
              + content
              + ", got "
              + (String) resp.getEntity()
              + newline);
    } else {
      sb.append(
          indent + "Correct content found in Response: " + (String) resp.getEntity() + newline);
    }

    if (resp.getStatus() != status) {
      pass = false;
      sb.append(
          indent
              + "Status code verification failed: expecting "
              + status
              + ", got "
              + resp.getStatus()
              + newline);
    } else {
      sb.append(indent + "Correct status found in Response: " + status + newline);
    }

    MultivaluedMap<java.lang.String, java.lang.Object> mvp = resp.getMetadata();
    if (expected_map == null) {
      sb.append(
          indent
              + "No keys to verify or expected, but found the following keys in Response:"
              + newline);
      for (String key : mvp.keySet()) {
        sb.append(indent + indent + "Key: " + key + "; " + mvp.getFirst(key) + ";" + newline);
      }
    } else {
      for (String key_actual : mvp.keySet()) {
        sb.append(indent + "Response contains key: " + key_actual + newline);
      }
      sb.append(indent + "Verifying the following keys in Response:" + newline);
      String actual, expected = null;
      for (Map.Entry<String, String> entry : expected_map.entrySet()) {
        String key = entry.getKey();
        if (!mvp.containsKey(key)) {
          pass = false;
          sb.append(indent + indent + "Key: " + key + " is not found in Response;" + newline);
        } else if (key.equalsIgnoreCase("last-modified")) {
          sb.append(indent + indent + "Key Last-Modified is found in response" + newline);
        } else {
          expected = entry.getValue().toLowerCase();
          actual = mvp.getFirst(key).toString().toLowerCase();

          if (actual.startsWith("\"") && actual.endsWith("\"")) {
            actual = actual.substring(1, actual.length() - 1);
          }

          if (!actual.equals(expected)) {
            pass = false;
            sb.append(
                indent
                    + indent
                    + "Key: "
                    + key
                    + " found in Response, but with different value;"
                    + newline);
            sb.append(
                indent
                    + indent
                    + "Expecting "
                    + entry.getValue()
                    + "; got "
                    + mvp.getFirst(key)
                    + newline);
          }
          sb.append(
              indent
                  + indent
                  + "Processed key "
                  + key
                  + " with expected value "
                  + entry.getValue()
                  + newline);
        }
      }
    }
    sb.append(indent + pass);
    return sb.toString();
  }