Пример #1
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();
 }
Пример #2
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);
  }
Пример #3
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"));
  }
  @GET
  @Path("{productId}")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveSavingProductDetails(
      @PathParam("productId") final Long productId, @Context final UriInfo uriInfo) {

    context.authenticatedUser().validateHasReadPermission(entityType);

    Set<String> typicalResponseParameters =
        new HashSet<String>(
            Arrays.asList(
                "id",
                "createdOn",
                "lastModifedOn",
                "locale",
                "name",
                "description",
                "currencyCode",
                "digitsAfterDecimal",
                "interstRate",
                "minInterestRate",
                "maxInterestRate",
                "savingsDepositAmount",
                "savingProductType",
                "tenureType",
                "tenure",
                "frequency",
                "interestType",
                "interestCalculationMethod",
                "minimumBalanceForWithdrawal",
                "isPartialDepositAllowed",
                "isLockinPeriodAllowed",
                "lockinPeriod",
                "lockinPeriodType",
                "depositEvery"));

    Set<String> responseParameters =
        ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
    if (responseParameters.isEmpty()) {
      responseParameters.addAll(typicalResponseParameters);
    }

    SavingProductData savingProduct =
        this.savingProductReadPlatformService.retrieveSavingProduct(productId);

    boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());
    boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters());
    if (template) {
      savingProduct = handleTemplateRelatedData(responseParameters, savingProduct);
    }

    return this.apiJsonSerializerService.serializeSavingProductDataToJson(
        prettyPrint, responseParameters, savingProduct);
  }
  /*
   * see
   * http://stackoverflow.com/questions/5250074/what-uri-can-be-used-to-request
   * -a-default-resource
   */
  @GET
  @Path("template")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveNewLoanProductDetails(@Context final UriInfo uriInfo) {

    // TODO - KW - every addition of a parameter here requires same addition in supported params
    // used in 'apiDataConversionService' method.
    Set<String> typicalResponseParameters =
        new HashSet<String>(
            Arrays.asList(
                "id",
                "name",
                "description",
                "fundId",
                "fundName",
                "transactionProcessingStrategyId",
                "transactionProcessingStrategyName",
                "principal",
                "inArrearsTolerance",
                "numberOfRepayments",
                "repaymentEvery",
                "interestRatePerPeriod",
                "annualInterestRate",
                "repaymentFrequencyType",
                "interestRateFrequencyType",
                "amortizationType",
                "interestType",
                "interestCalculationPeriodType",
                "charges",
                "createdOn",
                "lastModifedOn",
                "currencyOptions",
                "amortizationTypeOptions",
                "interestTypeOptions",
                "interestCalculationPeriodTypeOptions",
                "repaymentFrequencyTypeOptions",
                "interestRateFrequencyTypeOptions",
                "fundOptions",
                "transactionProcessingStrategyOptions",
                "chargeOptions"));

    Set<String> responseParameters =
        ApiParameterHelper.extractFieldsForResponseIfProvided(uriInfo.getQueryParameters());
    if (responseParameters.isEmpty()) {
      responseParameters.addAll(typicalResponseParameters);
    }
    boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters());

    LoanProductData loanProduct =
        this.loanProductReadPlatformService.retrieveNewLoanProductDetails();

    return this.apiJsonSerializerService.serializeLoanProductDataToJson(
        prettyPrint, responseParameters, loanProduct);
  }
Пример #6
0
  @GET
  @Path("{groupId}/clientstransfertemplate")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveClientTranferTemplate(
      @Context final UriInfo uriInfo,
      @PathParam("groupId") final Long groupId,
      @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly")
          final boolean staffInSelectedOfficeOnly) {

    this.context.authenticatedUser().validateHasReadPermission("GROUP");
    GroupGeneralData group = this.groupReadPlatformService.retrieveOne(groupId);

    final boolean transferActiveLoans = true;
    final boolean inheritDestinationGroupLoanOfficer = true;

    Collection<ClientData> membersOfGroup =
        this.clientReadPlatformService.retrieveClientMembersOfGroup(groupId);
    if (CollectionUtils.isEmpty(membersOfGroup)) {
      membersOfGroup = null;
    }

    final boolean loanOfficersOnly = false;
    Collection<StaffData> staffOptions = null;
    if (staffInSelectedOfficeOnly) {
      staffOptions = this.staffReadPlatformService.retrieveAllStaffForDropdown(group.officeId());
    } else {
      staffOptions =
          this.staffReadPlatformService.retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(
              group.officeId(), loanOfficersOnly);
    }
    if (CollectionUtils.isEmpty(staffOptions)) {
      staffOptions = null;
    }

    Collection<GroupGeneralData> groupOptions =
        this.groupReadPlatformService.retrieveGroupsForLookup(group.officeId(), groupId);
    GroupTransferData data =
        GroupTransferData.template(
            groupId,
            membersOfGroup,
            groupOptions,
            staffOptions,
            transferActiveLoans,
            inheritDestinationGroupLoanOfficer);

    final Set<String> GROUP_TRANSFERS_DATA_PARAMETERS =
        new HashSet<String>(
            Arrays.asList(
                "groupId",
                "clientOptions",
                "groupOptions",
                "staffOptions",
                "transferActiveLoans",
                "inheritDestinationGroupLoanOfficer"));

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(settings, data, GROUP_TRANSFERS_DATA_PARAMETERS);
  }
Пример #7
0
  @GET
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveAll(
      @Context final UriInfo uriInfo,
      @QueryParam("sqlSearch") final String sqlSearch,
      @QueryParam("officeId") final Long officeId,
      @QueryParam("externalId") final String externalId,
      @QueryParam("name") final String name,
      @QueryParam("underHierarchy") final String hierarchy,
      @QueryParam("offset") final Integer offset,
      @QueryParam("limit") final Integer limit,
      @QueryParam("orderBy") final String orderBy,
      @QueryParam("sortOrder") final String sortOrder) {

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

    final SearchParameters searchParameters =
        SearchParameters.forGroups(
            sqlSearch, officeId, externalId, name, hierarchy, offset, limit, orderBy, sortOrder);
    final Page<GroupGeneralData> groups =
        this.groupReadPlatformService.retrieveAll(searchParameters);

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(
        settings, groups, GroupingTypesApiConstants.GROUP_RESPONSE_DATA_PARAMETERS);
  }
  @GET
  @Path("template")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveTemplate(
      @PathParam("fixedDepositAccountId") final Long fixedDepositAccountId,
      // @QueryParam("command") final String commandParam,
      @Context final UriInfo uriInfo) {

    this.context
        .authenticatedUser()
        .validateHasReadPermission(DepositsApiConstants.FIXED_DEPOSIT_ACCOUNT_RESOURCE_NAME);

    SavingsAccountTransactionData savingsAccount =
        this.savingsAccountReadPlatformService.retrieveDepositTransactionTemplate(
            fixedDepositAccountId, DepositAccountType.FIXED_DEPOSIT);
    final Collection<PaymentTypeData> paymentTypeOptions =
        this.paymentTypeReadPlatformService.retrieveAllPaymentTypes();

    savingsAccount =
        SavingsAccountTransactionData.templateOnTop(savingsAccount, paymentTypeOptions);

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(
        settings, savingsAccount, SavingsApiConstants.SAVINGS_TRANSACTION_RESPONSE_DATA_PARAMETERS);
  }
  /**
   * 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);
    }
  }
  @GET
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveAllSavingsAccountCharges(
      @PathParam("savingsAccountId") final Long savingsAccountId,
      @DefaultValue("all") @QueryParam("chargeStatus") final String chargeStatus,
      @Context final UriInfo uriInfo) {

    this.context
        .authenticatedUser()
        .validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME);

    if (!(is(chargeStatus, "all") || is(chargeStatus, "active") || is(chargeStatus, "inactive"))) {
      throw new UnrecognizedQueryParamException(
          "status", chargeStatus, new Object[] {"all", "active", "inactive"});
    }

    final Collection<SavingsAccountChargeData> savingsAccountCharges =
        this.savingsAccountChargeReadPlatformService.retrieveSavingsAccountCharges(
            savingsAccountId, chargeStatus);

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(
        settings,
        savingsAccountCharges,
        SavingsApiConstants.SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS);
  }
  @GET
  @Path("accounts/template")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String accountsTemplate(
      @QueryParam("clientId") final Long clientId,
      @PathParam("loanId") final Long loanId,
      @Context final UriInfo uriInfo) {

    this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);

    PortfolioAccountDTO portfolioAccountDTO =
        new PortfolioAccountDTO(PortfolioAccountType.SAVINGS.getValue(), clientId, null);
    Collection<PortfolioAccountData> accountLinkingOptions = null;
    if (this.loanReadPlatformService.isGuaranteeRequired(loanId)) {
      accountLinkingOptions =
          this.portfolioAccountReadPlatformService.retrieveAllForLookup(portfolioAccountDTO);
    }
    final GuarantorData guarantorData =
        GuarantorData.template(null, null, null, accountLinkingOptions);
    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.apiJsonSerializerService.serialize(
        settings, guarantorData, AccountTransfersApiConstants.RESPONSE_DATA_PARAMETERS);
  }
  @GET
  @Path("template")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String newGuarantorTemplate(@Context final UriInfo uriInfo) {
    this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission);

    final List<EnumOptionData> guarantorTypeOptions =
        GuarantorEnumerations.guarantorType(GuarantorType.values());
    final Collection<CodeValueData> allowedClientRelationshipTypes =
        this.codeValueReadPlatformService.retrieveCodeValuesByCode(
            GuarantorConstants.GUARANTOR_RELATIONSHIP_CODE_NAME);
    final Collection<CodeValueData> allowedGncbTypes =
        this.codeValueReadPlatformService.retrieveCodeValuesByCode(
            GuarantorConstants.GNCB_RELATIONSHIP_CODE_NAME);

    final Collection<PortfolioAccountData> accountLinkingOptions = null;
    final GuarantorData guarantorData =
        GuarantorData.template(
            guarantorTypeOptions,
            allowedClientRelationshipTypes,
            allowedGncbTypes,
            accountLinkingOptions);

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.apiJsonSerializerService.serialize(
        settings, guarantorData, RESPONSE_DATA_PARAMETERS);
  }
Пример #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));
 }
 @GET
 @Path("/count")
 @Produces(MediaType.APPLICATION_JSON)
 public CountResultDto getIncidentsCount(@Context UriInfo uriInfo) {
   IncidentQueryDto queryParameter = new IncidentQueryDto(uriInfo.getQueryParameters());
   return queryIncidentsCount(queryParameter);
 }
  /**
   * This method <code>retrieveMessageTemplate</code> used for Retrieving the Particular Message
   * Template with it's Parameters.
   *
   * @param messageId id of the MessageTemplate
   * @param uriInfo Containing Url information
   * @return
   */
  @GET
  @Path("{messageId}")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrieveMessageTemplate(
      @PathParam("messageId") final Long messageId, @Context final UriInfo uriInfo) {

    context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);

    final List<BillingMessageTemplateData> messageParams =
        this.billingMesssageReadPlatformService.retrieveMessageParams(messageId);

    final BillingMessageTemplateData messageType =
        this.billingMesssageReadPlatformService.retrieveTemplate();

    final BillingMessageTemplateData templateData =
        this.billingMesssageReadPlatformService.retrieveMessageTemplate(messageId);
    templateData.setMessageParams(messageParams);
    templateData.setMessageType(messageType.getMessageTypes());

    final ApiRequestJsonSerializationSettings settings =
        apiRequestParameterHelper.process(uriInfo.getQueryParameters());

    return this.toApiJsonSerializer.serialize(settings, templateData, RESPONSE_PARAMETERS);
  }
Пример #16
0
  @GET
  public String retrieveAll(
      @DefaultValue("-1") @QueryParam("typeId") final int typeId,
      @DefaultValue("-1") @QueryParam("entityId") final int entityId,
      @Context final UriInfo uriInfo) {

    this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION);

    // FIXME - we dont use the ORM when doing fetches - we write SQL and fetch through JDBC
    // returning data to be serialized to JSON
    List<Template> templates = new ArrayList<Template>();

    if (typeId != -1 && entityId != -1) {
      templates =
          this.templateService.getAllByEntityAndType(
              TemplateEntity.values()[entityId], TemplateType.values()[typeId]);
    } else {
      templates = this.templateService.getAll();
    }

    final ApiRequestJsonSerializationSettings settings =
        this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    return this.toApiJsonSerializer.serialize(
        settings, templates, this.RESPONSE_TEMPLATES_DATA_PARAMETERS);
  }
Пример #17
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));
  }
Пример #18
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()));
  }
Пример #19
0
  @POST
  @RequireApplicationAccess
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONWithPadding executePost(
      @Context UriInfo ui,
      EntityHolder<Object> body,
      @QueryParam("callback") @DefaultValue("callback") String callback)
      throws Exception {

    logger.debug("ServiceResource.executePost");

    Object json = body.getEntity();

    ApiResponse response = createApiResponse();

    response.setAction("post");
    response.setApplication(services.getApplication());
    response.setParams(ui.getQueryParameters());

    ServicePayload payload = getPayload(json);

    executeServiceRequest(ui, response, ServiceAction.POST, payload);

    return new JSONWithPadding(response, callback);
  }
 /**
  * Returns a message with a multiple values of params
  *
  * @param info Context containing the parameters
  * @return a message with the list of msg and the uniqueMsg
  */
 @GET
 @Path("/multiContext")
 public Response getMessages(@Context UriInfo info) {
   List<String> lStrings = info.getQueryParameters().get("params");
   String result = "Restful example : " + lStrings;
   return Response.status(200).entity(result).build();
 }
 private Type getType(final UriInfo uri, final Type defaultType) {
   try {
     return Type.valueOf(uri.getQueryParameters().getFirst(PARAM_OUTPUT_TYPE));
   } catch (final Exception e) {
     return defaultType;
   }
 }
  /** {@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());
    }
  }
Пример #23
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);
  }
Пример #24
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;
 }
Пример #25
0
  @GET
  @Path("{taxMapId}")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String retrievedSingleTaxMap(
      @PathParam("taxMapId") final Long taxMapId, @Context final UriInfo uriInfo) {

    context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions);
    TaxMapData taxMapData = taxMapReadPlatformService.retrievedSingleTaxMapData(taxMapId);
    final ApiRequestJsonSerializationSettings settings =
        apiRequestParameterHelper.process(uriInfo.getQueryParameters());
    if (settings.isTemplate()) {
      final List<ChargeCodeData> chargeCodeData =
          this.taxMapReadPlatformService.retrivedChargeCodeTemplateData();
      final Collection<MCodeData> taxTypeData =
          this.mCodeReadPlatformService.getCodeValue(CodeNameConstants.CODE_TYPE);
      final List<PriceRegionData> priceRegionData =
          this.regionalPriceReadplatformService.getPriceRegionsDetails();
      taxMapData.setChargeCodesForTax(chargeCodeData);
      taxMapData.setTaxTypeData(taxTypeData);
      taxMapData.setPriceRegionData(priceRegionData);
      taxMapData.setDate(DateUtils.getLocalDateOfTenantForClient());
    }
    return this.apiJsonSerializer.serialize(settings, taxMapData, RESPONSE_TAXMAPPING_PARAMETERS);
  }
Пример #26
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;
  }
 public String getQueryParam(String key) {
   List<String> values = uriInfo.getQueryParameters().get(key);
   if (!values.isEmpty()) {
     return values.get(0);
   }
   return null;
 }
Пример #28
0
 protected Map<String, Serializable> computeConversionParameters(UriInfo uriInfo) {
   MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
   Map<String, Serializable> parameters = new HashMap<>();
   for (String parameterKey : queryParams.keySet()) {
     parameters.put(parameterKey, queryParams.getFirst(parameterKey));
   }
   return parameters;
 }
Пример #29
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 "));
  }
  public static void setupUriInfo(UriInfo uriInfo, Map<String, String> params) {
    MultivaluedMap<String, String> multivaluedMap = mock(MultivaluedMap.class);

    for (Map.Entry<String, String> keyValue : params.entrySet()) {
      when(multivaluedMap.getFirst(keyValue.getKey())).thenReturn(keyValue.getValue());
    }
    when(uriInfo.getQueryParameters()).thenReturn(multivaluedMap);
  }