Ejemplo n.º 1
2
  /*
   * curl --data "[email protected]&password=test" http://localhost:8080/prostalytics/rest/auth/login
   *
   */
  @Path("/login")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.TEXT_HTML)
  public Response login(
      @FormParam("email") String email,
      @FormParam("password") String password,
      @HeaderParam("Auth-Token") String token)
      throws URISyntaxException {

    String newToken = null;
    try {
      User user = dao.authenticate(email, hashPassword(password));
      if (user != null) {
        newToken = auth.loggedIn(user, token);
      }

      URI redir =
          uriInfo
              .getBaseUri()
              .resolve(Navigation.fromLogin(user != null ? Navigation.OK : Navigation.ERROR));
      URI uri = UriBuilder.fromUri(redir).build();
      Response.ResponseBuilder res = Response.seeOther(uri);
      if (newToken != null) {
        res.header("Auth-Token", newToken);
      }
      return res.build();
    } catch (Throwable e) {
      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromLogin(Navigation.ERROR, e)))
              .build();
      return Response.seeOther(uri).build();
    }
  }
Ejemplo n.º 2
0
 protected static URI getRedirectUri(final UriInfo m_uriInfo, final Object... pathComponents) {
   if (pathComponents != null && pathComponents.length == 0) {
     final URI requestUri = m_uriInfo.getRequestUri();
     try {
       return new URI(
           requestUri.getScheme(),
           requestUri.getUserInfo(),
           requestUri.getHost(),
           requestUri.getPort(),
           requestUri.getPath().replaceAll("/$", ""),
           null,
           null);
     } catch (final URISyntaxException e) {
       return requestUri;
     }
   } else {
     UriBuilder builder = m_uriInfo.getRequestUriBuilder();
     for (final Object component : pathComponents) {
       if (component != null) {
         builder = builder.path(component.toString());
       }
     }
     return builder.build();
   }
 }
 public TreatmentRepresentation(TreatmentDto treatmentDTO, UriInfo context) {
   this.diagnosis = treatmentDTO.getDiagnosis();
   this.patient.setRelation(Representation.RELATION_PATIENT);
   this.patient.setMediaType(Representation.MEDTA_TYPE);
   UriBuilder ub1 = context.getBaseUriBuilder();
   this.patient.setUrl(
       ub1.path("patient").path("{id}").build(treatmentDTO.getPatientId()).toString());
   this.provider.setRelation(Representation.RELATION_PROVIDER);
   this.provider.setMediaType(Representation.MEDTA_TYPE);
   UriBuilder ub2 = context.getBaseUriBuilder();
   this.provider.setUrl(
       ub2.path("provider").path("{id}").build(treatmentDTO.getPatientId()).toString());
   if (treatmentDTO.TreatmentType instanceof DrugTreatmentType) {
     DrugTreatmentType dt = (DrugTreatmentType) treatmentDTO.TreatmentType;
     this.drugTreatment.setDosage(dt.getDosage());
     this.drugTreatment.setName(dt.getName());
   } else if (treatmentDTO.TreatmentType instanceof SurgeryType) {
     this.surgery.setDate(((SurgeryType) treatmentDTO.TreatmentType).getDate());
   } else if (treatmentDTO.TreatmentType instanceof RadiologyType) {
     List<Date> dates = ((RadiologyType) treatmentDTO.TreatmentType).getDate();
     List<Date> treatmentDates = this.radiology.getDate();
     for (Date i : dates) {
       treatmentDates.add(i);
     }
   }
 }
Ejemplo n.º 4
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);
  }
Ejemplo n.º 5
0
  @GET
  @Path("template")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveTemplate(
      @Context final UriInfo uriInfo,
      @QueryParam("officeId") final Long officeId,
      @QueryParam("center") final boolean isCenterGroup,
      @QueryParam("centerId") final Long centerId,
      @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly")
          final boolean staffInSelectedOfficeOnly) {

    this.context
        .authenticatedUser()
        .validateHasReadPermission(GroupingTypesApiConstants.GROUP_RESOURCE_NAME);

    if (centerId != null) {
      final GroupGeneralData centerGroupTemplate =
          this.centerReadPlatformService.retrieveCenterGroupTemplate(centerId);
      final ApiRequestJsonSerializationSettings settings =
          this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
      return this.groupGeneralApiJsonSerializer.serialize(
          settings,
          centerGroupTemplate,
          GroupingTypesApiConstants.CENTER_GROUP_RESPONSE_DATA_PARAMETERS);
    }

    final GroupGeneralData groupTemplate =
        this.groupReadPlatformService.retrieveTemplate(
            officeId, isCenterGroup, staffInSelectedOfficeOnly);
    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.groupGeneralApiJsonSerializer.serialize(
        settings, groupTemplate, GroupingTypesApiConstants.GROUP_RESPONSE_DATA_PARAMETERS);
  }
  /** {@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 method for creating an instance of ContactResource
   *
   * @param content representation for the new resource
   * @return an HTTP response with content of the created resource
   */
  @POST // Create
  @Consumes({
    MediaType.APPLICATION_XML,
    MediaType.APPLICATION_JSON,
    MediaType.TEXT_PLAIN,
    MediaType.TEXT_HTML
  })
  @Produces({
    MediaType.APPLICATION_XML,
    MediaType.APPLICATION_JSON,
    MediaType.TEXT_PLAIN,
    MediaType.TEXT_HTML
  })
  public Response postXmlOrJson(PhoneDirectoryEntry myEntry) {
    String phoneNo = myEntry.getPhoneNo();
    boolean recordExist = phoneDirectoryDAO.checkPhoneNoExist(phoneNo);

    if (recordExist == true) {
      return Response.status(Response.Status.CONFLICT) // .CONFLICT
          .header(
              "Location ",
              String.format("%s%s", context.getAbsolutePath().toString(), myEntry.getPhoneNo()))
          .entity("<PhoneNumber_AlreadyExists PhoneNumber = '" + phoneNo + "'>")
          .build();
    } else {
      phoneDirectoryDAO.addPhoneNumber(myEntry);

      return Response.status(Response.Status.CREATED)
          .header(
              "Location ",
              String.format("%s%s", context.getAbsolutePath().toString(), myEntry.getPhoneNo()))
          .entity(myEntry)
          .build();
    }
  }
Ejemplo n.º 8
0
  public static Package toPackage(ModuleItem p, UriInfo uriInfo) {
    PackageMetadata metadata = new PackageMetadata();
    metadata.setUuid(p.getUUID());
    metadata.setCreated(p.getCreatedDate().getTime());
    metadata.setState((p.getState() != null) ? p.getState().getName() : "");
    metadata.setArchived(p.isArchived());
    metadata.setVersionNumber(p.getVersionNumber());
    metadata.setCheckinComment(p.getCheckinComment());

    Package ret = new Package();
    ret.setMetadata(metadata);
    ret.setTitle(p.getTitle());
    ret.setAuthor(p.getLastContributor());
    ret.setPublished(p.getLastModified().getTime());
    ret.setDescription(p.getDescription());

    ret.setBinaryLink(
        uriInfo.getBaseUriBuilder().path("/packages/{packageName}/binary").build(p.getName()));
    ret.setSourceLink(
        uriInfo.getBaseUriBuilder().path("/packages/{packageName}/source").build(p.getName()));
    // ret.setSnapshot(p.getSnapshotName());

    Iterator<AssetItem> iter = p.getAssets();
    Set<URI> assets = new HashSet<URI>();
    while (iter.hasNext()) {
      AssetItem a = iter.next();
      Asset asset = toAsset(a, uriInfo);
      assets.add(asset.getRefLink());
    }

    ret.setAssets(assets);
    return ret;
  }
Ejemplo n.º 9
0
  @Test
  public void testVisit_Tree_MapBy() {

    DB.insert("e2", "id, name", "1, 'xxx'");
    DB.insert("e2", "id, name", "2, 'yyy'");
    DB.insert("e2", "id, name", "3, 'zzz'");

    DB.insert("e5", "id, name", "1, 'xxx'");
    DB.insert("e5", "id, name", "2, 'yyy'");

    DB.insert("e3", "id, e2_id, e5_id, name", "7, 2, 1, 'zzz'");
    DB.insert("e3", "id, e2_id, e5_id, name", "8, 1, 1, 'yyy'");
    DB.insert("e3", "id, e2_id, e5_id, name", "9, 1, 2, 'zzz'");

    MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
    params.putSingle("include", "{\"path\":\"e3s\",\"sort\":\"id\"}");
    params.putSingle("include", "e3s.e5");
    params.putSingle("mapBy", "name");

    UriInfo mockUri = mock(UriInfo.class);
    when(mockUri.getQueryParameters()).thenReturn(params);

    DataResponse<E2> response = createLRService().select(E2.class).uri(mockUri).select();

    PushPopVisitor visitor = new PushPopVisitor();

    assertEquals("E3:8;E3:9;E3:7", responseContents(response, visitor));
  }
Ejemplo n.º 10
0
  @PUT
  public Response putItem(@Context HttpHeaders headers, byte[] data) {
    System.out.println("PUT ITEM " + container + " " + item);

    URI uri = uriInfo.getAbsolutePath();
    MediaType mimeType = headers.getMediaType();
    GregorianCalendar gc = new GregorianCalendar();
    gc.set(GregorianCalendar.MILLISECOND, 0);
    Item i = new Item(item, uri.toString(), mimeType.toString(), gc);
    String digest = computeDigest(data);
    i.setDigest(digest);

    Response r;
    if (!MemoryStore.MS.hasItem(container, item)) {
      r = Response.created(uri).build();
    } else {
      r = Response.noContent().build();
    }

    Item ii = MemoryStore.MS.createOrUpdateItem(container, i, data);
    if (ii == null) {
      // Create the container if one has not been created
      URI containerUri = uriInfo.getAbsolutePathBuilder().path("..").build().normalize();
      Container c = new Container(container, containerUri.toString());
      MemoryStore.MS.createContainer(c);
      i = MemoryStore.MS.createOrUpdateItem(container, i, data);
      if (i == null) throw new NotFoundException("Container not found");
    }

    return r;
  }
  private UriInfo setUpCmdExpectations(
      String[] commands, String[] returns, String collectionType, String newId, boolean build)
      throws Exception {
    mockStatic(PowerShellCmd.class);
    for (int i = 0; i < Math.min(commands.length, returns.length); i++) {
      if (commands[i] != null) {
        expect(PowerShellCmd.runCommand(setUpPoolExpectations(), commands[i]))
            .andReturn(returns[i]);
      }
    }

    UriInfo uriInfo = null;
    if (collectionType != null && newId != null) {
      uriInfo = setUpBasicUriExpectations();
      if (build) {
        UriBuilder uriBuilder = createMock(UriBuilder.class);
        expect(uriInfo.getAbsolutePathBuilder()).andReturn(uriBuilder);
        expect(uriBuilder.path(newId)).andReturn(uriBuilder);
        expect(uriBuilder.build())
            .andReturn(new URI("vms/" + VM_ID + "/" + collectionType + "/" + newId))
            .anyTimes();
      }
    }

    replayAll();

    return uriInfo;
  }
Ejemplo n.º 12
0
  @GET
  @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
  @Produces(MediaType.APPLICATION_JSON)
  @ApiOperation(value = "Polls the data for a sitemap.", response = PageDTO.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(
            code = 404,
            message =
                "Sitemap with requested name does not exist or page does not exist, or page refers to a non-linkable widget")
      })
  public Response getPageData(
      @Context HttpHeaders headers,
      @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
      @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
      @PathParam("pageid") @ApiParam(value = "page id") String pageId) {
    final Locale locale = LocaleUtil.getLocale(language);
    logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());

    if (headers.getRequestHeader("X-Atmosphere-Transport") != null) {
      // Make the REST-API pseudo-compatible with openHAB 1.x
      // The client asks Atmosphere for server push functionality,
      // so we do a simply listening for changes on the appropriate items
      blockUnlessChangeOccurs(sitemapname, pageId);
    }
    Object responseObject =
        getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build(), locale);
    return Response.ok(responseObject).build();
  }
Ejemplo n.º 13
0
 @SuppressWarnings({"unchecked"})
 private UriInfo mockEmptyUriInfo() {
   UriInfo uriInfo = mock(UriInfo.class);
   when(uriInfo.getPathParameters(true)).thenReturn(mock(MultivaluedMap.class));
   when(uriInfo.getQueryParameters(true)).thenReturn(mock(MultivaluedMap.class));
   return uriInfo;
 }
Ejemplo n.º 14
0
 @Override
 public void filter(ContainerRequestContext requestContext) throws IOException {
   UriInfo uriInfo = requestContext.getUriInfo();
   MultivaluedMap<String, String> params = uriInfo.getPathParameters();
   String formationId = params.getFirst("formationId");
   String year = params.getFirst("annee");
   String semester = params.getFirst("semestre");
   try {
     if (uePromoDao
             .queryBuilder()
             .where()
             .eq("formation_id", formationId)
             .and()
             .eq("year", year)
             .and()
             .eq("semester", semester)
             .countOf()
         == 0) {
       requestContext.abortWith(Response.status(Response.Status.NOT_FOUND).build());
     }
   } catch (SQLException e) {
     e.printStackTrace();
     requestContext.abortWith(Response.serverError().build());
   }
 }
Ejemplo n.º 15
0
  /** Migrated Jersey 1.x {@code com.sun.jersey.impl.QueryParametersHttpRequestTest}. */
  @Test
  public void testGetQueryParametersDecoded() throws Exception {
    UriInfo ui;
    MultivaluedMap<String, String> p;

    ui = createContext("/widgets/10?x+=+1%20&%20y+=+2", "GET");
    p = ui.getQueryParameters();
    assertEquals(" 1 ", p.getFirst("x "));
    assertEquals(" 2", p.getFirst(" y "));

    ui = createContext("/widgets/10?x=1&y=1+%2B+2", "GET");
    p = ui.getQueryParameters(true);
    assertEquals("1", p.getFirst("x"));
    assertEquals("1 + 2", p.getFirst("y"));

    ui = createContext("/widgets/10?x=1&y=1+%26+2", "GET");
    p = ui.getQueryParameters(true);
    assertEquals("1", p.getFirst("x"));
    assertEquals("1 & 2", p.getFirst("y"));

    ui = createContext("/widgets/10?x=1&y=1+%7C%7C+2", "GET");
    p = ui.getQueryParameters(true);
    assertEquals("1", p.getFirst("x"));
    assertEquals("1 || 2", p.getFirst("y"));
  }
Ejemplo n.º 16
0
 /**
  * Endpoint for executing reset credentials flow. If code is null, a client session is created
  * with the account service as the client. Successful reset sends you to the account page. Note,
  * account service must be enabled.
  *
  * @param code
  * @param execution
  * @return
  */
 @Path(RESET_CREDENTIALS_PATH)
 @GET
 public Response resetCredentialsGET(
     @QueryParam("code") String code, @QueryParam("execution") String execution) {
   // we allow applications to link to reset credentials without going through OAuth or SAML
   // handshakes
   //
   if (code == null) {
     if (!realm.isResetPasswordAllowed()) {
       event.event(EventType.RESET_PASSWORD);
       event.error(Errors.NOT_ALLOWED);
       return ErrorPage.error(session, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
     }
     // set up the account service as the endpoint to call.
     ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
     ClientSessionModel clientSession = session.sessions().createClientSession(realm, client);
     clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name());
     clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret());
     // clientSession.setNote(AuthenticationManager.END_AFTER_REQUIRED_ACTIONS, "true");
     clientSession.setAuthMethod(OIDCLoginProtocol.LOGIN_PROTOCOL);
     String redirectUri =
         Urls.accountBase(uriInfo.getBaseUri()).path("/").build(realm.getName()).toString();
     clientSession.setRedirectUri(redirectUri);
     clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name());
     clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret());
     clientSession.setNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
     clientSession.setNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
     clientSession.setNote(
         OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
     return processResetCredentials(null, clientSession, null);
   }
   return resetCredentials(code, execution);
 }
Ejemplo n.º 17
0
 public static WriterParameters parseWriterParameters(final UriInfo info) {
   WriterParameters.WriterParametersBuilder wpBuilder =
       new WriterParameters.WriterParametersBuilder();
   String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
   if (!Strings.isNullOrEmpty(param) && !"unbounded".equals(param)) {
     try {
       final int depth = Integer.valueOf(param);
       if (depth < 1) {
         throw new RestconfDocumentedException(
             new RestconfError(
                 RestconfError.ErrorType.PROTOCOL,
                 RestconfError.ErrorTag.INVALID_VALUE,
                 "Invalid depth parameter: " + depth,
                 null,
                 "The depth parameter must be an integer > 1 or \"unbounded\""));
       }
       wpBuilder.setDepth(depth);
     } catch (final NumberFormatException e) {
       throw new RestconfDocumentedException(
           new RestconfError(
               RestconfError.ErrorType.PROTOCOL,
               RestconfError.ErrorTag.INVALID_VALUE,
               "Invalid depth parameter: " + e.getMessage(),
               null,
               "The depth parameter must be an integer > 1 or \"unbounded\""));
     }
   }
   param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
   wpBuilder.setPrettyPrint("true".equals(param));
   return wpBuilder.build();
 }
  @Test
  public void testContextUriInfoUtil1stPassPathParamsQueryP() throws URISyntaxException {

    String dasBaseUri = "http://localhost:port/";

    Map<String, String> pathParams = new HashMap<String, String>();
    pathParams.put("aa", "2.16.840.1.113883.4.349");
    pathParams.put("pid", "1012581676V377802");
    pathParams.put("profile", "benefits");
    pathParams.put("domain", "integratedCare");
    pathParams.put("speciality", "careCoordinatorProfiles");

    String queryP = "?zzzzzz=3333333&xxxxx=111111&yyyy=22222";

    Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put("zzzzzz", "3333333");
    queryParams.put("xxxxx", "111111");
    queryParams.put("yyyy", "22222");

    javax.ws.rs.core.UriInfo contextUriInfo =
        ContextUriInfoUtil.createUriInfo(dasBaseUri, null, pathParams, queryP, queryParams);

    System.out.println("baseUri: " + contextUriInfo.getBaseUri());
    System.out.println("path: " + contextUriInfo.getPath());
    System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath());
    System.out.println("requestUri: " + contextUriInfo.getRequestUri());
    System.out.println("");
  }
Ejemplo n.º 19
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;
  }
Ejemplo n.º 20
0
 @POST
 @Path("blueprint/{name}")
 public Response createBlueprint(
     @Context UriInfo uri, @PathParam("name") String name, ConfigManifest blueprint) {
   Response res;
   try {
     ZooKeeper zk = Controller.getInstance().getZKInstance();
     blueprint.setUrl(uri.getAbsolutePath().toURL());
     byte[] data = JAXBUtil.write(blueprint);
     Stat stat =
         zk.exists(
             CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name, false);
     if (stat == null) {
       zk.create(
           CommonConfigurationKeys.ZOOKEEPER_CONFIG_BLUEPRINT_PATH_DEFAULT + '/' + name,
           data,
           Ids.OPEN_ACL_UNSAFE,
           CreateMode.PERSISTENT);
     } else {
       throw new WebApplicationException(409);
     }
     res = Response.created(uri.getAbsolutePath()).build();
     return res;
   } catch (WebApplicationException e) {
     throw e;
   } catch (Exception e) {
     LOG.error(ExceptionUtil.getStackTrace(e));
     throw new WebApplicationException(500);
   }
 }
  @Test
  public void testContextUriInfoUtil2nd2ndPassPathParamsQueryParams() throws URISyntaxException {

    String dasBaseUri = "http://localhost:port/";

    Map<String, String> pathParams = new HashMap<String, String>();
    pathParams.put("aa", "2.16.840.1.113883.4.349");
    pathParams.put("pid", "1012581676V377802");
    pathParams.put("profile", "benefits");
    pathParams.put("domain", "integratedCare");
    pathParams.put("speciality", "careCoordinatorProfiles");
    pathParams.put("homeCommunityId", "2.16.840.1.113883.4.349.3");
    pathParams.put("remoteRepositoryId", "3.33.333.3.333333.3.333");
    pathParams.put("documentUniqueId", "1001");
    pathParams.put("fileExtension", "xml");

    Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put("queryParamName1", "queryParamValue1");
    queryParams.put("queryParamName2", "queryParamValue2");
    queryParams.put("queryParamName3", "queryParamValue3");

    javax.ws.rs.core.UriInfo contextUriInfo =
        ContextUriInfoUtil.createUriInfo(dasBaseUri, pathParams, queryParams);

    System.out.println("baseUri: " + contextUriInfo.getBaseUri());
    System.out.println("path: " + contextUriInfo.getPath());
    System.out.println("absolutePath: " + contextUriInfo.getAbsolutePath());
    System.out.println("requestUri: " + contextUriInfo.getRequestUri());
    System.out.println("");
  }
Ejemplo n.º 22
0
  /*
   * curl --data "name=Test&lastname=Tester&[email protected]&password=test" http://localhost:8080/prostalytics/rest/auth/register
   *
   */
  @Path("/register")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.TEXT_HTML)
  public Response register(
      @FormParam("email") String email,
      @FormParam("name") String name,
      @FormParam("lastname") String lastName,
      @FormParam("password") String password)
      throws URISyntaxException {

    try {
      User user = new User();
      user.setName(name);
      user.setLastname(lastName);
      user.setEmail(email);
      user.setPassword(hashPassword(password));
      validate(user);

      userDao.saveUser(user);

      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromAuthRegister(Navigation.OK)))
              .build();
      return Response.seeOther(uri).build();
    } catch (Throwable e) {
      e.printStackTrace(); // TODO :)
      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromAuthRegister(Navigation.ERROR, e)))
              .build();
      return Response.seeOther(uri).build();
    }
  }
Ejemplo n.º 23
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"));
  }
Ejemplo n.º 24
0
  @Override
  public void filter(ContainerRequestContext rc) throws IOException {
    checkSecurityContextStart(rc);
    UriInfo ui = rc.getUriInfo();
    String absoluteRequestUri = ui.getAbsolutePath().toString();

    boolean sameUriRedirect = false;
    if (completeUri == null) {
      String referer = rc.getHeaderString("Referer");
      if (referer != null && referer.startsWith(authorizationServiceUri)) {
        completeUri = absoluteRequestUri;
        sameUriRedirect = true;
      }
    }

    if (!sameUriRedirect && absoluteRequestUri.endsWith(startUri)) {
      ClientTokenContext request = getClientTokenContext(rc);
      if (request != null) {
        setClientCodeRequest(request);
        if (completeUri != null) {
          rc.setRequestUri(URI.create(completeUri));
        }
        return;
      }
      Response codeResponse = createCodeResponse(rc, ui);
      rc.abortWith(codeResponse);
    } else if (absoluteRequestUri.endsWith(completeUri)) {
      MultivaluedMap<String, String> requestParams = toRequestState(rc, ui);
      processCodeResponse(rc, ui, requestParams);
      checkSecurityContextEnd(rc, requestParams);
    }
  }
  public String getOverview(UriInfo uriInfo) {
    // verify interaction URI is valid
    findInteraction();

    StringBuilder buffer = new StringBuilder();

    buffer
        .append("<html>")
        .append("<head></head>")
        .append("<body>")
        .append("<p><a href='")
        .append(uriInfo.getAbsolutePath())
        .append("/definition'>Show Interaction Definition</a></p>")
        .append("<p><a href='")
        .append(uriInfo.getAbsolutePath())
        .append("/owner'>Show Interaction Owner</a></p>")
        .append("<p><a href='")
        .append(uriInfo.getAbsolutePath())
        .append("/inData'>Show In Data Values</a></p>")
        .append("<p><a href='")
        .append(uriInfo.getAbsolutePath())
        .append("/outData'>Submit Out Data Values</a></p>")
        .append("</body></html>");

    return buffer.toString();
  }
Ejemplo n.º 26
0
  /* Test the contract for multipart POST commands.
   * A POST command should should receive an InteractionContext that has the new resource set; enabling the
   * command to process the resource contained in the current part of the multipart request
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testMultipartPostCommandReceivesResource() throws InteractionException {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    initialState.addTransition(
        new Transition.Builder().method("POST").target(initialState).build());
    // create a mock command to test the context is initialised correctly
    InteractionCommand mockCommand = mock(InteractionCommand.class);
    when(mockCommand.execute(any(InteractionContext.class))).thenReturn(Result.SUCCESS);
    // RIM with command controller that issues commands that always return SUCCESS
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(mockCommand),
            new ResourceStateMachine(initialState),
            createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));

    InMultiPart inMP = mock(InMultiPart.class);
    when(inMP.hasNext()).thenReturn(true, false);
    when(inMP.next()).thenReturn(mock(InPart.class));

    rim.post(mock(HttpHeaders.class), uriInfo, inMP);
    verify(mockCommand)
        .execute((InteractionContext) argThat(new CommandReceivesResourceArgumentMatcher()));
  }
Ejemplo n.º 27
0
  /** Migrated Jersey 1.x {@code com.sun.jersey.impl.QueryParametersHttpRequestTest}. */
  @Test
  public void testGetQueryParametersEncoded() throws Exception {
    final UriInfo ui = createContext("/widgets/10?x+=+1%20&%20y+=+2", "GET");
    MultivaluedMap<String, String> p = ui.getQueryParameters(false);

    assertEquals("+1%20", p.getFirst("x "));
    assertEquals("+2", p.getFirst(" y "));
  }
Ejemplo n.º 28
0
  @Override
  public SearchResults search(MessageContext context) throws PieceworkException {
    UriInfo uriInfo = context.getContext(UriInfo.class);

    MultivaluedMap<String, String> rawQueryParameters =
        uriInfo != null ? uriInfo.getQueryParameters() : null;
    return search(rawQueryParameters);
  }
Ejemplo n.º 29
0
  @Path("/{requestId}/status")
  @GET
  @ApiOperation(
      value = "Get the status of this request",
      notes = "The status is either queued, running, or stopped.",
      response = java.lang.String.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 400, message = "No request id supplied"),
        @ApiResponse(code = 404, message = "Request not found"),
        @ApiResponse(
            code = 500,
            message = "Unable to complete request, see response body for error details")
      })
  public Response getStatus(
      @ApiParam(value = "The request id", required = true) @PathParam("requestId") String requestId,
      @Context UriInfo uriInfo) {

    ServiceResponse<JobStatus> sr = macroService.getStatus(requestId);

    if (sr.isRequestOk()) {
      JobStatus status = sr.getPayload();
      if (status.equals(JobStatus.RUNNING)) {
        return Response.status(Status.SEE_OTHER)
            .entity(status.name())
            .location(
                UriBuilder.fromUri(uriInfo.getBaseUri())
                    .path(getClass())
                    .path(requestId)
                    .path("log/tail")
                    .build())
            .build();
      } else if (status.equals(JobStatus.PENDING)) {
        return Response.status(Status.SEE_OTHER)
            .entity(status.name())
            .location(
                UriBuilder.fromUri(uriInfo.getBaseUri())
                    .path(getClass())
                    .path(requestId)
                    .path("status")
                    .build())
            .build();

      } else {
        return Response.status(Status.SEE_OTHER)
            .entity(status.name())
            .location(
                UriBuilder.fromUri(uriInfo.getBaseUri())
                    .path(getClass())
                    .path(requestId)
                    .path("log")
                    .build())
            .build();
      }
    } else {
      return Response.status(500).entity(sr.getMessagesAsStrings()).build();
    }
  }
Ejemplo n.º 30
0
  @SuppressWarnings("unchecked")
  @Test
  public void testPutCommandWithIfMatchHeader() throws InteractionException {
    ResourceState initialState = new ResourceState("entity", "state", mockActions(), "/test");
    initialState.addTransition(new Transition.Builder().method("PUT").target(initialState).build());

    // this test incorrectly supplies a resource as a result of the command.
    InteractionCommand mockCommand =
        new InteractionCommand() {
          public Result execute(InteractionContext ctx) {
            assertNotNull(ctx.getResource());
            assertNull(
                ctx.getResource().getEntityTag()); // Etag is a response header and should be null
            assertNotNull(ctx.getPreconditionIfMatch());
            assertEquals("ABCDEFG", ctx.getPreconditionIfMatch());
            return Result.SUCCESS;
          }
        };

    // RIM with command controller that issues commands that always return SUCCESS
    HTTPHypermediaRIM rim =
        new HTTPHypermediaRIM(
            mockCommandController(mockCommand),
            new ResourceStateMachine(initialState),
            createMockMetadata());

    UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getPathParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));
    when(uriInfo.getQueryParameters(anyBoolean())).thenReturn(mock(MultivaluedMap.class));

    // EntityResource without Etag
    EntityResource<Object> er = new EntityResource<Object>("test resource");

    // Apply If-Match header
    HttpHeaders httpHeaders = mock(HttpHeaders.class);
    doAnswer(
            new Answer<List<String>>() {
              @SuppressWarnings("serial")
              @Override
              public List<String> answer(InvocationOnMock invocation) throws Throwable {
                String headerName = (String) invocation.getArguments()[0];
                if (headerName.equals(HttpHeaders.IF_MATCH)) {
                  return new ArrayList<String>() {
                    {
                      add("ABCDEFG");
                    }
                  };
                }
                return null;
              }
            })
        .when(httpHeaders)
        .getRequestHeader(any(String.class));

    // execute
    rim.put(httpHeaders, "id", uriInfo, er);
  }