Java Code Examples for com.haulmont.cuba.security.entity.User

The following examples show how to use com.haulmont.cuba.security.entity.User. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cuba   Source File: OptionsGroupTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDatasource() {
    OptionsGroup component = uiComponents.create(OptionsGroup.class);

    //noinspection unchecked
    Datasource<User> testDs = new DsBuilder()
            .setId("testDs")
            .setJavaClass(User.class)
            .setView(viewRepository.getView(User.class, View.LOCAL))
            .buildDatasource();

    testDs.setItem(new User());
    ((DatasourceImpl) testDs).valid();

    assertNull(component.getValue());

    component.setDatasource(testDs, "group");
    assertNotNull(component.getDatasource());
}
 
Example 2
Source Project: cuba   Source File: TestCascadingEntityListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onBeforeUpdate(User entity, EntityManager entityManager) {
    events.add("onBeforeUpdate: " + entity.getId());

    Transaction.Runnable code = (em) -> {
        TypedQuery<User> query = entityManager.createQuery("select u from sec$User u where u.login = 'admin'", User.class);
        if (withView) {
            query.setViewName(View.MINIMAL);
        }
        User admin = query.getSingleResult();
        System.out.println(admin.getLogin());
    };

    if (withNewTx) {
        AppBeans.get(Persistence.class).runInTransaction(code);
    } else {
        code.run(entityManager);
    }
}
 
Example 3
Source Project: cuba   Source File: QueryConditionsUsageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    LogicalCondition condition = and()
            .add(where("u.login like :login"))
            .add(where("u.userRoles ur", "ur.role.name = :roleName"))
            .add(or()
                    .add(where("u.foo = :foo"))
                    .add(where("u.bar = :bar"))
            );

    LoadContext.Query query = LoadContext.createQuery("select u from sec$User u")
            .setCondition(condition)
            .setParameter("login", "admin");
    LoadContext<User> loadContext = LoadContext.create(User.class).setQuery(query);
    List<User> users = dataManager.loadList(loadContext);
    assertEquals(1, users.size());

    Optional<User> userOpt = dataManager.load(User.class)
            .query("select u from sec$User u")
            .condition(condition)
            .parameter("login", "admin")
            .optional();
    assertTrue(userOpt.isPresent());
}
 
Example 4
Source Project: cuba   Source File: BeforeCommitTransactionListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeEntity() throws Exception {
    User u1 = metadata.create(User.class);
    u1.setLogin("TxLstnrTst-1-" + u1.getId());
    u1.setGroup(companyGroup);

    TestBeforeCommitTxListener.test = "testChangeEntity";
    try (Transaction tx = persistence.createTransaction()) {
        persistence.getEntityManager().persist(u1);
        tx.commit();
    } finally {
        TestBeforeCommitTxListener.test = null;
    }

    try (Transaction tx = persistence.createTransaction()) {
        User user = persistence.getEntityManager().find(User.class, u1.getId());
        assertEquals("set by tx listener", user.getName());
    }
}
 
Example 5
Source Project: cuba   Source File: DynamicAttributesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCollectionOfEnumAttribute() {
    LoadContext<User> loadContext = LoadContext.create(User.class).setId(user.getId()).setLoadDynamicAttributes(true);
    User loadedUser = dataManager.load(loadContext);
    List<String> enumValues = loadedUser.getValue("+userEnumCollectionAttribute");
    assertEquals(2, enumValues.size());
    assertTrue(enumValues.contains("option1"));
    assertFalse(enumValues.contains("option2"));

    loadedUser.setValue("+userEnumCollectionAttribute", Lists.newArrayList("option2"));
    dataManager.commit(loadedUser);

    loadedUser = dataManager.load(loadContext);
    enumValues = loadedUser.getValue("+userEnumCollectionAttribute");
    assertEquals(1, enumValues.size());
    assertEquals("option2", enumValues.get(0));
}
 
Example 6
Source Project: cuba   Source File: DatePickerDsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeDsListener() {
    DatePicker datePicker = uiComponents.create(DatePicker.NAME);

    Datasource<User> userDs = getTestUserDatasource();
    User user = userDs.getItem();
    Date updateTs = new Date();
    user.setUpdateTs(updateTs);
    datePicker.setDatasource(userDs, "updateTs");

    // unbind
    datePicker.setDatasource(null, null);

    Datasource.ItemPropertyChangeListener<User> propertyChangeListener = e -> {
        throw new RuntimeException("Value was changed externally");
    };
    userDs.addItemPropertyChangeListener(propertyChangeListener);

    datePicker.setValue(new Date());
    assertEquals(updateTs, user.getUpdateTs());
}
 
Example 7
Source Project: cuba   Source File: ViewRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultViews() {
    View localView = repository.getView(User.class, View.LOCAL);
    assertNotNull(localView);
    assertNotNull(localView.getProperty("name"));
    assertNotNull(localView.getProperty("login"));
    assertNotNull(localView.getProperty("email"));
    assertNull(localView.getProperty("userRoles"));

    View minView = repository.getView(User.class, View.MINIMAL);
    assertNotNull(minView);
    assertNotNull(minView.getProperty("name"));
    assertNotNull(minView.getProperty("login"));
    assertNull(minView.getProperty("email"));
    assertNull(minView.getProperty("userRoles"));

    View baseView = repository.getView(User.class, View.BASE);
    assertNotNull(baseView.getProperty("name"));
    assertNotNull(baseView.getProperty("login"));
    assertNotNull(localView.getProperty("email"));

    Collection<String> definedViews = repository.getViewNames(User.class);
    assertFalse(definedViews.contains(View.LOCAL));
    assertFalse(definedViews.contains(View.MINIMAL));
    assertFalse(definedViews.contains(View.BASE));
}
 
Example 8
Source Project: cuba   Source File: AuthenticationManagerBean.java    License: Apache License 2.0 6 votes vote down vote up
protected User loadSubstitutedUser(User substitutedUser, UserSession currentSession, EntityManager em) {
    TypedQuery<User> query = em.createQuery(
            "select su from sec$User su where " +
                    "su in (select s.substitutedUser from sec$User u join u.substitutions s " +
                    "where u.id = ?1 and s.substitutedUser.id = ?2)",
            User.class
    );
    query.setParameter(1, currentSession.getUser().getId());
    query.setParameter(2, substitutedUser.getId());
    List<User> list = query.getResultList();
    if (list.isEmpty()) {
        throw new NoResultException("User not found");
    }

    return list.get(0);
}
 
Example 9
Source Project: cuba   Source File: AuthenticationServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public UserSession substituteUser(User substitutedUser) {
    try {
        UserSession currentSession = userSessionSource.getUserSession();
        SessionLogEntry logEntry = userSessionLog.updateSessionLogRecord(currentSession, SessionAction.SUBSTITUTION);

        UserSession substitutionSession =
                authenticationManager.substituteUser(substitutedUser);

        Map<String, Object> logParams = emptyMap();
        if (logEntry != null && logEntry.getClientType() != null) {
            logParams = ParamsMap.of(ClientType.class.getName(), logEntry.getClientType().name());
        }

        userSessionLog.createSessionLogRecord(substitutionSession, SessionAction.LOGIN, currentSession, logParams);

        return substitutionSession;
    } catch (Throwable e) {
        log.error("Substitution error", e);
        throw new RuntimeException("Substitution error: " + e.toString());
    }
}
 
Example 10
Source Project: cuba   Source File: NonDetachedTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSaveNotDetached_DM() throws Exception {
    Group companyGroupCopy = metadata.getTools().copy(companyGroup);
    assertTrue(PersistenceHelper.isNew(companyGroupCopy));
    PersistenceHelper.makeDetached(companyGroupCopy);

    User user = persistence.callInTransaction((em) -> em.find(User.class, this.user.getId()));
    User userCopy = metadata.getTools().copy(user);
    assertNull(userCopy.getGroup());

    assertTrue(PersistenceHelper.isNew(userCopy));
    PersistenceHelper.makeDetached(userCopy);

    userCopy.setGroup(companyGroupCopy);
    userCopy.setName("new name");
    AppBeans.get(DataManager.class).commit(userCopy);

    user = persistence.callInTransaction((em) -> em.find(User.class, this.user.getId()));
    assertEquals("new name", user.getName());
}
 
Example 11
Source Project: sample-timesheets   Source File: SimpleWeeklyTimesheets.java    License: Apache License 2.0 6 votes vote down vote up
@Install(to = "weeklyTsTable", subject = "styleProvider")
private String weeklyTsTableStyleProvider(WeeklyReportEntry entity, String property) {
    String id = null;
    if (property != null && property.endsWith(COLUMN_SUFFIX)) {
        id = property.replace(COLUMN_SUFFIX, "");
    }

    DayOfWeek day = DayOfWeek.fromId(id != null ? id : property);
    if (entity == null) {
        User currentOrSubstitutedUser = userSession.getCurrentOrSubstitutedUser();
        if (day != null) {
            return validationTools.isWorkTimeMatchToPlanForDay(
                    DateTimeUtils.getSpecificDayOfWeek(firstDayOfWeek, day.getJavaCalendarDay()),
                    currentOrSubstitutedUser) ? null : "overtime";
        } else if (TOTAL_COLUMN_ID.equals(property)) {
            return validationTools.isWorkTimeMatchToPlanForWeek(
                    firstDayOfWeek, currentOrSubstitutedUser) ? null : "overtime";
        }
    }
    return null;
}
 
Example 12
Source Project: cuba   Source File: LookupFieldDsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeSubscribeDsListener() {
    LookupField lookupField = uiComponents.create(LookupField.class);

    CollectionDatasource<Group, UUID> groupsDs = getTestCollectionDatasource();
    lookupField.setOptionsDatasource(groupsDs);

    Datasource<User> userDs = getTestUserDatasource();
    Group group = groupsDs.getItems().iterator().next();
    userDs.getItem().setGroup(group);
    lookupField.setDatasource(userDs, "group");

    // unbind
    lookupField.setDatasource(null, null);

    // setup
    boolean[] valueWasChanged = {false};
    Datasource.ItemPropertyChangeListener<User> listener = e -> valueWasChanged[0] = true;
    userDs.addItemPropertyChangeListener(listener);

    lookupField.setDatasource(userDs, "group");
    lookupField.setValue(null);
    assertTrue(valueWasChanged[0]);
}
 
Example 13
Source Project: cuba   Source File: ViewRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetView() {
    View view = repository.getView(User.class, "test");
    assertNotNull(view);
    assertNotNull(view.getProperty("name"));
    assertNotNull(view.getProperty("login"));
    assertNotNull(view.getProperty("userRoles"));

    View userRolesView = view.getProperty("userRoles").getView();
    assertNotNull(userRolesView);
    assertNotNull(userRolesView.getProperty("role"));

    View roleView = userRolesView.getProperty("role").getView();
    assertNotNull(roleView);
    assertNotNull(roleView.getProperty("name"));
}
 
Example 14
Source Project: cuba   Source File: LabelDsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeSubscribeDsListener() {
    Label label = uiComponents.create(Label.NAME);

    Datasource<User> userDs = getTestUserDatasource();
    User user = userDs.getItem();
    user.setName("testName");
    label.setDatasource(userDs, "name");

    label.setDatasource(null, null);
    label.setDatasource(userDs, "name");

    boolean[] valueWasChanged = {false};
    Datasource.ItemPropertyChangeListener<User> propertyChangeListener = e -> valueWasChanged[0] = true;
    userDs.addItemPropertyChangeListener(propertyChangeListener);

    label.setValue("anotherName");
    assertEquals(true, valueWasChanged[0]);
    assertEquals("anotherName", user.getName());
}
 
Example 15
Source Project: cuba   Source File: StaticServerSelectorTest.java    License: Apache License 2.0 6 votes vote down vote up
public StaticServerSelectorTest() {
    User user1 = new User();
    user1.setLogin("user1");
    session1 = new UserSession(UUID.randomUUID(), user1, Collections.emptyList(), Locale.ENGLISH, false);

    User user2 = new User();
    user2.setLogin("user2");
    session2 = new UserSession(UUID.randomUUID(), user2, Collections.emptyList(), Locale.ENGLISH, false);

    User user3 = new User();
    user3.setLogin("user3");
    session3 = new UserSession(UUID.randomUUID(), user3, Collections.emptyList(), Locale.ENGLISH, false);

    User user4 = new User();
    user4.setLogin("user4");
    session4 = new UserSession(UUID.randomUUID(), user4, Collections.emptyList(), Locale.ENGLISH, false);
}
 
Example 16
Source Project: sample-timesheets   Source File: ProjectsServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<TimeEntry> getApprovableTimeEntriesForPeriod(
        Date start, Date end, User approver, User user, @Nullable TimeEntryStatus status, @Nullable String viewName
) {
    LoadContext<TimeEntry> loadContext = new LoadContext<>(TimeEntry.class);
    if (viewName != null) {
        loadContext.setView(viewName);
    }
    String queryStr = "select e from ts$TimeEntry e join e.task t join t.project pr join pr.participants p " +
            "where p.user.id = :approverId and (p.role.code = '" + MANAGER.getId() + "' or p.role.code = '" + APPROVER.getId() + "') " +
            "and e.user.id = :userId and (e.date between :start and :end)";
    if (status != null) {
        queryStr += " and e.status = :status";
    }
    LoadContext.Query query = loadContext.setQueryString(queryStr)
            .setParameter("start", start)
            .setParameter("end", end)
            .setParameter("approverId", approver.getId())
            .setParameter("userId", user.getId());
    if (status != null) {
        query.setParameter("status", status);
    }
    return dataManager.loadList(loadContext);
}
 
Example 17
Source Project: cuba   Source File: CheckBoxDsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeComponentListener() {
    CheckBox checkBox = uiComponents.create(CheckBox.NAME);

    Datasource<User> userDs = getTestUserDatasource();
    User user = userDs.getItem();
    user.setActive(true);
    checkBox.setDatasource(userDs, "active");

    // unbind
    checkBox.setDatasource(null, null);

    Consumer valueChangeListener = e -> {
        throw new RuntimeException("Value was changed externally");
    };
    checkBox.addValueChangeListener(valueChangeListener);

    user.setActive(false);
    assertEquals(true, checkBox.getValue());
}
 
Example 18
Source Project: cuba   Source File: LookupPickerFieldDsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeSubscribeDsListener() {
    LookupPickerField component = uiComponents.create(LookupPickerField.NAME);

    CollectionDatasource<Group, UUID> groupsDs = getTestCollectionDatasource();
    component.setOptionsDatasource(groupsDs);
    List<Group> groups = new ArrayList<>(groupsDs.getItems());

    Datasource<User> userDs = getTestUserDatasource();
    userDs.getItem().setGroup(groups.get(0));

    component.setDatasource(userDs, "group");

    // unbind
    component.setDatasource(null, null);

    // setup
    boolean[] valueWasChanged = {false};
    Datasource.ItemPropertyChangeListener<User> listener = e -> valueWasChanged[0] = true;
    userDs.addItemPropertyChangeListener(listener);
    component.setDatasource(userDs, "group");

    component.setValue(null);
    assertEquals(true, valueWasChanged[0]);
}
 
Example 19
Source Project: cuba   Source File: ExceptionDialog.java    License: Apache License 2.0 6 votes vote down vote up
public void sendSupportEmail(String message, String stackTrace) {
    try {
        User user = userSessionSource.getUserSession().getUser();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timeSource.currentTimestamp());

        Map<String, Object> binding = new HashMap<>();
        binding.put("timestamp", date);
        binding.put("errorMessage", message);
        binding.put("stacktrace", stackTrace);
        binding.put("systemId", clientConfig.getSystemID());
        binding.put("userLogin", user.getLogin());

        if (MapUtils.isNotEmpty(additionalExceptionReportBinding)) {
            binding.putAll(additionalExceptionReportBinding);
        }

        reportService.sendExceptionReport(clientConfig.getSupportEmail(), Collections.unmodifiableMap(binding));

        Notification.show(messages.getMainMessage("exceptionDialog.emailSent"));
    } catch (Throwable e) {
        log.error("Error sending exception report", e);
        Notification.show(messages.getMainMessage("exceptionDialog.emailSendingErr"));
    }
}
 
Example 20
Source Project: cuba   Source File: SystemAuthenticationProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationDetails authenticate(Credentials credentials) throws LoginException {
    SystemUserCredentials systemLogin = (SystemUserCredentials) credentials;

    String login = systemLogin.getLogin();

    Locale credentialsLocale = systemLogin.getLocale() == null ?
            messages.getTools().getDefaultLocale() : systemLogin.getLocale();

    User user = loadUser(login);
    if (user == null) {
        throw new LoginException(getInvalidCredentialsMessage(login, credentialsLocale));
    }

    Locale userLocale = getUserLocale(systemLogin, user);

    UserSession session = userSessionManager.createSession(user, userLocale, true);

    return new SimpleAuthenticationDetails(session);
}
 
Example 21
Source Project: cuba   Source File: TextFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDatasource() {
    TextField component = uiComponents.create(TextField.class);

    //noinspection unchecked
    Datasource<User> testDs = new DsBuilder()
            .setId("testDs")
            .setJavaClass(User.class)
            .setView(viewRepository.getView(User.class, View.LOCAL))
            .buildDatasource();

    testDs.setItem(new User());
    ((DatasourceImpl) testDs).valid();

    assertNull(component.getValue());
    testDs.getItem().setLogin("Ok");

    component.setValue("none");
    component.setDatasource(testDs, "login");
    assertEquals("Ok", component.getValue());

    component.setValue("user");
    assertEquals("user", testDs.getItem().getLogin());

    testDs.getItem().setLogin("login");
    assertEquals("login", component.getValue());
}
 
Example 22
Source Project: cuba   Source File: LoginTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    PasswordEncryption passwordEncryption = AppBeans.get(PasswordEncryption.NAME);
    authenticationManager = AppBeans.get(AuthenticationManager.NAME);
    userSessionSource = AppBeans.get(UserSessionSource.NAME);
    standardTestUserSession = userSessionSource.getUserSession();

    Transaction tx = cont.persistence().createTransaction();
    try {
        EntityManager em = cont.persistence().getEntityManager();

        Group group = em.getReference(Group.class, UUID.fromString("0fa2b1a5-1d68-4d69-9fbd-dff348347f93"));

        User user1 = new User();
        user1Id = user1.getId();
        user1.setGroup(group);
        user1.setLogin("user1");
        user1.setPassword(passwordEncryption.getPasswordHash(user1.getId(), "1"));
        em.persist(user1);

        User user2 = new User();
        user2Id = user2.getId();
        user2.setGroup(group);
        user2.setLogin("user2");
        user2.setPassword(passwordEncryption.getPasswordHash(user2.getId(), "2"));
        em.persist(user2);

        tx.commit();
    } finally {
        tx.end();
    }
}
 
Example 23
Source Project: cuba   Source File: TestBeforeCommitTxListener.java    License: Apache License 2.0 5 votes vote down vote up
private void queryWithFlush(Collection<Entity> managedEntities, EntityManager entityManager) {
    if (!managedEntities.stream().anyMatch(e -> e instanceof User && ((User) e).getLogin().startsWith("TxLstnrTst-")))
        return;

    TypedQuery<User> query = entityManager.createQuery("select u from sec$User u where u.login like ?1", User.class);
    query.setParameter(1, "TxLstnrTst-2-%");
    query.setFlushMode(FlushModeType.AUTO);
    User result = query.getFirstResult();
    assertNotNull(result);
}
 
Example 24
Source Project: cuba   Source File: PersistenceAttributeLoadedCheckTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    dataManager = AppBeans.get(DataManager.class);
    persistence = AppBeans.get(Persistence.class);

    try (Transaction tx = persistence.createTransaction()) {
        EntityManager em = persistence.getEntityManager();

        ScheduledTask task = new ScheduledTask();
        task.setBeanName("BeanName");
        task.setMethodName("MethodName");
        taskId = task.getId();

        User user = new User();
        userId = user.getId();
        user.setName("testUser");
        user.setLogin("login" + userId);
        user.setPassword("000");
        user.setGroup(em.find(Group.class, groupId));
        em.persist(user);

        em.persist(task);
        em.persist(user);
        tx.commit();
    }

    taskView = new View(ScheduledTask.class, true)
            .addProperty("beanName");

    userView = new View(User.class, true)
            .addProperty("login")
            .addProperty("loginLowerCase")
            .addProperty("name")
            .addProperty("password")
            .addProperty("group", new View(Group.class).addProperty("name"))
            .addProperty("userRoles", new View(UserRole.class));
}
 
Example 25
Source Project: cuba   Source File: LabelDsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsubscribeSubscribeComponentListener() {
    Label label = uiComponents.create(Label.NAME);

    Datasource<User> userDs = getTestUserDatasource();
    User user = userDs.getItem();
    user.setName("testName");
    label.setDatasource(userDs, "name");

    label.setDatasource(null, null);

    // datasource before listener
    label.setDatasource(userDs, "name");
    assertEquals("testName", label.getValue());

    boolean[] valueWasChanged = {false};
    Consumer<HasValue.ValueChangeEvent> listener = e -> valueWasChanged[0] = true;
    label.addValueChangeListener(listener);

    user.setName("anotherName");
    assertEquals(true, valueWasChanged[0]);
    assertEquals("anotherName", label.getValue());

    // reset state
    label.removeValueChangeListener(listener);
    label.setDatasource(null, null);
    valueWasChanged[0] = false;
    label.setValue("testName");

    // listener before datasource
    label.addValueChangeListener(listener);
    label.setDatasource(userDs, "name");
    assertEquals(true, valueWasChanged[0]);
    assertEquals("anotherName", label.getValue());
}
 
Example 26
Source Project: cuba   Source File: DateFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDatasource() throws ParseException {
    DateField component = uiComponents.create(DateField.class);

    //noinspection unchecked
    Datasource<User> testDs = new DsBuilder()
            .setId("testDs")
            .setJavaClass(User.class)
            .setView(viewRepository.getView(User.class, View.LOCAL))
            .buildDatasource();

    testDs.setItem(new User());
    ((DatasourceImpl) testDs).valid();

    assertNull(component.getValue());

    Date dsInitValue = new SimpleDateFormat("dd.MM.yyyy").parse("12.12.2000");
    testDs.getItem().setCreateTs(dsInitValue);

    component.setValue(new Date());
    component.setDatasource(testDs, "createTs");
    assertEquals(dsInitValue, component.getValue());

    Date componentValue = new SimpleDateFormat("dd.MM.yyyy").parse("06.06.2000");
    component.setValue(componentValue);
    assertEquals(componentValue, testDs.getItem().getCreateTs());

    Date dsValue = new SimpleDateFormat("dd.MM.yyyy").parse("08.08.2000");
    testDs.getItem().setCreateTs(dsValue);
    assertEquals(dsValue, component.getValue());
}
 
Example 27
Source Project: cuba   Source File: TestAfterCompleteTxListener.java    License: Apache License 2.0 5 votes vote down vote up
private void testAccessUserRoles(boolean committed, Collection<Entity> detachedEntities) {
    for (Entity entity : detachedEntities) {
        if (entity instanceof User) {
            try {
                System.out.println("User roles size: " + ((User) entity).getUserRoles().size());
            } catch (IllegalStateException e) {
                System.out.println("An exception has been thrown: " + e);
            }
        }
    }
}
 
Example 28
Source Project: cuba   Source File: LookupFieldDsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsubscribeSubscribeComponentListener() {
    LookupField lookupField = uiComponents.create(LookupField.class);

    CollectionDatasource<Group, UUID> groupsDs = getTestCollectionDatasource();
    lookupField.setOptionsDatasource(groupsDs);

    Datasource<User> userDs = getTestUserDatasource();
    Group group = groupsDs.getItems().iterator().next();
    User user = userDs.getItem();
    user.setGroup(group);
    lookupField.setDatasource(userDs, "group");

    // unbind
    lookupField.setDatasource(null, null);

    // setup
    boolean[] valueWasChanged = {false};
    Consumer<HasValue.ValueChangeEvent> listener = e -> valueWasChanged[0] = true;

    // datasource before listener
    lookupField.setDatasource(userDs, "group");
    lookupField.addValueChangeListener(listener);

    user.setGroup(metadata.create(Group.class));
    assertTrue(valueWasChanged[0]);

    // reset state

    valueWasChanged[0] = false;
    lookupField.setDatasource(null, null);
    lookupField.removeValueChangeListener(listener);
    lookupField.setValue(null);

    // listener before datasource

    lookupField.addValueChangeListener(listener);
    lookupField.setDatasource(userDs, "group");
    assertTrue(valueWasChanged[0]);
}
 
Example 29
Source Project: cuba   Source File: UserSessions.java    License: Apache License 2.0 5 votes vote down vote up
public UserSessions() {
    User noUser = new User();
    noUser.setLogin("server");
    NO_USER_SESSION = new UserSession(
            UUID.fromString("a66abe96-3b9d-11e2-9db2-3860770d7eaf"), noUser,
            Collections.emptyList(), Locale.ENGLISH, true) {
        @Override
        public UUID getId() {
            return AppContext.NO_USER_CONTEXT.getSessionId();
        }
    };
}
 
Example 30
Source Project: cuba   Source File: DataManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTemporalType() throws Exception {
    Date nextYear = DateUtils.addYears(AppBeans.get(TimeSource.class).currentTimestamp(), 1);
    LoadContext<User> loadContext = LoadContext.create(User.class).setQuery(
            LoadContext.createQuery("select u from sec$User u where u.createTs = :ts")
                    .setParameter("ts", nextYear, TemporalType.DATE));

    List<User> users = dataManager.loadList(loadContext);
    assertTrue(users.isEmpty());
}