@Test
  public void testGroupKeyCodeSetExtraction() {
    PayTypeBo pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "1"));
    Set<String> extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet();
    Assert.assertEquals(extractedGroupKeyCodeWithIdSet.size(), 2);
    Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("ISU-IA"));
    Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA"));

    pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "5"));
    extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet();
    Assert.assertEquals(2, extractedGroupKeyCodeWithIdSet.size());
    Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("IU-IN"));
    Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA"));

    pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "2"));
    extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet();
    Assert.assertTrue(
        (extractedGroupKeyCodeWithIdSet == null) || extractedGroupKeyCodeWithIdSet.isEmpty());
    pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "4"));
    extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet();
    Assert.assertTrue(
        (extractedGroupKeyCodeWithIdSet == null) || extractedGroupKeyCodeWithIdSet.isEmpty());
  }
  @Test
  public void shouldNotReturnRepositoryForInvalidUrl() {
    try {
      url = "file:?Test Repository Source";
      repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
      fail("Expected repository exception");
    } catch (RepositoryException e) {
      // expected
    }

    try {
      url = "file:src/test/resources/nonExistentFile";
      repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
      fail("Expected repository exception");
    } catch (RepositoryException e) {
      // expected
    }

    try {
      url = "file:src/test/resources/nonExistentFile";
      repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
      fail("Expected repository exception");
    } catch (RepositoryException e) {
      // expected
    }
  }
Example #3
0
  public void testFoo() throws Exception {
    RAMFileSystem fs = new RAMFileSystem();
    FileSystemScanner<RAMPath> scanner = new FileSystemScanner<RAMPath>(fs);

    //
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    //
    RAMPath foo = fs.addDir(fs.getRoot(), "foo");
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    RAMFile bar = fs.addFile(foo, "bar.txt");
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.ADD), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    bar.update("abc");
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.UPDATE), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());

    bar.remove();
    waitForOneMillis();
    assertEquals(Collections.singletonMap("foo/bar.txt", Change.REMOVE), scanner.scan());
    assertEquals(Collections.<String, Change>emptyMap(), scanner.scan());
  }
Example #4
0
 public List<SponsorDTO> getMatchingSponsors(SponsorCriteriaDto searchCriteria) {
   List<SponsorDTO> results = new ArrayList<SponsorDTO>();
   Collection<Sponsor> sponsors;
   if (ObjectUtils.isNull(searchCriteria)
       || (StringUtils.isEmpty(searchCriteria.getSponsorCode())
           && StringUtils.isEmpty(searchCriteria.getCustomerNumber()))) {
     sponsors = getBusinessObjectService().findAll(Sponsor.class);
   } else if (StringUtils.isNotEmpty(searchCriteria.getSponsorCode())) {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("sponsorCode", searchCriteria.getSponsorCode()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   } else {
     sponsors =
         legacyDataAdapter.findCollectionBySearchHelper(
             Sponsor.class,
             Collections.singletonMap("customerNumber", searchCriteria.getCustomerNumber()),
             Collections.<String>emptyList(),
             true,
             false,
             0);
   }
   if (sponsors != null && !sponsors.isEmpty()) {
     for (Sponsor sponsor : sponsors) {
       results.add(sponsorDtoService.buildDto(sponsor));
     }
   }
   return results;
 }
  protected Object executeScript(
      ScriptFactory scriptFactory,
      HttpServletRequest request,
      HttpServletResponse response,
      String scriptUrl) {
    Map<String, Object> scriptVariables = createScriptVariables(request, response);

    try {
      return scriptFactory.getScript(scriptUrl).execute(scriptVariables);
    } catch (ScriptNotFoundException e) {
      logger.error("Script not found at " + scriptUrl, e);

      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return Collections.singletonMap(errorMessageModelAttributeName, "REST script not found");
    } catch (Exception e) {
      logger.error("Error executing REST script at " + scriptUrl, e);

      HttpStatusCodeAwareException cause =
          ExceptionUtils.getThrowableOfType(e, HttpStatusCodeAwareException.class);
      String errorMsg;

      if (cause != null) {
        response.setStatus(cause.getStatusCode());

        errorMsg = ((Exception) cause).getMessage();
      } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        errorMsg = e.getMessage();
      }

      return Collections.singletonMap(errorMessageModelAttributeName, errorMsg);
    }
  }
 @Before
 public void setUp() {
   interceptor = new ClaimsAuthorizingInterceptor();
   interceptor.setNameAliases(Collections.singletonMap("authentication", "http://authentication"));
   interceptor.setFormatAliases(Collections.singletonMap("claims", "http://claims"));
   interceptor.setSecuredObject(new TestService());
 }
  @Test
  public void quick() throws Exception {
    Mailbox mbox =
        MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);

    Contact contact =
        mbox.createContact(
            null,
            new ParsedContact(
                Collections.singletonMap(ContactConstants.A_email, "test1@zimbra.com")),
            Mailbox.ID_FOLDER_CONTACTS,
            null);
    MailboxTestUtil.index(mbox);

    mbox.createContact(
        null,
        new ParsedContact(Collections.singletonMap(ContactConstants.A_email, "test2@zimbra.com")),
        Mailbox.ID_FOLDER_CONTACTS,
        null);

    SearchParams params = new SearchParams();
    params.setQueryString("test");
    params.setSortBy(SortBy.NONE);
    params.setTypes(EnumSet.of(MailItem.Type.CONTACT));
    params.setQuick(true);

    ZimbraQuery query =
        new ZimbraQuery(new OperationContext(mbox), SoapProtocol.Soap12, mbox, params);
    ZimbraQueryResults result = query.execute();
    Assert.assertTrue(result.hasNext());
    Assert.assertEquals(contact.getId(), result.getNext().getItemId());
    Assert.assertFalse(result.hasNext());
    Closeables.closeQuietly(result);
  }
Example #8
0
 @Path("/ping2")
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Map<String, Map<String, Date>> ping2() {
   return Collections.singletonMap(
       "pong", Collections.<String, Date>singletonMap("date", new Date()));
 }
 @Override
 public Response toResponse(ConstraintViolationException e) {
   return Response.status(Response.Status.BAD_REQUEST)
       .entity(
           Collections.singletonMap("errors", Collections.singletonMap("message", getMessage(e))))
       .build();
 }
Example #10
0
  public void testSqlEscaping() throws Exception {
    VirtualTable vt = new VirtualTable("test", "%param1%");
    vt.setEscapeSql(true);
    vt.addParameter(
        new VirtualTableParameter("param1", "default_value", new RegexpValidator(".*")));
    String singleQuote =
        vt.expandParameters(
            new Hints(
                Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "o'shea")));
    assertEquals("single quotes should be doubled", "o''shea", singleQuote);

    String doubleQuote =
        vt.expandParameters(
            new Hints(
                Hints.VIRTUAL_TABLE_PARAMETERS,
                Collections.singletonMap(
                    "param1",
                    "If you hear a voice within you say \"you cannot paint,\" then by all means paint, and that voice will be silenced.")));
    assertEquals(
        "double quotes should be doubled",
        "If you hear a voice within you say \"\"you cannot paint,\"\" then by all means paint, and that voice will be silenced.",
        doubleQuote);

    String backslash =
        vt.expandParameters(
            new Hints(
                Hints.VIRTUAL_TABLE_PARAMETERS, Collections.singletonMap("param1", "abc\\n")));
    assertEquals("backslashes should be removed", "abcn", backslash);
  }
  @Test
  public void testHasChanges_DifferentTypes() throws Exception {
    TestResDesc resourceDesc = new TestResDesc();
    resourceDesc.imported.add(FOO);
    resourceDesc.exported.add(
        EObjectDescription.create(
            BAR, EcorePackage.Literals.EANNOTATION, Collections.singletonMap("foo", "bar")));

    TestResDesc resourceDesc2 = new TestResDesc();
    resourceDesc2.imported.add(FOO);
    resourceDesc2.exported.add(
        new EObjectDescription(
            BAR,
            EcorePackage.Literals.EANNOTATION__CONTENTS,
            Collections.singletonMap("foo", "bar")) {
          @Override
          public URI getEObjectURI() {
            return EcoreUtil.getURI(EcorePackage.Literals.EANNOTATION);
          }
        });

    assertTrue(
        new DefaultResourceDescriptionDelta(resourceDesc, resourceDesc2)
            .haveEObjectDescriptionsChanged());
  }
 protected Void doInBackground(Map... mapArr) {
   Map map = mapArr[0];
   Map hashMap = new HashMap();
   Iterator it = map.entrySet().iterator();
   while (it.hasNext()) {
     Entry entry = (Entry) it.next();
     hashMap.put(entry.getKey(), entry.getValue());
   }
   try {
     this.httpService.doGetRequest(HttpService.buildURIWithQueryParameters(baseURL, hashMap));
   } catch (MalformedURLException e) {
     Analytics.this.eventEmitter.emit(
         ErrorUtil.ERROR, Collections.singletonMap(ErrorUtil.ERROR, e));
   } catch (UnsupportedEncodingException e2) {
     Analytics.this.eventEmitter.emit(
         ErrorUtil.ERROR, Collections.singletonMap(ErrorUtil.ERROR, e2));
   } catch (URISyntaxException e3) {
     Analytics.this.eventEmitter.emit(
         ErrorUtil.ERROR, Collections.singletonMap(ErrorUtil.ERROR, e3));
   } catch (IOException e4) {
     Analytics.this.eventEmitter.emit(
         ErrorUtil.ERROR, Collections.singletonMap(ErrorUtil.ERROR, e4));
   }
   return null;
 }
  public void testActivateInErrorStateAfterOpen() throws Exception {
    Map<String, Object> attributes =
        Collections.<String, Object>singletonMap(AbstractVirtualHost.NAME, getTestName());
    final MessageStore store = mock(MessageStore.class);
    doThrow(new RuntimeException("Cannot open store"))
        .when(store)
        .openMessageStore(any(ConfiguredObject.class));
    AbstractVirtualHost host =
        new AbstractVirtualHost(attributes, _node) {
          @Override
          protected MessageStore createMessageStore() {
            return store;
          }
        };

    host.open();
    assertEquals("Unexpected state", State.ERRORED, host.getState());

    doNothing().when(store).openMessageStore(any(ConfiguredObject.class));
    when(store.newMessageStoreReader()).thenReturn(mock(MessageStore.MessageStoreReader.class));

    host.setAttributes(
        Collections.<String, Object>singletonMap(VirtualHost.DESIRED_STATE, State.ACTIVE));
    assertEquals("Unexpected state", State.ACTIVE, host.getState());
    host.close();
  }
  public void removeAccessTokenUsingRefreshToken(String refreshToken) {
    String tokenId = null;

    try {
      tokenId =
          dynamoDBTemplate.queryUnique(
              schema.getAccessTableName(),
              schema.getAccessIndexRefreshToken(), //
              Collections.singletonMap(
                  schema.getAccessColumnRefreshToken(),
                  new Condition()
                      .withAttributeValueList(new AttributeValue(extractTokenKey(refreshToken)))
                      .withComparisonOperator(ComparisonOperator.EQ)), //
              new ObjectExtractor<String>() {

                public String extract(Map<String, AttributeValue> values) {
                  return values.get(schema.getAccessColumnTokenId()).getS();
                }
              },
              schema.getAccessColumnTokenId());
    } catch (EmptyResultDataAccessException | IncorrectResultSizeDataAccessException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Failed to find access token for refresh token " + refreshToken);
      }
    }

    if (tokenId == null) {
      return;
    }

    dynamoDBTemplate.delete(
        schema.getAccessTableName(),
        Collections.singletonMap(schema.getAccessColumnTokenId(), new AttributeValue(tokenId)));
  }
  @Test
  public void testContainerBootstrapSharedCacheMode() {
    // first, via the integration vars
    PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter();
    {
      // as object
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  empty,
                  Collections.singletonMap(
                      AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE));
      assertEquals(
          SharedCacheMode.DISABLE_SELECTIVE,
          builder.getConfigurationValues().get(AvailableSettings.SHARED_CACHE_MODE));
    }
    {
      // as string
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  empty,
                  Collections.singletonMap(
                      AvailableSettings.SHARED_CACHE_MODE,
                      SharedCacheMode.DISABLE_SELECTIVE.name()));
      assertEquals(
          SharedCacheMode.DISABLE_SELECTIVE.name(),
          builder.getConfigurationValues().get(AvailableSettings.SHARED_CACHE_MODE));
    }

    // next, via the PUI
    PersistenceUnitInfoAdapter adapter =
        new PersistenceUnitInfoAdapter() {
          @Override
          public SharedCacheMode getSharedCacheMode() {
            return SharedCacheMode.ENABLE_SELECTIVE;
          }
        };
    {
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(adapter, null);
      assertEquals(
          SharedCacheMode.ENABLE_SELECTIVE,
          builder.getConfigurationValues().get(AvailableSettings.SHARED_CACHE_MODE));
    }

    // via both, integration vars should take precedence
    {
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  adapter,
                  Collections.singletonMap(
                      AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE));
      assertEquals(
          SharedCacheMode.DISABLE_SELECTIVE,
          builder.getConfigurationValues().get(AvailableSettings.SHARED_CACHE_MODE));
    }
  }
Example #16
0
  /*
   * 1 receiveProcess, 1 sendProcess, Message contains datas goes from EndEvent to ReceiveTask
   * dynamic -> deployAndEnable(sendProcess), deployAndEnable(receiveProcess), startProcess(receiveProcess), startProcess(sendProcess)
   * checks : receiveProcess wait on receive task, sendProcess is finished, receiveProcess goes through receive task (found message sent by
   * sendProcess) and reaches user task, data is transmitted to
   * the receiveProcess.
   */
  @Cover(
      classes = {EventInstance.class, ReceiveTaskInstance.class},
      concept = BPMNConcept.EVENTS,
      keywords = {"Event", "Message event", "Receive task", "Send", "Receive"},
      jira = "")
  @Test
  public void receiveMessageWithData() throws Exception {
    final ProcessDefinition sendMessageProcess =
        deployAndEnableProcessWithEndMessageEvent(
            "sendMessageProcess",
            "m5",
            "receiveMessageProcess",
            "waitForMessage",
            null,
            Collections.singletonMap("lastName", String.class.getName()),
            Collections.singletonMap("lName", String.class.getName()),
            Collections.singletonMap("lName", "lastName"));
    final List<Operation> receiveMessageOperations =
        Collections.singletonList(
            buildAssignOperation(
                "name", "lName", String.class.getName(), ExpressionType.TYPE_VARIABLE));
    final ProcessDefinition receiveMessageProcess =
        deployAndEnableProcessWithReceivedTask(
            "receiveMessageProcess",
            "waitForMessage",
            "userTask1",
            "delivery",
            user,
            "m5",
            null,
            Collections.singletonMap("name", String.class.getName()),
            receiveMessageOperations);

    final ProcessInstance receiveMessageProcessInstance =
        getProcessAPI().startProcess(receiveMessageProcess.getId());
    waitForFlowNodeInState(
        receiveMessageProcessInstance, "waitForMessage", TestStates.WAITING, true);

    final ProcessInstance sendMessageProcessInstance =
        getProcessAPI()
            .startProcess(
                sendMessageProcess.getId(),
                Arrays.asList(
                    buildAssignOperation(
                        "lastName", "Doe", String.class.getName(), ExpressionType.TYPE_CONSTANT)),
                null);
    waitForProcessToFinish(sendMessageProcessInstance);
    forceMatchingOfEvents();
    final HumanTaskInstance step1 =
        waitForUserTaskAndGetIt(receiveMessageProcessInstance, "userTask1");

    final DataInstance dataInstance =
        getProcessAPI().getProcessDataInstance("name", step1.getRootContainerId());
    assertEquals("Doe", dataInstance.getValue());

    disableAndDeleteProcess(sendMessageProcess);
    disableAndDeleteProcess(receiveMessageProcess);
  }
 @Test
 public void test() {
   ParametricVaRDataBundle data = new ParametricVaRDataBundle(null, ZERO, VECTOR, MATRIX, 1);
   Map<Integer, ParametricVaRDataBundle> bundle = Collections.singletonMap(1, data);
   assertEquals(F.evaluate(bundle), 0, 1e-9);
   data = new ParametricVaRDataBundle(null, VECTOR, VECTOR, MATRIX, 1);
   bundle = Collections.singletonMap(1, data);
   assertEquals(F.evaluate(bundle), 9, 1e-9);
 }
  @Test
  public void testContainerBootstrapValidationMode() {
    // first, via the integration vars
    PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter();
    {
      // as object
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  empty,
                  Collections.singletonMap(
                      AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK));
      assertEquals(
          ValidationMode.CALLBACK,
          builder.getConfigurationValues().get(AvailableSettings.VALIDATION_MODE));
    }
    {
      // as string
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  empty,
                  Collections.singletonMap(
                      AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name()));
      assertEquals(
          ValidationMode.CALLBACK.name(),
          builder.getConfigurationValues().get(AvailableSettings.VALIDATION_MODE));
    }

    // next, via the PUI
    PersistenceUnitInfoAdapter adapter =
        new PersistenceUnitInfoAdapter() {
          @Override
          public ValidationMode getValidationMode() {
            return ValidationMode.CALLBACK;
          }
        };
    {
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(adapter, null);
      assertEquals(
          ValidationMode.CALLBACK,
          builder.getConfigurationValues().get(AvailableSettings.VALIDATION_MODE));
    }

    // via both, integration vars should take precedence
    {
      EntityManagerFactoryBuilderImpl builder =
          (EntityManagerFactoryBuilderImpl)
              Bootstrap.getEntityManagerFactoryBuilder(
                  adapter,
                  Collections.singletonMap(AvailableSettings.VALIDATION_MODE, ValidationMode.NONE));
      assertEquals(
          ValidationMode.NONE,
          builder.getConfigurationValues().get(AvailableSettings.VALIDATION_MODE));
    }
  }
  @BeforeClass
  public static void beforeClass() throws Exception {

    VaultRule vaultRule = new VaultRule();
    vaultRule.before();

    assumeTrue(vaultRule.prepare().getVersion().isGreaterThanOrEqualTo(Version.parse("0.6.1")));

    VaultProperties vaultProperties = Settings.createVaultProperties();

    if (!vaultRule.prepare().hasAuth(vaultProperties.getAppRole().getAppRolePath())) {
      vaultRule.prepare().mountAuth(vaultProperties.getAppRole().getAppRolePath());
    }

    VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();

    String rules =
        "{ \"name\": \"testpolicy\",\n" //
            + "  \"path\": {\n" //
            + "    \"*\": {  \"policy\": \"read\" }\n" //
            + "  }\n" //
            + "}";

    vaultOperations.write("sys/policy/testpolicy", Collections.singletonMap("rules", rules));

    String appId = VaultConfigAppRoleTests.class.getSimpleName();

    vaultOperations.write(
        "secret/" + VaultConfigAppRoleTests.class.getSimpleName(),
        Collections.singletonMap("vault.value", "foo"));

    Map<String, String> withSecretId = new HashMap<String, String>();
    withSecretId.put("policies", "testpolicy"); // policy
    withSecretId.put("bound_cidr_list", "0.0.0.0/0");
    withSecretId.put("bind_secret_id", "true");

    vaultOperations.write("auth/approle/role/with-secret-id", withSecretId);

    String roleId =
        (String)
            vaultOperations
                .read("auth/approle/role/with-secret-id/role-id")
                .getData()
                .get("role_id");
    String secretId =
        (String)
            vaultOperations
                .write(
                    String.format("auth/approle/role/with-secret-id/secret-id", "with-secret-id"),
                    null)
                .getData()
                .get("secret_id");

    System.setProperty("spring.cloud.vault.app-role.role-id", roleId);
    System.setProperty("spring.cloud.vault.app-role.secret-id", secretId);
  }
 @Test
 public void genericEnclosingClass() {
   HasGen<Map<String, String>> hasGen = new HasGen<>();
   hasGen.which = 1;
   Assert.assertEquals(
       Collections.singletonMap("a", "b"),
       new PickSomeBuilder<Map<String, String>>(hasGen)
           .setSecond(Collections.singletonMap("a", "b"))
           .build());
 }
  public void testSupplementaryCharactersInPaths() {
    Map<String, Object> map = new HashMap<>();
    map.put("搜索", 2);
    map.put("指数", 3);

    assertEquals(
        Collections.singletonMap("搜索", 2),
        XContentMapValues.filter(map, new String[] {"搜索"}, new String[0]));
    assertEquals(
        Collections.singletonMap("指数", 3),
        XContentMapValues.filter(map, new String[0], new String[] {"搜索"}));
  }
  public void testSharedPrefixes() {
    Map<String, Object> map = new HashMap<>();
    map.put("foobar", 2);
    map.put("foobaz", 3);

    assertEquals(
        Collections.singletonMap("foobar", 2),
        XContentMapValues.filter(map, new String[] {"foobar"}, new String[0]));
    assertEquals(
        Collections.singletonMap("foobaz", 3),
        XContentMapValues.filter(map, new String[0], new String[] {"foobar"}));
  }
Example #23
0
  private void setSubmissionCheckListinfo(
      org.kuali.kra.irb.actions.submit.ProtocolSubmissionLite protocolSubmission,
      SubmissionDetails protocolSubmissionDetail) {
    SubmissionChecklistInfo submissionChecklistInfo =
        protocolSubmissionDetail.addNewSubmissionChecklistInfo();
    String formattedCode = new String();
    Collection<ProtocolExemptStudiesCheckListItem> protocolExemptCheckList =
        getBusinessObjectService()
            .findMatching(
                ProtocolExemptStudiesCheckListItem.class,
                Collections.singletonMap("submissionIdFk", protocolSubmission.getSubmissionId()));
    for (ProtocolExemptStudiesCheckListItem protocolExemptStudiesCheckListBean :
        protocolExemptCheckList) {
      Checklists checkListItem = submissionChecklistInfo.addNewChecklists();
      checkListItem.setChecklistCode(
          protocolExemptStudiesCheckListBean.getExemptStudiesCheckListCode());
      checkListItem.setChecklistDescription(
          protocolExemptStudiesCheckListBean.getExemptStudiesCheckListItem().getDescription());
      formattedCode =
          formattedCode
              + "("
              + protocolExemptStudiesCheckListBean.getExemptStudiesCheckListCode()
              + ") ";
    }
    if (formattedCode.length() > 0) {
      submissionChecklistInfo.setChecklistCodesFormatted(
          formattedCode); // this will have format (3) (7) like that...
    }
    Collection<ProtocolExpeditedReviewCheckListItem> vecExpeditedCheckList =
        getBusinessObjectService()
            .findMatching(
                ProtocolExpeditedReviewCheckListItem.class,
                Collections.singletonMap("submissionIdFk", protocolSubmission.getSubmissionId()));
    for (ProtocolExpeditedReviewCheckListItem protocolReviewTypeCheckListBean :
        vecExpeditedCheckList) {
      Checklists checkListItem = submissionChecklistInfo.addNewChecklists();
      checkListItem.setChecklistCode(
          protocolReviewTypeCheckListBean.getExpeditedReviewCheckListCode());
      checkListItem.setChecklistDescription(
          protocolReviewTypeCheckListBean.getExpeditedReviewCheckListItem().getDescription());
      formattedCode =
          formattedCode
              + "("
              + protocolReviewTypeCheckListBean.getExpeditedReviewCheckListCode()
              + ") ";
    }

    if (formattedCode.length() > 0) {
      submissionChecklistInfo.setChecklistCodesFormatted(
          formattedCode); // this will have format (3) (7) like that...
    }
  }
  @Test
  public void shouldGoThrough() {
    UserRegData anotherUserData = RandomUtils.randomUser();
    UserDTO anotherUser = AuthEndPointsHandler.registerNewUser(anotherUserData);

    UserRegData userData = RandomUtils.randomUser();

    // register new user
    UserDTO registeredUser = AuthEndPointsHandler.registerNewUser(userData);

    // registration of new user is not a authentication - non public resources are not available
    Response userDataResponse2 =
        RequestHelper.doGet(
            UserRoutes.USER_GET,
            Collections.singletonMap(RestTestConstants.USER_ID, registeredUser.getUserId()),
            HttpStatus.SC_UNAUTHORIZED);
    AuthResponse userDataResponse2AuthResponse = userDataResponse2.as(AuthResponse.class);
    assertThat(
        userDataResponse2AuthResponse.getDetails().get(AuthResponse.AUTH_RESULT), is(UNAUTHORIZED));

    // login as earlie registered user
    AuthResponse authResponse2 =
        AuthEndPointsHandler.login(userData.getLogin(), userData.getPassword());

    // non public resources should be available now
    UserEditDTO ownData = UserEndPointsHandler.getUserEditData(registeredUser.getUserId());
    Response anotherUserDataResponse =
        RequestHelper.doGet(
            UserRoutes.USER_GET,
            Collections.singletonMap(RestTestConstants.USER_ID, anotherUser.getUserId()),
            HttpStatus.SC_UNPROCESSABLE_ENTITY);
    Response nonExistingUserDataResponse =
        RequestHelper.doGet(
            UserRoutes.USER_GET,
            Collections.singletonMap(RestTestConstants.USER_ID, 1024),
            HttpStatus.SC_UNPROCESSABLE_ENTITY);

    // log out
    AuthResponse logoutAuthResponse = AuthEndPointsHandler.logout();
    assertThat(logoutAuthResponse.getResponseCode(), is(HttpStatus.SC_OK));

    // non public resources are not available again
    Response userDataResponse4 =
        RequestHelper.doGet(
            UserRoutes.USER_GET,
            Collections.singletonMap(RestTestConstants.USER_ID, registeredUser.getUserId()),
            HttpStatus.SC_UNAUTHORIZED);
    AuthResponse taskList4AuthResponse = userDataResponse4.as(AuthResponse.class);
    assertThat(taskList4AuthResponse.getDetails().get(AuthResponse.AUTH_RESULT), is(UNAUTHORIZED));
  }
  @Test
  public void testKeyCodeSetOwnerAssignment() {
    PayTypeBo pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "1"));
    for (PayTypeKeyBo keyBo : pstnRptGrpBo.getEffectiveKeySet()) {
      Assert.assertEquals(keyBo.getOwnerId(), "1");
    }

    pstnRptGrpBo =
        boService.findByPrimaryKey(PayTypeBo.class, Collections.singletonMap("hrPayTypeId", "5"));
    for (PayTypeKeyBo keyBo : pstnRptGrpBo.getEffectiveKeySet()) {
      Assert.assertEquals(keyBo.getOwnerId(), "5");
    }
  }
  public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    OAuth2AccessToken accessToken = null;

    String key = authenticationKeyGenerator.extractKey(authentication);
    try {
      String accessTokenId =
          dynamoDBTemplate.queryUnique(
              schema.getAccessTableName(),
              schema.getAccessIndexAuthenticationId(), //
              Collections.singletonMap(
                  schema.getAccessColumnAuthenticationId(),
                  new Condition()
                      .withComparisonOperator(ComparisonOperator.EQ)
                      .withAttributeValueList(new AttributeValue(key))), //
              new ObjectExtractor<String>() {

                public String extract(Map<String, AttributeValue> values) {
                  return values.get(schema.getAccessColumnTokenId()).getS();
                }
              });
      accessToken =
          dynamoDBTemplate.get(
              schema.getAccessTableName(),
              Collections.singletonMap(
                  schema.getAccessColumnTokenId(), new AttributeValue(accessTokenId)),
              new ObjectExtractor<OAuth2AccessToken>() {

                public OAuth2AccessToken extract(Map<String, AttributeValue> values) {
                  return deserializeAccessToken(values.get(schema.getAccessColumnToken()).getB());
                }
              });
    } catch (EmptyResultDataAccessException | IncorrectResultSizeDataAccessException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Failed to find access token for authentication " + authentication);
      }
    } catch (IllegalArgumentException e) {
      LOG.error("Could not extract access token for authentication " + authentication, e);
    }

    if (accessToken != null
        && !key.equals(
            authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
      // Keep the store consistent (maybe the same user is represented by this authentication but
      // the details have
      // changed)
      storeAccessToken(accessToken, authentication);
    }
    return accessToken;
  }
Example #27
0
 /** Test of {@link TextTagParser#readTagsFromText} method with tabs. */
 @Test
 public void testTab() {
   Assert.assertEquals(
       TextTagParser.readTagsFromText("shop\tjewelry"),
       Collections.singletonMap("shop", "jewelry"));
   Assert.assertEquals(
       TextTagParser.readTagsFromText("!shop\tjewelry"),
       Collections.singletonMap("shop", "jewelry"));
   Assert.assertEquals(
       TextTagParser.readTagsFromText("!!!shop\tjewelry"),
       Collections.singletonMap("shop", "jewelry"));
   Assert.assertEquals(
       TextTagParser.readTagsFromText("shop\t\t\tjewelry"),
       Collections.singletonMap("shop", "jewelry"));
 }
  @Test
  public void testWithMetaData() {
    Map<String, Object> metaDataMap = Collections.singletonMap("key", (Object) "value");
    MetaData metaData = MetaData.from(metaDataMap);
    when(serializer.deserialize(serializedMetaData)).thenReturn(metaData);
    SerializedEventMessage<Object> message =
        new SerializedEventMessage<Object>(
            eventId, timestamp, serializedPayload, serializedMetaData, serializer);
    EventMessage<Object> message1 = message.withMetaData(MetaData.emptyInstance());
    EventMessage<Object> message2 =
        message.withMetaData(MetaData.from(Collections.singletonMap("key", (Object) "otherValue")));

    assertEquals(0, message1.getMetaData().size());
    assertEquals(1, message2.getMetaData().size());
  }
 @NotNull
 @Override
 public Map<String, Void> map(@NotNull FileContent inputData) {
   final VirtualFile file = inputData.getFile();
   final String name = file.getName();
   if (PyNames.INIT_DOT_PY.equals(name)) {
     final VirtualFile parent = file.getParent();
     if (parent != null && parent.isDirectory()) {
       return Collections.singletonMap(parent.getName(), null);
     }
   } else {
     return Collections.singletonMap(FileUtil.getNameWithoutExtension(name), null);
   }
   return Collections.emptyMap();
 }
Example #30
0
  private void init() {
    count = 0;
    names = new ArrayList<String>();
    numbers = new ArrayList<Integer>();
    repeatValues = new ArrayList<String>();
    dataModel = new ListDataModel(names);

    Map<String, String> item1 = Collections.singletonMap("page", "includedDynamically01.xhtml");

    Map<String, String> item2 = Collections.singletonMap("page", "includedDynamically02.xhtml");

    Object[] myPages = {item1, item2};

    pages = myPages;
  }