コード例 #1
0
 @Override
 public void writeTo(
     FileRange fileRange,
     Class<?> type,
     Type genericType,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, Object> httpHeaders,
     OutputStream entityStream)
     throws IOException, WebApplicationException {
   long fileSize = fileRange.getFile().length();
   String contentRange =
       "bytes " + fileRange.getBegin() + "-" + fileRange.getEnd() + "/" + fileSize;
   long length = (fileRange.getEnd() - fileRange.getBegin()) + 1;
   httpHeaders.putSingle("Content-Range", contentRange);
   httpHeaders.putSingle("Content-Length", length);
   FileInputStream fis = new FileInputStream(fileRange.getFile());
   try {
     if (fileRange.getBegin() > 0) {
       fis.getChannel().position(fileRange.getBegin());
     }
     final byte[] buf = new byte[2048];
     while (length > 0) {
       int len = 2048 > length ? (int) length : 2048;
       int read = fis.read(buf, 0, len);
       if (read == -1) {
         break;
       }
       entityStream.write(buf, 0, read);
       length -= len;
     }
   } finally {
     fis.close();
   }
 }
コード例 #2
0
ファイル: AuditTest.java プロジェクト: mindis/nuxeo
  @Test
  public void shouldFilterLogEntriesOnEventId() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("eventId", "documentModified");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);

    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(1, nodes.size());
    assertEquals("documentModified", nodes.get(0).get("eventId").getValueAsText());

    queryParams.putSingle("principalName", "bender");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(0, nodes.size());
  }
コード例 #3
0
ファイル: CallsEndpoint.java プロジェクト: rogervaas/RestComm
 private void normalize(final MultivaluedMap<String, String> data)
     throws IllegalArgumentException {
   final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
   final String from = data.getFirst("From");
   if (!from.contains("@")) {
     // https://github.com/Mobicents/RestComm/issues/150 Don't complain in case of URIs in the From
     // header
     data.remove("From");
     try {
       data.putSingle(
           "From",
           phoneNumberUtil.format(phoneNumberUtil.parse(from, "US"), PhoneNumberFormat.E164));
     } catch (final NumberParseException exception) {
       throw new IllegalArgumentException(exception);
     }
   }
   final String to = data.getFirst("To");
   // Only try to normalize phone numbers.
   if (to.startsWith("client")) {
     if (to.split(":").length != 2) {
       throw new IllegalArgumentException(to + " is an invalid client identifier.");
     }
   } else if (!to.contains("@")) {
     data.remove("To");
     try {
       data.putSingle(
           "To", phoneNumberUtil.format(phoneNumberUtil.parse(to, "US"), PhoneNumberFormat.E164));
     } catch (final NumberParseException exception) {
       throw new IllegalArgumentException(exception);
     }
   }
   URI.create(data.getFirst("Url"));
 }
コード例 #4
0
ファイル: TemplateWriter.java プロジェクト: aholstenson/dust
  @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();
  }
コード例 #5
0
 @Override
 public void filter(
     ContainerRequestContext requestContext, ContainerResponseContext responseContext)
     throws IOException {
   MultivaluedMap<String, Object> headers = responseContext.getHeaders();
   headers.putSingle("Access-Control-Allow-Origin", "*");
   headers.putSingle("Access-Control-Allow-Methods", "GET, POST");
   headers.putSingle("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
 }
 @Override
 public void filter(
     ContainerRequestContext requestContext, ContainerResponseContext responseContext)
     throws IOException {
   MultivaluedMap<String, Object> headers = responseContext.getHeaders();
   headers.putSingle("OData-Version", "4.0");
   headers.putSingle("Cache-Control", "max-age=0");
   headers.putSingle("Access-Control-Allow-Origin", "*");
 }
コード例 #7
0
  @Override
  public void writeTo(
      final Viewable viewable,
      final Class<?> type,
      final Type genericType,
      final Annotation[] annotations,
      final MediaType mediaType,
      final MultivaluedMap<String, Object> httpHeaders,
      final OutputStream entityStream)
      throws IOException, WebApplicationException {

    try {
      final ResolvedViewable resolvedViewable = resolve(viewable);
      if (resolvedViewable == null) {
        final String message =
            LocalizationMessages.TEMPLATE_NAME_COULD_NOT_BE_RESOLVED(viewable.getTemplateName());
        throw new WebApplicationException(
            new ProcessingException(message), Response.Status.NOT_FOUND);
      }

      httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, resolvedViewable.getMediaType());
      resolvedViewable.writeTo(entityStream, httpHeaders);
    } catch (ViewableContextException vce) {
      throw new NotFoundException(vce);
    }
  }
コード例 #8
0
  public MultivaluedMap<String, String> bindCamelHeadersToRequestHeaders(
      Map<String, Object> camelHeaders, Exchange camelExchange) throws Exception {

    MultivaluedMap<String, String> answer = new MetadataMap<String, String>();
    for (Map.Entry<String, Object> entry : camelHeaders.entrySet()) {
      // Need to make sure the cxf needed header will not be filtered
      if (headerFilterStrategy.applyFilterToCamelHeaders(
              entry.getKey(), entry.getValue(), camelExchange)
          && camelToCxfHeaderMap.get(entry.getKey()) == null) {
        LOG.trace("Drop Camel header: {}={}", entry.getKey(), entry.getValue());
        continue;
      }

      // we need to make sure the entry value is not null
      if (entry.getValue() == null) {
        LOG.trace("Drop Camel header: {}={}", entry.getKey(), entry.getValue());
        continue;
      }

      String mappedHeaderName = camelToCxfHeaderMap.get(entry.getKey());
      if (mappedHeaderName == null) {
        mappedHeaderName = entry.getKey();
      }

      LOG.trace(
          "Propagate Camel header: {}={} as {}",
          new Object[] {entry.getKey(), entry.getValue(), mappedHeaderName});

      answer.putSingle(mappedHeaderName, entry.getValue().toString());
    }
    return answer;
  }
コード例 #9
0
  @Override
  public void publish(Hub hub, QuoteEvent event) {

    MultivaluedMap<String, String> query = URIParser.getParameters(hub.getQuery());
    query.putSingle("id", event.getId());

    // fields to filter view
    Set<String> fieldSet = URIParser.getFieldsSelection(query);

    List<QuoteEvent> resultList = null;
    resultList = eventFacade.findByCriteria(query, QuoteEvent.class);

    if (resultList != null && !resultList.isEmpty()) {
      if (!fieldSet.isEmpty() && !fieldSet.contains(URIParser.ALL_FIELDS)) {
        fieldSet.add("id");
        fieldSet.add("date");
        fieldSet.add("eventType");
        fieldSet.add("reason");
        ObjectNode rootNode = Jackson.createNode(event, fieldSet);
        client.publishEvent(hub.getCallback(), rootNode);
      } else {
        client.publishEvent(hub.getCallback(), event);
      }
    }
  }
コード例 #10
0
  public static ExecutionRequest readRequest0(
      String content, MultivaluedMap<String, String> headers) throws Exception {
    ExecutionRequest req = new ExecutionRequest();

    JsonParser jp = JsonWriter.getFactory().createJsonParser(content);
    jp.nextToken(); // skip {
    JsonToken tok = jp.nextToken();
    while (tok != JsonToken.END_OBJECT) {
      String key = jp.getCurrentName();
      jp.nextToken();
      if ("input".equals(key)) {
        String input = jp.getText();
        if (input != null) {
          req.setInput(resolveInput(input));
        }
      } else if ("params".equals(key)) {
        readParams(jp, req);
      } else if ("context".equals(key)) {
        readContext(jp, req);
      } else if ("documentProperties".equals(key)) {
        // TODO XXX - this is wrong - headers are ready only! see with td
        String documentProperties = jp.getText();
        if (documentProperties != null) {
          headers.putSingle(JsonDocumentWriter.DOCUMENT_PROPERTIES_HEADER, documentProperties);
        }
      }
      tok = jp.nextToken();
    }
    return req;
  }
コード例 #11
0
ファイル: JAXRSOutInterceptor.java プロジェクト: Evolveum/cxf
 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()));
 }
コード例 #12
0
ファイル: ClientProxyImpl.java プロジェクト: eonezhang/cxf
  private MultivaluedMap<String, String> setRequestHeaders(
      MultivaluedMap<String, String> headers,
      OperationResourceInfo ori,
      boolean formParams,
      Class<?> bodyClass,
      Class<?> responseClass) {
    if (headers.getFirst(HttpHeaders.CONTENT_TYPE) == null) {
      if (formParams || bodyClass != null && MultivaluedMap.class.isAssignableFrom(bodyClass)) {
        headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
      } else {
        String ctType = null;
        List<MediaType> consumeTypes = ori.getConsumeTypes();
        if (!consumeTypes.isEmpty() && !consumeTypes.get(0).equals(MediaType.WILDCARD_TYPE)) {
          ctType = JAXRSUtils.mediaTypeToString(ori.getConsumeTypes().get(0));
        } else if (bodyClass != null) {
          ctType = MediaType.APPLICATION_XML;
        }
        if (ctType != null) {
          headers.putSingle(HttpHeaders.CONTENT_TYPE, ctType);
        }
      }
    }

    List<MediaType> accepts = getAccept(headers);
    if (accepts == null) {
      boolean produceWildcard =
          ori.getProduceTypes().size() == 0
              || ori.getProduceTypes().get(0).equals(MediaType.WILDCARD_TYPE);
      if (produceWildcard) {
        accepts =
            InjectionUtils.isPrimitive(responseClass)
                ? Collections.singletonList(MediaType.TEXT_PLAIN_TYPE)
                : Collections.singletonList(MediaType.APPLICATION_XML_TYPE);
      } else if (responseClass == Void.class || responseClass == Void.TYPE) {
        accepts = Collections.singletonList(MediaType.WILDCARD_TYPE);
      } else {
        accepts = ori.getProduceTypes();
      }

      for (MediaType mt : accepts) {
        headers.add(HttpHeaders.ACCEPT, JAXRSUtils.mediaTypeToString(mt));
      }
    }

    return headers;
  }
コード例 #13
0
 @Test
 public void should_create_category() throws Exception {
   MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
   map.putSingle("name", "taxi fee");
   Response response = target("/users/1/categories").request().post(Entity.form(new Form(map)));
   assertThat(response.getStatus(), is(201));
   verify(categoryMapper).createCategory(eq(1), categoryArgumentCaptor.capture());
   assertThat(categoryArgumentCaptor.getValue().getName(), is("taxi fee"));
 }
コード例 #14
0
ファイル: ApplicationResource.java プロジェクト: chagara/nifi
 protected MultivaluedMap<String, String> getRequestParameters(final boolean forceClientId) {
   final MultivaluedMap<String, String> params = getRequestParameters();
   if (forceClientId) {
     if (StringUtils.isBlank(params.getFirst(CLIENT_ID))) {
       params.putSingle(CLIENT_ID, new ClientIdParameter().getClientId());
     }
   }
   return params;
 }
コード例 #15
0
 protected MultivaluedMap<String, String> createRedirectState(
     ContainerRequestContext rc, UriInfo ui) {
   if (clientStateManager == null) {
     return new MetadataMap<String, String>();
   }
   String codeVerifier = null;
   MultivaluedMap<String, String> codeRequestState = toCodeRequestState(rc, ui);
   if (codeVerifierTransformer != null) {
     codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
     codeRequestState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier);
   }
   MultivaluedMap<String, String> redirectState =
       clientStateManager.toRedirectState(mc, codeRequestState);
   if (codeVerifier != null) {
     redirectState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier);
   }
   return redirectState;
 }
コード例 #16
0
  @Test
  public void overridesHttpMethodWhenXHTTPMethodOverrideHeaderIsSet() throws Exception {
    when(configuration.isHttpMethodOverride()).thenReturn(true);
    requestHeaders.putSingle(X_HTTP_METHOD_OVERRIDE, "PUT");
    ContainerRequest containerRequest = mockContainerRequest();
    ContainerResponse containerResponse = mockContainerResponse();
    EnvironmentContext environmentContext = mock(EnvironmentContext.class);

    everrestProcessor.process(containerRequest, containerResponse, environmentContext);

    verify(containerRequest).setMethod("PUT");
  }
コード例 #17
0
    private void invoke(int ind) throws Exception {
      client.type("text/plain").accept("text/plain");

      String actualHeaderName = bookHeader + ind;
      String actualBookName = bookName + ind;

      MultivaluedMap<String, String> map = client.getHeaders();
      map.putSingle("CustomHeader", actualHeaderName);
      client.headers(map).path("booksecho");

      doInvoke(actualBookName, actualHeaderName);

      // reset current path
      client.back(true);
    }
コード例 #18
0
 private void invalidRequestDollarFormat(
     final ODataHttpMethod method,
     final UriType uriType,
     final boolean isValue,
     final String dollarFormatOption)
     throws EdmException, ODataException {
   try {
     MultivaluedMap<String, String> options = new MultivaluedHashMap<String, String>(3);
     options.putSingle("$format", dollarFormatOption);
     checkRequest(method, mockPathSegments(uriType, false, isValue), options, null);
     fail("Expected ODataException not thrown");
   } catch (ODataBadRequestException e) {
     assertNotNull(e);
   } catch (Exception e) {
     fail("Unexpected Exception thrown");
   }
 }
コード例 #19
0
    private void invoke(int ind) throws Exception {

      String actualHeaderName = bookHeader + ind;
      String actualBookName = bookName + ind;

      if (stateCanBeChanged) {
        Client c = WebClient.client(proxy);
        MultivaluedMap<String, String> map = c.getHeaders();
        map.putSingle("CustomHeader", actualHeaderName);
        c.headers(map);
        proxy.echoBookNameAndHeader2(actualBookName);
        verifyResponse(c.getResponse(), actualBookName, actualHeaderName);
      } else {
        verifyResponse(
            proxy.echoBookNameAndHeader(actualHeaderName, actualBookName),
            actualBookName,
            actualHeaderName);
      }
    }
コード例 #20
0
 @SuppressWarnings("unchecked")
 @Override
 public void writeTo(
     T t,
     Class<?> type,
     Type genericType,
     Annotation[] annotations,
     MediaType mediaType,
     MultivaluedMap<String, Object> httpHeaders,
     OutputStream entityStream)
     throws IOException, WebApplicationException {
   // Add Cache-Control before start write body.
   httpHeaders.putSingle(HttpHeaders.CACHE_CONTROL, "public, no-cache, no-store, no-transform");
   if (t instanceof JsonSerializable) {
     try (Writer w = new OutputStreamWriter(entityStream, Charset.forName("UTF-8"))) {
       w.write(((JsonSerializable) t).toJson());
     }
   } else {
     delegate.writeTo(t, type, genericType, annotations, mediaType, httpHeaders, entityStream);
   }
 }
コード例 #21
0
    @Override
    public void writeTo(
        final String t,
        final Class<?> type,
        final Type genericType,
        final Annotation[] annotations,
        final MediaType mediaType,
        final MultivaluedMap<String, Object> httpHeaders,
        final OutputStream entityStream)
        throws IOException, WebApplicationException {
      // Underlying stream should not be closed and Jersey is preventing from closing it.
      entityStream.close();

      httpHeaders.putSingle(
          HEADER_NAME,
          config.getRuntimeType().equals(RuntimeType.SERVER)
              ? HEADER_VALUE_SERVER
              : HEADER_VALUE_CLIENT);

      entityStream.write(t.getBytes());
    }
コード例 #22
0
 private void setHeaders(MultivaluedMap<String, Object> headers) {
   this.headers = headers;
   Object location = headers.getFirst(HttpHeaders.LOCATION);
   if (location != null) {
     if (location instanceof URI) {
       final URI locationUri = (URI) location;
       if (!locationUri.isAbsolute()) {
         final URI base =
             (statusType.getStatusCode() == Status.CREATED.getStatusCode())
                 ? request.getAbsolutePath()
                 : request.getBaseUri();
         location =
             UriBuilder.fromUri(base)
                 .path(locationUri.getRawPath())
                 .replaceQuery(locationUri.getRawQuery())
                 .fragment(locationUri.getRawFragment())
                 .build();
       }
       headers.putSingle(HttpHeaders.LOCATION, location);
     }
   }
 }
コード例 #23
0
ファイル: JAXRSOutInterceptor.java プロジェクト: Evolveum/cxf
 private MultivaluedMap<String, Object> prepareResponseHeaders(
     Message message, ResponseImpl response, Object entity, boolean firstTry) {
   MultivaluedMap<String, Object> responseHeaders = response.getMetadata();
   @SuppressWarnings("unchecked")
   Map<String, List<Object>> userHeaders =
       (Map<String, List<Object>>) message.get(Message.PROTOCOL_HEADERS);
   if (firstTry && userHeaders != null) {
     responseHeaders.putAll(userHeaders);
   }
   if (entity != null) {
     Object customContentType = responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE);
     if (customContentType == null) {
       String initialResponseContentType = (String) message.get(Message.CONTENT_TYPE);
       if (initialResponseContentType != null) {
         responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, initialResponseContentType);
       }
     } else {
       message.put(Message.CONTENT_TYPE, customContentType.toString());
     }
   }
   message.put(Message.PROTOCOL_HEADERS, responseHeaders);
   setResponseDate(responseHeaders, firstTry);
   return responseHeaders;
 }
コード例 #24
0
ファイル: AuditTest.java プロジェクト: mindis/nuxeo
  @Test
  public void shouldFilterLogEntriesOnMultipleCriteria() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    DateTime firstDate = new DateTime();
    DateTime secondDate = firstDate.plusDays(10);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntry.setPrincipalName("bender");
    logEntry.setEventDate(firstDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(firstDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(secondDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("thirdEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(secondDate.toDate());
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(3, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    queryParams.add("eventId", "thirdEvent");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(1, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    queryParams.add("eventId", "thirdEvent");
    queryParams.add("startEventDate", ISODateTimeFormat.date().print(firstDate.plusDays(1)));
    queryParams.add("endEventDate", ISODateTimeFormat.date().print(secondDate.minus(1)));
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(0, nodes.size());
  }
コード例 #25
0
  /**
   * Writes a Atom (OData) representation of {@link EntityResource} to the output stream.
   *
   * @precondition supplied {@link EntityResource} is non null
   * @precondition {@link EntityResource#getEntity()} returns a valid OEntity, this provider only
   *     supports serialising OEntities
   * @postcondition non null Atom (OData) XML document written to OutputStream
   * @invariant valid OutputStream
   */
  @SuppressWarnings("unchecked")
  @Override
  public void writeTo(
      RESTResource resource,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    assert (resource != null);
    assert (uriInfo != null);
    // Set response headers
    if (httpHeaders != null) {
      httpHeaders.putSingle(
          HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); // Workaround for
      // https://issues.apache.org/jira/browse/WINK-374
    }

    try {
      RESTResource restResource = processLinks((RESTResource) resource);
      Collection<Link> processedLinks = restResource.getLinks();
      if (ResourceTypeHelper.isType(type, genericType, EntityResource.class, OEntity.class)) {
        EntityResource<OEntity> entityResource = (EntityResource<OEntity>) resource;
        OEntity tempEntity = entityResource.getEntity();
        EdmEntitySet entitySet = getEdmEntitySet(entityResource.getEntityName());
        List<OLink> olinks = formOLinks(entityResource);
        // Write entry
        // create OEntity with our EdmEntitySet see issue
        // https://github.com/aphethean/IRIS/issues/20
        OEntity oentity =
            OEntities.create(
                entitySet, tempEntity.getEntityKey(), tempEntity.getProperties(), null);
        entryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            Responses.entity(oentity),
            entitySet,
            olinks);
      } else if (ResourceTypeHelper.isType(type, genericType, EntityResource.class, Entity.class)) {
        EntityResource<Entity> entityResource = (EntityResource<Entity>) resource;
        // Write entry
        Entity entity = entityResource.getEntity();
        String entityName = entityResource.getEntityName();
        // Write Entity object with Abdera implementation
        entityEntryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            entityName,
            entity,
            processedLinks,
            entityResource.getEmbedded());
      } else if (ResourceTypeHelper.isType(type, genericType, EntityResource.class)) {
        EntityResource<Object> entityResource = (EntityResource<Object>) resource;
        // Links and entity properties
        Object entity = entityResource.getEntity();
        String entityName = entityResource.getEntityName();
        EntityProperties props = new EntityProperties();
        if (entity != null) {
          Map<String, Object> objProps =
              (transformer != null ? transformer : new BeanTransformer()).transform(entity);
          if (objProps != null) {
            for (String propName : objProps.keySet()) {
              props.setProperty(new EntityProperty(propName, objProps.get(propName)));
            }
          }
        }
        entityEntryWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            entityName,
            new Entity(entityName, props),
            processedLinks,
            entityResource.getEmbedded());
      } else if (ResourceTypeHelper.isType(
          type, genericType, CollectionResource.class, OEntity.class)) {
        CollectionResource<OEntity> collectionResource = ((CollectionResource<OEntity>) resource);
        EdmEntitySet entitySet = getEdmEntitySet(collectionResource.getEntityName());
        List<EntityResource<OEntity>> collectionEntities =
            (List<EntityResource<OEntity>>) collectionResource.getEntities();
        List<OEntity> entities = new ArrayList<OEntity>();
        Map<OEntity, Collection<Link>> linkId = new HashMap<OEntity, Collection<Link>>();
        for (EntityResource<OEntity> collectionEntity : collectionEntities) {
          // create OEntity with our EdmEntitySet see issue
          // https://github.com/aphethean/IRIS/issues/20
          OEntity tempEntity = collectionEntity.getEntity();
          List<OLink> olinks = formOLinks(collectionEntity);
          Collection<Link> links = collectionEntity.getLinks();
          OEntity entity =
              OEntities.create(
                  entitySet,
                  null,
                  tempEntity.getEntityKey(),
                  tempEntity.getEntityTag(),
                  tempEntity.getProperties(),
                  olinks);
          entities.add(entity);
          linkId.put(entity, links);
        }
        // TODO implement collection properties and get transient values for inlinecount and
        // skiptoken
        Integer inlineCount = null;
        String skipToken = null;
        feedWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            processedLinks,
            Responses.entities(entities, entitySet, inlineCount, skipToken),
            metadata.getModelName(),
            linkId);
      } else if (ResourceTypeHelper.isType(
          type, genericType, CollectionResource.class, Entity.class)) {
        CollectionResource<Entity> collectionResource = ((CollectionResource<Entity>) resource);

        // TODO implement collection properties and get transient values for inlinecount and
        // skiptoken
        Integer inlineCount = null;
        String skipToken = null;
        // Write feed
        AtomEntityFeedFormatWriter entityFeedWriter =
            new AtomEntityFeedFormatWriter(serviceDocument, metadata);
        entityFeedWriter.write(
            uriInfo,
            new OutputStreamWriter(entityStream, UTF_8),
            collectionResource,
            inlineCount,
            skipToken,
            metadata.getModelName());
      } else {
        logger.error(
            "Accepted object for writing in isWriteable, but type not supported in writeTo method");
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
      }
    } catch (ODataProducerException e) {
      logger.error("An error occurred while writing " + mediaType + " resource representation", e);
    }
  }
コード例 #26
0
 protected MultivaluedMap<String, String> initMap() {
   MultivaluedMap<String, String> map = new MetadataMap<String, String>();
   map.putSingle(OAuthConstants.GRANT_TYPE, grantType);
   return map;
 }
コード例 #27
0
 protected void addScope(MultivaluedMap<String, String> map) {
   if (scope != null) {
     map.putSingle(OAuthConstants.SCOPE, scope);
   }
 }
コード例 #28
0
ファイル: JAXRSOutInterceptor.java プロジェクト: Evolveum/cxf
  private void serializeMessage(
      ServerProviderFactory providerFactory,
      Message message,
      Response theResponse,
      OperationResourceInfo ori,
      boolean firstTry) {

    ResponseImpl response = (ResponseImpl) JAXRSUtils.copyResponseIfNeeded(theResponse);

    final Exchange exchange = message.getExchange();

    boolean headResponse =
        response.getStatus() == 200
            && firstTry
            && ori != null
            && HttpMethod.HEAD.equals(ori.getHttpMethod());
    Object entity = response.getActualEntity();
    if (headResponse && entity != null) {
      LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString());
      entity = null;
    }

    Method invoked =
        ori == null
            ? null
            : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke();

    Annotation[] annotations = null;
    Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[] {};
    Annotation[] responseAnns = response.getEntityAnnotations();
    if (responseAnns != null) {
      annotations = new Annotation[staticAnns.length + responseAnns.length];
      System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length);
      System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length);
    } else {
      annotations = staticAnns;
    }

    response.setStatus(getActualStatus(response.getStatus(), entity));
    response.setEntity(entity, annotations);

    // Prepare the headers
    MultivaluedMap<String, Object> responseHeaders =
        prepareResponseHeaders(message, response, entity, firstTry);

    // Run the filters
    try {
      JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked);
    } catch (Throwable ex) {
      handleWriteException(providerFactory, message, ex, firstTry);
      return;
    }

    // Write the entity
    entity = InjectionUtils.getEntity(response.getActualEntity());
    setResponseStatus(message, getActualStatus(response.getStatus(), entity));
    if (entity == null) {
      if (!headResponse) {
        responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0");
        if (MessageUtils.getContextualBoolean(
            message, "remove.content.type.for.empty.response", false)) {
          responseHeaders.remove(HttpHeaders.CONTENT_TYPE);
          message.remove(Message.CONTENT_TYPE);
        }
      }
      HttpUtils.convertHeaderValuesToString(responseHeaders, true);
      return;
    }

    Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS);
    boolean ignoreWriters =
        ignoreWritersProp == null ? false : Boolean.valueOf(ignoreWritersProp.toString());
    if (ignoreWriters) {
      writeResponseToStream(message.getContent(OutputStream.class), entity);
      return;
    }

    MediaType responseMediaType =
        getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE));

    Class<?> serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null;
    Class<?> targetType = InjectionUtils.getRawResponseClass(entity);
    Type genericType =
        InjectionUtils.getGenericResponseType(
            invoked, serviceCls, response.getActualEntity(), targetType, exchange);
    targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType);
    annotations = response.getEntityAnnotations();

    List<WriterInterceptor> writers =
        providerFactory.createMessageBodyWriterInterceptor(
            targetType,
            genericType,
            annotations,
            responseMediaType,
            message,
            ori == null ? null : ori.getNameBindings());

    OutputStream outOriginal = message.getContent(OutputStream.class);
    if (writers == null || writers.isEmpty()) {
      writeResponseErrorMessage(
          message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType);
      return;
    }
    try {
      boolean checkWriters = false;
      if (responseMediaType.isWildcardSubtype()) {
        Produces pM =
            AnnotationUtils.getMethodAnnotation(
                ori == null ? null : ori.getAnnotatedMethod(), Produces.class);
        Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class);
        checkWriters = pM == null && pC == null;
      }
      responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters);
    } catch (Throwable ex) {
      handleWriteException(providerFactory, message, ex, firstTry);
      return;
    }
    String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType);
    if (LOG.isLoggable(Level.FINE)) {
      LOG.fine("Response content type is: " + finalResponseContentType);
    }
    responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType);
    message.put(Message.CONTENT_TYPE, finalResponseContentType);

    boolean enabled = checkBufferingMode(message, writers, firstTry);
    try {

      try {
        JAXRSUtils.writeMessageBody(
            writers,
            entity,
            targetType,
            genericType,
            annotations,
            responseMediaType,
            responseHeaders,
            message);

        if (isResponseRedirected(message)) {
          return;
        }
        checkCachedStream(message, outOriginal, enabled);
      } finally {
        if (enabled) {
          OutputStream os = message.getContent(OutputStream.class);
          if (os != outOriginal && os instanceof CachedOutputStream) {
            os.close();
          }
          message.setContent(OutputStream.class, outOriginal);
          message.put(XMLStreamWriter.class.getName(), null);
        }
      }

    } catch (Throwable ex) {
      logWriteError(firstTry, targetType, responseMediaType);
      handleWriteException(providerFactory, message, ex, firstTry);
    }
  }
コード例 #29
0
 @Override
 public void putSingle(final String key, final V value) {
   delegate.putSingle(key, value);
 }
コード例 #30
0
ファイル: AuditTest.java プロジェクト: mindis/nuxeo
  @Test
  public void shouldHandlePagination() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("thirdEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("fourthEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("fifthEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("sixthEvent");
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(6, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "0");
    queryParams.putSingle("pageSize", "2");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(0, node.get("currentPageIndex").getIntValue());
    assertEquals(2, node.get("pageSize").getIntValue());
    assertEquals(3, node.get("numberOfPages").getIntValue());
    nodes = getLogEntries(node);
    assertEquals(2, nodes.size());
    assertEquals("sixthEvent", nodes.get(0).get("eventId").getValueAsText());
    assertEquals("fifthEvent", nodes.get(1).get("eventId").getValueAsText());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "1");
    queryParams.putSingle("pageSize", "3");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(1, node.get("currentPageIndex").getIntValue());
    assertEquals(3, node.get("pageSize").getIntValue());
    assertEquals(2, node.get("numberOfPages").getIntValue());
    nodes = getLogEntries(node);
    assertEquals(3, nodes.size());
    assertEquals("thirdEvent", nodes.get(0).get("eventId").getValueAsText());
    assertEquals("secondEvent", nodes.get(1).get("eventId").getValueAsText());
    assertEquals("firstEvent", nodes.get(2).get("eventId").getValueAsText());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "2");
    queryParams.putSingle("pageSize", "3");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(0, nodes.size());
  }