Exemplo n.º 1
0
 // Registra un MR para su gestion
 // curl -d "ip=192.168.119.35&port=10001&domain=broadcaster&type=Webservices"
 // http://192.168.119.35:9999/mbs/register
 @POST
 @Path("/register")
 @Produces(MediaType.TEXT_PLAIN)
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public String register(
     @FormParam("ip") String ip,
     @FormParam("port") String port,
     @FormParam("domain") String domain,
     @FormParam("type") String type) {
   if (domain.equals("SNMPInstrumentingServer")) {
     Client client = Client.create();
     WebResource webResource =
         client.resource(
             "http://"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_IP
                 + ":"
                 + MBeanServerMaster.INSTRUMENTING_SERVER_WS_PORT
                 + "/snmp_mbs/register");
     MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
     queryParams.add("domain", "SNMPInstrumentingServer");
     queryParams.add("type", type);
     ClientResponse s =
         webResource.queryParams(queryParams).post(ClientResponse.class, queryParams);
     if (s.getEntity(String.class).equals("ok"))
       DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   } else DynamicMBeanMirrorFactory.register(ip, port, domain, type);
   return "";
 }
Exemplo n.º 2
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()));
 }
Exemplo n.º 3
0
  /**
   * Builds a paged result out of a list of items and additional information.
   *
   * @param <T> result type
   * @param list bare list of items to be returned
   * @param page current page
   * @param size requested size
   * @param totalCount total result size (not considering pagination)
   * @return paged result
   */
  protected <T extends AbstractBaseBean> PagedResult<T> buildPagedResult(
      final List<T> list, final int page, final int size, final int totalCount) {

    PagedResult<T> result = new PagedResult<>();
    result.getResult().addAll(list);

    result.setPage(page);
    result.setSize(result.getResult().size());
    result.setTotalCount(totalCount);

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      builder.queryParam(queryParam.getKey(), queryParam.getValue().toArray());
    }

    if (result.getPage() > 1) {
      result.setPrev(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() - 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }
    if ((result.getPage() - 1) * size + result.getSize() < totalCount) {
      result.setNext(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() + 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }

    return result;
  }
Exemplo n.º 4
0
 @Override
 protected AbstractCommonList getCommonList(UriInfo ui) {
   try {
     ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
     MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
     DocumentHandler handler = createDocumentHandler(ctx);
     String docType = queryParams.getFirst(IQueryManager.SEARCH_TYPE_DOCTYPE);
     String mode = queryParams.getFirst(IQueryManager.SEARCH_TYPE_INVOCATION_MODE);
     String whereClause = null;
     DocumentFilter documentFilter = null;
     String common_part = ctx.getCommonPartLabel();
     if (docType != null && !docType.isEmpty()) {
       whereClause = QueryManager.createWhereClauseForInvocableByDocType(common_part, docType);
       documentFilter = handler.getDocumentFilter();
       documentFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND);
     }
     if (mode != null && !mode.isEmpty()) {
       whereClause = QueryManager.createWhereClauseForInvocableByMode(common_part, mode);
       documentFilter = handler.getDocumentFilter();
       documentFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND);
     }
     if (whereClause != null && logger.isDebugEnabled()) {
       logger.debug("The WHERE clause is: " + documentFilter.getWhereClause());
     }
     getRepositoryClient(ctx).getFiltered(ctx, handler);
     AbstractCommonList list = (AbstractCommonList) handler.getCommonPartList();
     return list;
   } catch (Exception e) {
     throw bigReThrow(e, ServiceMessages.LIST_FAILED);
   }
 }
Exemplo n.º 5
0
  /** Migrated Jersey 1.x {@code com.sun.jersey.impl.PathSegmentsHttpRequestTest}. */
  @Test
  public void testGetPathSegmentsGeneral() {
    final UriInfo ui = createContext("/p1;x=1;y=1/p2;x=2;y=2/p3;x=3;y=3", "GET");

    List<PathSegment> segments = ui.getPathSegments();
    assertEquals(3, segments.size());

    final Iterator<PathSegment> psi = segments.iterator();
    PathSegment segment;

    segment = psi.next();
    assertEquals("p1", segment.getPath());
    MultivaluedMap<String, String> m = segment.getMatrixParameters();
    assertEquals("1", m.getFirst("x"));
    assertEquals("1", m.getFirst("y"));

    segment = psi.next();
    assertEquals("p2", segment.getPath());
    m = segment.getMatrixParameters();
    assertEquals("2", m.getFirst("x"));
    assertEquals("2", m.getFirst("y"));

    segment = psi.next();
    assertEquals("p3", segment.getPath());
    m = segment.getMatrixParameters();
    assertEquals("3", m.getFirst("x"));
    assertEquals("3", m.getFirst("y"));
  }
Exemplo n.º 6
0
  /**
   * Create a unique node or return fail (create).
   *
   * <p>Here, in case of an already existing node, an error should be returned. In this example, no
   * existing indexed node is found and a new node is created.
   */
  @Documented
  @Test
  public void create_a_unique_node_or_fail_create() throws Exception {
    final String index = "people", key = "name", value = "Tobias";
    helper.createNodeIndex(index);
    ResponseEntity response =
        gen.get()
            .noGraph()
            .expectedStatus(201 /* created */)
            .payloadType(MediaType.APPLICATION_JSON_TYPE)
            .payload(
                "{\"key\": \""
                    + key
                    + "\", \"value\": \""
                    + value
                    + "\", \"properties\": {\""
                    + key
                    + "\": \""
                    + value
                    + "\", \"sequence\": 1}}")
            .post(functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail");

    MultivaluedMap<String, String> headers = response.response().getHeaders();
    Map<String, Object> result = JsonHelper.jsonToMap(response.entity());
    assertEquals(result.get("indexed"), headers.getFirst("Location"));
    Map<String, Object> data = assertCast(Map.class, result.get("data"));
    assertEquals(value, data.get(key));
    assertEquals(1, data.get("sequence"));
  }
Exemplo n.º 7
0
 /**
  * Returns a list of saved queries
  *
  * @param criteria a multivalued map that has the filter criteria
  * @param start Displacement from the start of the search result
  * @param count Count of number of records required
  * @return list of saved queries
  * @throws LensException
  */
 public ListResponse getList(MultivaluedMap<String, String> criteria, long start, long count)
     throws LensException {
   final StringBuilder selectQueryBuilder =
       new StringBuilder("select * from " + SAVED_QUERY_TABLE_NAME);
   final Set<String> availableFilterKeys = FILTER_KEYS.keySet();
   final Sets.SetView<String> intersection =
       Sets.intersection(availableFilterKeys, criteria.keySet());
   if (intersection.size() > 0) {
     final StringBuilder whereClauseBuilder = new StringBuilder(" where ");
     final List<String> predicates = Lists.newArrayList();
     for (String colName : intersection) {
       predicates.add(
           FILTER_KEYS.get(colName).resolveFilterExpression(colName, criteria.getFirst(colName)));
     }
     Joiner.on(" and ").skipNulls().appendTo(whereClauseBuilder, predicates);
     selectQueryBuilder.append(whereClauseBuilder.toString());
   }
   final String listCountQuery =
       "select count(*) as "
           + VALUE_ALIAS
           + " from ("
           + selectQueryBuilder.toString()
           + ") tmp_table";
   selectQueryBuilder.append(" limit ").append(start).append(", ").append(count);
   final String listQuery = selectQueryBuilder.toString();
   try {
     return new ListResponse(
         start,
         runner.query(listCountQuery, new SingleValuedResultHandler()),
         runner.query(listQuery, new SavedQueryResultSetHandler()));
   } catch (SQLException e) {
     throw new LensException("List query failed!", e);
   }
 }
Exemplo n.º 8
0
  public List<Offer> getOffers(String latitude, String longitude) {
    // Request JSON data from the API for offers
    MultivaluedMap<String, String> QueryParams = new MultivaluedMapImpl();
    QueryParams.add("lat", latitude);
    QueryParams.add("long", longitude);
    String json =
        service
            .path("offers")
            .queryParams(QueryParams)
            .accept(MediaType.APPLICATION_JSON)
            .get(String.class);

    List<Offer> offers = null;

    try {
      // Transform this to a list of POJOs
      offers = mapper.readValue(json, new TypeReference<List<Offer>>() {});

      for (Offer offer : offers) {
        Log.d(TAG, "Offer: " + offer.getId() + " decription: " + offer.getDescription());
      }
    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JsonMappingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return offers;
  }
  /** {@inheritDoc} */
  @Override
  public Collection<CacheEntity> getCaches(final UriInfo info) {
    LOG.debug(
        String.format("Invoking CachesResourceServiceImpl.getCaches: %s", info.getRequestUri()));

    validator.validateSafe(info);

    String cacheManagerNames =
        info.getPathSegments().get(1).getMatrixParameters().getFirst("names");
    Set<String> cmNames =
        cacheManagerNames == null
            ? null
            : new HashSet<String>(Arrays.asList(cacheManagerNames.split(",")));

    String cacheNames = info.getPathSegments().get(2).getMatrixParameters().getFirst("names");
    Set<String> cNames =
        cacheNames == null ? null : new HashSet<String>(Arrays.asList(cacheNames.split(",")));

    MultivaluedMap<String, String> qParams = info.getQueryParameters();
    List<String> attrs = qParams.get(ATTR_QUERY_KEY);
    Set<String> cAttrs = attrs == null || attrs.isEmpty() ? null : new HashSet<String>(attrs);

    try {
      return entityResourceFactory.createCacheEntities(cmNames, cNames, cAttrs);
    } catch (ServiceExecutionException e) {
      throw new ResourceRuntimeException(
          "Failed to get caches", e, Response.Status.BAD_REQUEST.getStatusCode());
    }
  }
  @POST
  // @Consumes ({"application/rdf+xml", "application/xml"})
  // @Consumes ({"text/xml"})
  public void doPost(
      @PathParam("projectId") String projectId,
      @Context UriInfo uriInfo,
      MultivaluedMap<String, String> formData) {
    String title = formData.getFirst("title");
    String description = formData.getFirst("description");
    String status = formData.getFirst("status");

    if (description == null) {
      description = "";
    }

    try {
      ChangeRequestDto dto = new ChangeRequestDto();
      dto.setTitle(title);
      dto.setDescription(description);
      dto.setStatus(status);

      String baseUrl = uriInfo.getBaseUri().toString() + IConstants.SERVICE_SERVICES;
      ResourceAdapter adapter = AdapterRegistry.getAdapter(baseUrl);
      adapter.addChangeRequest(dto);
    } catch (Exception e) {
      e.printStackTrace();
    }
    //		String uri = uriInfo.getBaseUri().toString() + IConstants.SERVICE_SERVICES + "/" + projectId
    // + "/list";
    //		return Response.seeOther(URI.create(uri)).build();
  }
Exemplo n.º 11
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);
      }
    }
  }
Exemplo n.º 12
0
  /*
   * Query method for interaction context parameters returning raw sql data.
   *
   * If given a key will return a single row.
   *
   * If given a null key will return all rows.
   */
  public SqlRowSet query(String tableName, String key, InteractionContext ctx)
      throws UnsupportedQueryOperationException, JdbcException, Exception {
    // Not much point selecting from a null table
    if (null == tableName) {
      logger.error("Jdbc producer cannot select from null table.");
      throw (new JdbcException(Status.INTERNAL_SERVER_ERROR, "Null table name"));
    }

    // Get column types from Jdbc. We need these both for constructing the
    // command and processing it's result set.
    // We need the primary key for row ordering.
    // TODO Eventually this should be cached.
    ColumnTypesMap colTypesMap = new ColumnTypesMap(this, tableName, true);

    // Unpack the commands $filter and $select terms.
    AccessProfile accessProfile = getAccessProfile(ctx);

    // Get top and skip parameters (null if not specified).
    MultivaluedMap<String, String> queryParams = ctx.getQueryParameters();
    String top = queryParams.getFirst(ODataParser.TOP_KEY);
    String skip = queryParams.getFirst(ODataParser.SKIP_KEY);

    List<OrderBy> orderBy = ODataParser.parseOrderBy(queryParams.getFirst(ODataParser.ORDERBY_KEY));

    // Build an SQL command
    SqlCommandBuilder sqlBuilder =
        new SqlCommandBuilder(
            tableName, key, accessProfile, colTypesMap, top, skip, orderBy, serverMode);
    String sqlCommand = sqlBuilder.getCommand();

    logger.info("Jdbc producer about to execute \"" + sqlCommand + "\"");

    // Execute the SQL command
    return query(sqlCommand);
  }
Exemplo n.º 13
0
 @GET
 @Path("/bookinfo")
 public Book getBookByUriInfo() throws Exception {
   MultivaluedMap<String, String> params = ui.getQueryParameters();
   String id = params.getFirst("param1") + params.getFirst("param2");
   return books.get(Long.valueOf(id));
 }
  @Test
  public void putAddToOrganizationFail() throws Exception {

    Map<String, String> originalProperties = getRemoteTestProperties();

    try {
      setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false");
      setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
      setTestProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false");
      setTestProperty(PROPERTIES_SYSADMIN_EMAIL, "*****@*****.**");

      String t = adminToken();
      MultivaluedMap formData = new MultivaluedMapImpl();
      formData.add("foo", "bar");
      try {
        resource()
            .path(
                "/management/organizations/test-organization/users/[email protected]")
            .queryParam("access_token", t)
            .accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_FORM_URLENCODED)
            .put(JsonNode.class, formData);
      } catch (UniformInterfaceException e) {
        assertEquals("Should receive a 400 Not Found", 400, e.getResponse().getStatus());
      }
    } finally {
      setTestProperties(originalProperties);
    }
  }
Exemplo n.º 15
0
  @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());
  }
Exemplo n.º 16
0
  @POST
  @Path("{templateId}")
  @Produces({MediaType.TEXT_HTML})
  public String mergeTemplate(
      @PathParam("templateId") final Long templateId,
      @Context final UriInfo uriInfo,
      final String apiRequestBodyAsJson)
      throws MalformedURLException, IOException {

    final Template template = this.templateService.findOneById(templateId);

    @SuppressWarnings("unchecked")
    final HashMap<String, Object> result =
        new ObjectMapper().readValue(apiRequestBodyAsJson, HashMap.class);

    final MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
    final Map<String, Object> parametersMap = new HashMap<String, Object>();
    for (final Map.Entry<String, List<String>> entry : parameters.entrySet()) {

      if (entry.getValue().size() == 1) {
        parametersMap.put(entry.getKey(), entry.getValue().get(0));
      } else {
        parametersMap.put(entry.getKey(), entry.getValue());
      }
    }

    parametersMap.put("BASE_URI", uriInfo.getBaseUri());
    parametersMap.putAll(result);
    return this.templateMergeService.compile(template, parametersMap);
  }
Exemplo n.º 17
0
  @Test
  public void get_or_create_node_with_array_properties() throws Exception {
    final String index = "people", key = "name", value = "Tobias";
    helper.createNodeIndex(index);
    ResponseEntity response =
        gen()
            .expectedStatus(201 /* created */)
            .payloadType(MediaType.APPLICATION_JSON_TYPE)
            .payload(
                "{\"key\": \""
                    + key
                    + "\", \"value\": \""
                    + value
                    + "\", \"properties\": {\""
                    + key
                    + "\": \""
                    + value
                    + "\", \"array\": [1,2,3]}}")
            .post(functionalTestHelper.nodeIndexUri() + index + "?unique");

    MultivaluedMap<String, String> headers = response.response().getHeaders();
    Map<String, Object> result = JsonHelper.jsonToMap(response.entity());
    String location = headers.getFirst("Location");
    assertEquals(result.get("indexed"), location);
    Map<String, Object> data = assertCast(Map.class, result.get("data"));
    assertEquals(value, data.get(key));
    assertEquals(Arrays.asList(1, 2, 3), data.get("array"));
    Node node;
    try (Transaction tx = graphdb().beginTx()) {
      node = graphdb().index().forNodes(index).get(key, value).getSingle();
    }
    assertThat(node, inTx(graphdb(), hasProperty(key).withValue(value)));
    assertThat(node, inTx(graphdb(), hasProperty("array").withValue(new int[] {1, 2, 3})));
  }
  /**
   * Retrieves representation of an instance of org.azrul.epice.rest.service.RetrivePasswordResource
   *
   * @return an instance of java.lang.String
   */
  @POST
  @Produces("application/xml")
  public String getXml() {
    // TODO return proper representation object
    XStream writer = new XStream();
    writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
    writer.alias("RetrievePasswordResponse", RetrievePasswordResponse.class);

    XStream reader = new XStream();
    reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
    reader.alias("RetrievePasswordRequest", RetrievePasswordRequest.class);

    RetrievePasswordResponse errorResponse = new RetrievePasswordResponse();
    List<String> errors = new ArrayList<String>();
    errors.add("MODIFY PASSWORD ERROR");
    errorResponse.setErrors(errors);

    MultivaluedMap<String, String> params = context.getQueryParameters();

    try {
      String request = URLDecoder.decode(params.getFirst("REQUEST"), "UTF-8");
      RetrievePasswordRequest oRequest = (RetrievePasswordRequest) reader.fromXML(request);
      RetrievePasswordResponse oResponse = doService(oRequest);
      return URLEncoder.encode(writer.toXML(oResponse), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      return writer.toXML(errorResponse);
    }
  }
  private FileMetaData getFileContentInfo(File file) {
    try {
      MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
      queryParams.add("redirect", "meta");
      ClientResponse resp =
          getRootApiWebResource()
              .path("files")
              .path(String.valueOf(file.getId()))
              .path("content")
              .queryParams(queryParams)
              .accept(MediaType.APPLICATION_OCTET_STREAM)
              .accept(MediaType.TEXT_HTML)
              .accept(MediaType.APPLICATION_XHTML_XML)
              .get(ClientResponse.class);

      String sResp = resp.getEntity(String.class);
      FileMetaData fileInfo =
          mapper.readValue(
              mapper.readValue(sResp, JsonNode.class).findPath(RESPONSE).toString(),
              FileMetaData.class);
      logger.info(fileInfo.toString());
      return fileInfo;
    } catch (BaseSpaceException bs) {
      throw bs;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
Exemplo n.º 20
0
  /** Test checks that POST on the '/form' resource gives a response page with the entered data. */
  @Test
  public void testPostOnForm() {
    MultivaluedMap<String, String> formData = new MultivaluedStringMap();
    formData.add("name", "testName");
    formData.add("colour", "red");
    formData.add("hint", "re");

    Response response =
        target()
            .path("form")
            .request()
            .post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
    assertEquals(Response.Status.OK, response.getStatusInfo());

    // check that the generated response is the expected one
    InputStream responseInputStream = response.readEntity(InputStream.class);
    try {
      byte[] responseData = new byte[responseInputStream.available()];
      final int read = responseInputStream.read(responseData);

      assertTrue(read > 0);
      assertTrue(new String(responseData).contains("Hello, you entered"));
    } catch (IOException ex) {
      Logger.getLogger(MainTest.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 21
0
  /** Executes an authentication request via HTTP POST */
  private <T> T executeAuthenticationPost(WebResource webResource, Class<T> returnClass)
      throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException {

    // Map query params for POST operation MultivaluedMap, MultivaluedMapImpl

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("username", getConnector().getConfig().getUsername());
    queryParams.add("password", getConnector().getConfig().getPassword());

    /** Call HTTP POST */
    ClientResponse clientResponse =
        webResource
            .queryParams(queryParams)
            .accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class);

    if (clientResponse.getStatus() == 200) {
      return clientResponse.getEntity(returnClass);
    } else if (clientResponse.getStatus() == 401) {
      throw new CIWiseRESTConnectorTokenExpiredException(
          "The access token has expired; " + clientResponse.getEntity(String.class));
    } else {
      throw new CIWiseRESTConnectorException(
          String.format(
              "ERROR - statusCode: %d - message: %s",
              clientResponse.getStatus(), clientResponse.getEntity(String.class)));
    }
  }
Exemplo n.º 22
0
  @Test
  public void testAttributes() throws Exception {
    DKIMSignature signed = new DKIMSignature();
    signed.setAttribute("path", "/hello/world");
    signed.setTimestamp();
    signed.addHeader("Visa");
    signed.addHeader("Visa");
    MultivaluedMapImpl<String, String> headers = new MultivaluedMapImpl<String, String>();
    headers.add("Visa", "v1");
    headers.add("Visa", "v2");
    headers.add("Visa", "v3");
    signed.sign(headers, null, keys.getPrivate());

    String signedHeader = signed.toString();

    System.out.println(signedHeader);

    DKIMSignature verified = new DKIMSignature(signedHeader);

    HashMap<String, String> requiredAttributes = new HashMap<String, String>();
    requiredAttributes.put("path", "/hello/world");

    Verification verification = new Verification();
    verification.getRequiredAttributes().put("path", "/hello/world");

    MultivaluedMap<String, String> verifiedHeaders =
        verification.verify(verified, headers, null, keys.getPublic());
    Assert.assertEquals(verifiedHeaders.size(), 1);
    List<String> visas = verifiedHeaders.get("Visa");
    Assert.assertNotNull(visas);
    Assert.assertEquals(visas.size(), 2);
    System.out.println(visas);
    Assert.assertEquals(visas.get(0), "v3");
    Assert.assertEquals(visas.get(1), "v2");
  }
Exemplo n.º 23
0
  @Override
  public PagedConnObjectTOResult listConnObjects(
      final String key, final String anyTypeKey, final ConnObjectTOListQuery listQuery) {

    Pair<SearchResult, List<ConnObjectTO>> list =
        logic.listConnObjects(
            key,
            anyTypeKey,
            listQuery.getSize(),
            listQuery.getPagedResultsCookie(),
            getOrderByClauses(listQuery.getOrderBy()));

    PagedConnObjectTOResult result = new PagedConnObjectTOResult();
    if (list.getLeft() != null) {
      result.setAllResultsReturned(list.getLeft().isAllResultsReturned());
      result.setPagedResultsCookie(list.getLeft().getPagedResultsCookie());
      result.setRemainingPagedResults(list.getLeft().getRemainingPagedResults());
    }
    result.getResult().addAll(list.getRight());

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      builder = builder.queryParam(queryParam.getKey(), queryParam.getValue().toArray());
    }

    if (StringUtils.isNotBlank(result.getPagedResultsCookie())) {
      result.setNext(
          builder
              .replaceQueryParam(PARAM_CONNID_PAGED_RESULTS_COOKIE, result.getPagedResultsCookie())
              .build());
    }

    return result;
  }
  /**
   * Set the cache control and last modified HTTP headers from data in the graph
   *
   * @param httpHeaders
   * @param rdf
   */
  public static void setCachingHeaders(
      final MultivaluedMap<String, Object> httpHeaders, final Dataset rdf, final UriInfo uriInfo) {

    final List<PathSegment> segments = uriInfo.getPathSegments();
    if (!segments.isEmpty() && segments.get(0).getPath().startsWith("tx:")) {
      // Do not set caching headers if we are in a transaction
      return;
    }

    httpHeaders.put(CACHE_CONTROL, of((Object) "max-age=0", (Object) "must-revalidate"));

    LOGGER.trace(
        "Attempting to discover the last-modified date of the node for the resource in question...");
    final Iterator<Quad> iterator =
        rdf.asDatasetGraph().find(ANY, getDatasetSubject(rdf), lastModifiedPredicate, ANY);

    if (!iterator.hasNext()) {
      return;
    }

    final Object dateObject = iterator.next().getObject().getLiteralValue();

    if (!(dateObject instanceof XSDDateTime)) {
      LOGGER.debug("Found last-modified date, but it was not an XSDDateTime: {}", dateObject);

      return;
    }

    final XSDDateTime lastModified = (XSDDateTime) dateObject;
    LOGGER.debug("Found last-modified date: {}", lastModified);
    final String lastModifiedAsRdf2822 =
        RFC2822DATEFORMAT.print(new DateTime(lastModified.asCalendar()));
    httpHeaders.put(LAST_MODIFIED, of((Object) lastModifiedAsRdf2822));
  }
 private String getParamString(MultivaluedMap<String, String> params, String param) {
   if (params.containsKey(param)) {
     return params.getFirst(param);
   } else {
     return "";
   }
 }
  @Test
  public void testPostProcessWithPaging() {
    when(page.getPageRequest()).thenReturn(pageRequest);
    when(page.getMaxRecords()).thenReturn(15);
    when(pageRequest.isPaging()).thenReturn(true);
    when(pageRequest.getPage()).thenReturn(2);
    when(pageRequest.getPerPage()).thenReturn(5);

    // We're going to take the quick path through buildBaseUrl.
    when(config.containsKey(eq(ConfigProperties.PREFIX_APIURL))).thenReturn(false);
    when(request.getRequestURL()).thenReturn(new StringBuffer("https://example.com/candlepin"));
    when(request.getQueryString()).thenReturn("order=asc&page=1&per_page=10");

    MultivaluedMap<String, Object> map = new MultivaluedMapImpl<String, Object>();
    when(response.getMetadata()).thenReturn(map);

    ResteasyProviderFactory.pushContext(Page.class, page);
    ResteasyProviderFactory.pushContext(HttpServletRequest.class, request);

    interceptor.postProcess(response);
    String header = (String) map.getFirst(LinkHeaderPostInterceptor.LINK_HEADER);

    // It would be a bit much to parse the entire header, so let's just make
    // sure that we have first, last, next, and prev links.
    assertTrue(header.contains("rel=\"first\""));
    assertTrue(header.contains("rel=\"last\""));
    assertTrue(header.contains("rel=\"next\""));
    assertTrue(header.contains("rel=\"prev\""));
  }
 @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();
   }
 }
  private static WebResource.Builder getBuilder(
      String url, String authorization, Map<String, String> key, Boolean overwrite) {
    Client client = Client.create();
    WebResource wr = client.resource(url);

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();

    if (key != null && !key.isEmpty()) {
      for (String k : key.keySet()) {
        queryParams.add(k, key.get(k));
      }
    }

    if (overwrite != null && overwrite) {
      queryParams.add(CLOUDHUB_OVERRITE_REST_PARAMETER, overwrite.toString());
    }

    if (queryParams.isEmpty()) {
      return wr.header(HTTP_AUTH_HEADER_NAME, authorization).type(MediaType.APPLICATION_JSON);
    } else {
      return wr.queryParams(queryParams)
          .header(HTTP_AUTH_HEADER_NAME, authorization)
          .type(MediaType.APPLICATION_JSON);
    }
  }
Exemplo n.º 29
0
 public void filter(ClientRequestContext requestContext) throws IOException {
   MultivaluedMap<String, Object> headers = requestContext.getHeaders();
   String authenticationHeader = getAuthenticationHeader();
   if (Strings.isNotBlank(authenticationHeader)) {
     headers.add("Authorization", authenticationHeader);
   }
 }
  @Override
  public UriBuilder replaceQueryParam(String name, Object... values) {
    checkSsp();

    if (queryParams == null) {
      queryParams = UriComponent.decodeQuery(query.toString(), false);
      query.setLength(0);
    }

    name = encode(name, UriComponent.Type.QUERY_PARAM);
    queryParams.remove(name);

    if (values == null) {
      return this;
    }

    for (Object value : values) {
      if (value == null) {
        throw new IllegalArgumentException("One or more of query value parameters are null");
      }

      queryParams.add(name, encode(value.toString(), UriComponent.Type.QUERY_PARAM));
    }
    return this;
  }