@RequestMapping(method = RequestMethod.GET)
  public String showForm(
      @RequestParam(value = ACTIVE_CATEGORY, required = true) final String activeCategory,
      @RequestParam(value = "agent", required = true) final String agentId,
      @RequestParam(value = SEND_STATUS, required = false) final String viewStatus,
      final Model model)
      throws CMSItemNotFoundException, YFormServiceException, InvalidAttributeValueException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(CONTACT_AGENT_FORM_CMS_PAGE));

    if (SEND.equals(viewStatus)) {
      final String dataId =
          sessionService.getAttribute(
              FinancialacceleratorstorefrontConstants.FINANCIAL_FIND_AGENT_FORM_ID);
      if (StringUtils.isNotEmpty(dataId)) {
        final YFormDataData yfdd = getYformFacade().getYFormData(dataId, YFormDataTypeEnum.DATA);
        agentFacade.sendMail(yfdd.getContent());

        sessionService.removeAttribute(
            FinancialacceleratorstorefrontConstants.FINANCIAL_FIND_AGENT_FORM_ID);
        model.addAttribute(THANK_YOU, Boolean.TRUE);
      } else {
        throw new InvalidAttributeValueException(
            "Can't upload yFormData. Attribute 'financialFindAgentForm' doesn't exist in session.");
      }
    }

    if (StringUtils.isNotBlank(agentId)) {
      final AgentData agent = getAgentFacade().getAgentByUid(agentId);
      model.addAttribute(AGENT_DATA, agent);
      model.addAttribute(ACTIVE_CATEGORY, activeCategory);
    }

    return ControllerConstants.Views.Pages.Agent.ContactAgentForm;
  }
 /**
  * Enables or disables language fall back
  *
  * <p>
  *
  * @param httpRequest current request
  * @param enabled enabled or disabled
  */
 protected void setFallbackLanguage(final HttpServletRequest httpRequest, final Boolean enabled) {
   final SessionService sessionService = getSessionService();
   if (sessionService != null) {
     sessionService.setAttribute(LocalizableItem.LANGUAGE_FALLBACK_ENABLED, enabled);
     sessionService.setAttribute(
         AbstractItemModel.LANGUAGE_FALLBACK_ENABLED_SERVICE_LAYER, enabled);
   }
 }
  @Override
  public ConfigurationProvider getProvider() {
    ConfigurationProvider provider = sessionService.getAttribute(SESSION_CACHE_KEY);
    if (provider == null) {
      provider = createProviderInstance();
      sessionService.setAttribute(SESSION_CACHE_KEY, provider);
    }

    return provider;
  }
  @Test
  public void testGetBranch() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            login(userId);

            // test getBranchMethod
            B2BUnitModel unit = b2bUnitService.getUnitForUid("IC");
            Assert.assertNotNull(unit);
            final Set<B2BUnitModel> decendents = b2bUnitService.getBranch(unit);
            Assert.assertNotNull(decendents);
            Assert.assertEquals(11, decendents.size());

            // test getAllUnitsOfOrganization
            final Set<B2BUnitModel> allUnits = b2bUnitService.getBranch(unit);
            Assert.assertNotNull(allUnits);
            Assert.assertEquals(11, allUnits.size());

            unit = b2bUnitService.getUnitForUid("IC Sales");
            Assert.assertNotNull(unit);
            Assert.assertEquals(b2bUnitService.getParent(unit).getUid(), "IC");
            Assert.assertEquals(b2bUnitService.getRootUnit(unit).getUid(), "IC");
            Assert.assertEquals(9, b2bUnitService.getBranch(unit).size());
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void shouldUpdateBranchInSession() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final JaloSession currentSession = JaloSession.getCurrentSession();
            final DefaultSession session =
                (DefaultSession) sessionService.getSession(currentSession.getSessionID());
            Assert.assertEquals(currentSession, session.getJaloSession());

            session.setAttribute("test", new Object());
            Assert.assertNotNull(currentSession.getAttribute("test"));
            final B2BCustomerModel user = (B2BCustomerModel) userService.getUserForUID("IC CEO");
            session.setAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH, null);
            session.setAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT, null);
            Assert.assertNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH));
            Assert.assertNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT));

            b2bUnitService.updateBranchInSession(session, user);
            Assert.assertNotNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_BRANCH));
            Assert.assertNotNull(currentSession.getAttribute(B2BConstants.CTX_ATTRIBUTE_ROOTUNIT));
          }
        },
        userService.getAdminUser());
  }
  /** Populates the flight extra content */
  @Override
  public void populate(final Object source, final ContentViewData target) {
    // REVISIT:Changed to BasePackage
    final BasePackage packageModel = packageCartService.getBasePackage();
    final FlightExtraFacilityStore flightExtraStore =
        sessionService.getAttribute(SessionObjectKeys.FLIGHT_EXTRA_FACILITY_STORE);
    String flightMealCode = StringUtils.EMPTY;
    if (flightExtraStore != null) {
      String inventoryCode = StringUtils.EMPTY;
      final Map<String, List<ExtraFacility>> validExtraFacilitiesMap =
          flightExtraStore.getExtraFacilityFromAllLegsBasedOnCabinClass(
              packageModel.getId(), PackageUtilityService.getCabinClass(packageModel));
      for (final List<ExtraFacility> eachEntry : validExtraFacilitiesMap.values()) {
        inventoryCode = eachEntry.get(0).getExtraFacilityCategory().getInventoryCode();
        final String extraCode = eachEntry.get(0).getExtraFacilityCode();
        final String corporateCode = eachEntry.get(0).getCorporateCode();
        final List<DynamicContentConfigModel> dynamicContents =
            genericContentService.getDynamicContentConfig(inventoryCode, extraCode, corporateCode);

        getDynamicContents(target, dynamicContents);
      }
      if (StringUtils.equalsIgnoreCase(inventoryCode, "FM")) {
        flightMealCode = inventoryCode;
      }

      final Leg leg = getFlightLeg(packageModel);
      populateContentForShortHaul(target, leg);
      populateMealContent(flightMealCode, target);
    }
  }
  @Before
  public void beforeTest() throws Exception {
    B2BIntegrationTest.loadTestData();
    importCsv("/b2bapprovalprocess/test/b2borganizations.csv", "UTF-8");
    importCsv("/b2bapprovalprocess/test/creditlimit.impex", "UTF-8");

    sessionService
        .getCurrentSession()
        .setAttribute(
            "user", this.modelService.<Object>toPersistenceLayer(userService.getAdminUser()));
    i18nService.setCurrentLocale(Locale.ENGLISH);
    commonI18NService.setCurrentLanguage(commonI18NService.getLanguage("en"));
    commonI18NService.setCurrentCurrency(commonI18NService.getCurrency("EUR"));
  }
 /**
  * This test is specially added for fetching the tree of child Unit in the organization hierarchy.
  * So used a user Id which is not the root unit for example GC.
  */
 @Test
 public void shouldGetAllBranchAndParentUnitOfChildUnit() {
   sessionService.executeInLocalView(
       new SessionExecutionBody() {
         @Override
         public void executeWithoutResult() {
           final String userId = "GC Sales UK Boss";
           login(userId);
           final Set<B2BUnitModel> allUnitsOfOrganization =
               b2bUnitService.getAllUnitsOfOrganization(
                   b2bCustomerService.getCurrentB2BCustomer());
           Assert.assertTrue(allUnitsOfOrganization.size() >= 3);
         }
       },
       userService.getAdminUser());
 }
  @Test
  public void testGetCurrentJavaCurrencyWithNonExistentJavaCurrency() {
    final CurrencyModel currency1 = new CurrencyModel();
    currency1.setIsocode("BLABLA");

    when(sessionService.getAttribute(I18NConstants.CURRENCY_SESSION_ATTR_KEY))
        .thenReturn(currency1);
    try {
      i18NService.getCurrentJavaCurrency();
      fail();
    } catch (final ConfigurationException e) {
      // ok
    }

    verify(sessionService, times(1)).getAttribute(Mockito.anyString());
  }
  @Test
  public void testGetCurrentTimeZone() {
    final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
    when(sessionService.getAttribute(I18NConstants.TIMEZONE_SESSION_ATTR_KEY)).thenReturn(timeZone);

    final TimeZone currentTimeZone = i18NService.getCurrentTimeZone();
    assertEquals(
        "Wrong current time zone ID! Should be: '"
            + timeZone.getID()
            + "' but was: '"
            + currentTimeZone.getID()
            + "'.",
        timeZone.getID(),
        currentTimeZone.getID());

    verify(sessionService, times(1)).getAttribute(Mockito.anyString());
  }
  @Test
  public void shouldGetParentUnitForCustomerWithMultipleUnitsAssigned() {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final B2BCustomerModel user =
                userService.getUserForUID("GC CEO", B2BCustomerModel.class);
            // assign user to session
            login(user);
            final B2BUnitModel parent = b2bUnitService.getParent(user);
            Assert.assertNotNull(parent);
            // try to add the member which the user is already a member of
            b2bUnitService.addMember(parent, user);
            modelService.save(user);
            Assert.assertEquals(
                1,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());

            // assign a 2nd unit to GC CEO
            final B2BUnitModel unitUK = b2bUnitService.getUnitForUid("GC Sales UK");
            b2bUnitService.addMember(unitUK, user);
            modelService.save(user);
            Assert.assertEquals(
                2,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());

            b2bUnitService.updateParentB2BUnit(unitUK, user);
            modelService.save(user);

            Assert.assertEquals(unitUK, b2bUnitService.getParent(user));
            // make sure user is still belongs to 2 units
            Assert.assertEquals(
                2,
                CollectionUtils.select(
                        user.getGroups(), PredicateUtils.instanceofPredicate(B2BUnitModel.class))
                    .size());
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void
      shouldExecuteSaveVaragsObjectsInTransactionWhenGlobalTransactionFlagIsFalseButLocallyTransactionsAreEnabled()
          throws Exception {
    // given
    modelService.setTransactional(false);
    doReturn(sessionService).when(modelService).lookupSessionService();
    given(sessionService.getAttribute(DefaultModelService.ENABLE_TRANSACTIONAL_SAVES))
        .willReturn(Boolean.TRUE);

    // when (execute all 4 save* methods)
    modelService.save(model1);
    modelService.saveAll(model1, model2);
    modelService.saveAll(Collections.singletonList(model1));
    modelService.saveAll();

    // then (should be 4 interactions with transaction mock)
    verify(transaction, times(4)).execute((TransactionCallback) anyObject());
  }
  @Test
  public void removeAllWithoutTransaction() throws Exception {
    // given
    doReturn(sessionService).when(modelService).lookupSessionService();
    doReturn(interceptorRegistry).when(modelService).lookupInterceptorRegistry();
    doReturn(converterRegistry).when(modelService).lookupConverterRegistry();
    given(converterRegistry.getModelConverterByModelType((Class) anyObject()))
        .willReturn(modelConverter);
    given(modelConverter.getType(model1)).willReturn("ItemModel");
    given(sessionService.getAttribute(DefaultModelService.ENABLE_TRANSACTIONAL_SAVES))
        .willReturn(Boolean.FALSE);

    // when (execute 2 remove* methods)
    modelService.remove(model1);
    modelService.removeAll(Arrays.asList(model1, model2));

    // then (should be 0 interactions with transaction mock)
    verify(transaction, times(0)).execute((TransactionCallback) anyObject());
  }
  @Test
  public void testGetCurrentJavaCurrency() {
    final CurrencyModel currency1 = new CurrencyModel();
    currency1.setIsocode("USD");

    when(sessionService.getAttribute(I18NConstants.CURRENCY_SESSION_ATTR_KEY))
        .thenReturn(currency1);
    final Currency currentJavaCurrency = i18NService.getCurrentJavaCurrency();

    assertEquals(
        "Wrong current java currency isocode! Should be: '"
            + currency1.getIsocode()
            + "' but was: '"
            + currentJavaCurrency.getCurrencyCode()
            + "'.",
        currency1.getIsocode(),
        currentJavaCurrency.getCurrencyCode());

    verify(sessionService, times(1)).getAttribute(Mockito.anyString());
  }
  @Test
  public void testGetApprovalProcessCode() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            String approvalCode = null;
            login(userId);

            // test findApprovalProcessCodeForUnit
            final B2BUnitModel unit = b2bUnitService.getUnitForUid("IC");
            Assert.assertNotNull(unit);
            // test
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unit);
            Assert.assertNull(approvalCode);

            unit.setApprovalProcessCode("simpleapproval");
            modelService.save(unit);

            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unit);
            Assert.assertNotNull(approvalCode);
            // test findApprovalProcessCodeForUnit - get value from parent
            final B2BUnitModel unitSales = b2bUnitService.getUnitForUid("IC Sales");
            Assert.assertNotNull(unitSales);
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unitSales);
            Assert.assertNotNull(approvalCode);

            unit.setApprovalProcessCode(null);
            modelService.save(unit);
            approvalCode = b2bUnitService.getApprovalProcessCodeForUnit(unitSales);
            Assert.assertNull(approvalCode);
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void
      shouldExecuteSaveVaragsObjectsWithoutTransactionWhenGlobalTransactionFlagIsTrueButLocallyTransactionsAreDisabled()
          throws Exception {
    // given
    modelService.setTransactional(true);
    doReturn(sessionService).when(modelService).lookupSessionService();
    doReturn(interceptorRegistry).when(modelService).lookupInterceptorRegistry();
    doReturn(converterRegistry).when(modelService).lookupConverterRegistry();
    given(converterRegistry.getModelConverterByModelType((Class) anyObject()))
        .willReturn(modelConverter);
    given(modelConverter.getType(model1)).willReturn("ItemModel");
    given(sessionService.getAttribute(DefaultModelService.ENABLE_TRANSACTIONAL_SAVES))
        .willReturn(Boolean.FALSE);

    // when (execute all 4 save* methods)
    modelService.save(model1);
    modelService.saveAll(model1, model2);
    modelService.saveAll(Collections.singletonList(model1));
    modelService.saveAll();

    // then (should be 0 interactions with transaction mock)
    verify(transaction, times(0)).execute((TransactionCallback) anyObject());
  }
  @Test
  public void shouldDisableBranchofParentUnit() {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "GC CEO";
            login(userId);

            final B2BUnitModel unitUK = b2bUnitService.getUnitForUid("GC Sales UK");

            b2bUnitService.disableBranch(unitUK);

            LOG.debug("Test all units are disabled for : " + unitUK.getUid());

            final Set<B2BUnitModel> allUnitsOfOrganization = b2bUnitService.getBranch(unitUK);

            for (final B2BUnitModel unit : allUnitsOfOrganization) {
              Assert.assertFalse(unit.getActive().booleanValue());
            }
          }
        },
        userService.getAdminUser());
  }
  @Test
  public void testIsLocalizationFallbackEnabled() {
    // both attributes are set to true
    when(sessionService.getAttribute(AbstractItemModel.LANGUAGE_FALLBACK_ENABLED_SERVICE_LAYER))
        .thenReturn(Boolean.TRUE);
    when(sessionService.getAttribute(I18NConstants.LANGUAGE_FALLBACK_ENABLED))
        .thenReturn(Boolean.TRUE);
    assertTrue(
        "The localization fallback mechanism should be enabled!",
        i18NService.isLocalizationFallbackEnabled());
    verify(sessionService, times(2)).getAttribute(Mockito.anyString());

    Mockito.reset(sessionService);

    // servicelayer attribute is set to false
    when(sessionService.getAttribute(AbstractItemModel.LANGUAGE_FALLBACK_ENABLED_SERVICE_LAYER))
        .thenReturn(Boolean.FALSE);
    when(sessionService.getAttribute(I18NConstants.LANGUAGE_FALLBACK_ENABLED))
        .thenReturn(Boolean.TRUE);
    assertFalse(
        "The localization fallback mechanism should be disabled!",
        i18NService.isLocalizationFallbackEnabled());
    verify(sessionService, times(1)).getAttribute(Mockito.anyString());

    Mockito.reset(sessionService);

    // jalo attribute is set to false
    when(sessionService.getAttribute(AbstractItemModel.LANGUAGE_FALLBACK_ENABLED_SERVICE_LAYER))
        .thenReturn(Boolean.TRUE);
    when(sessionService.getAttribute(I18NConstants.LANGUAGE_FALLBACK_ENABLED))
        .thenReturn(Boolean.FALSE);
    assertFalse(
        "The localization fallback mechanism should be disabled!",
        i18NService.isLocalizationFallbackEnabled());
    verify(sessionService, times(2)).getAttribute(Mockito.anyString());
  }
 /** @param user */
 public void login(final UserModel user) {
   userService.setCurrentUser(user);
   b2bUnitService.updateBranchInSession(sessionService.getCurrentSession(), user);
 }
  @Test
  public void testRestrictionsOfUsersAndUnits() throws Exception {
    sessionService.executeInLocalView(
        new SessionExecutionBody() {
          @Override
          public void executeWithoutResult() {
            final String userId = "IC CEO";
            login(userId);

            // test restrictions on units and employees
            Assert.assertNull(b2bUnitService.getUnitForUid("GC"));
            Assert.assertNull(
                baseDao.findFirstByAttribute(B2BCustomer.UID, "GC CEO", B2BCustomerModel.class));

            // test costcenter and budget restriction
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "IC 0", B2BCostCenterModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "GC 0", B2BCostCenterModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "IC BUDGET EUR 1M", B2BBudgetModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "GC BUDGET EUR 1M", B2BBudgetModel.class));

            // change the session IC_USER to the customer who belongs to different organization
            final UserModel GC_USER =
                (UserModel)
                    sessionService.executeInLocalView(
                        new SessionExecutionBody() {
                          @Override
                          public Object execute() {
                            searchRestrictionService.disableSearchRestrictions();
                            final UserModel user =
                                baseDao.findFirstByAttribute(
                                    B2BCustomerModel.UID, "GC CEO", B2BCustomerModel.class);
                            Assert.assertNotNull(user);
                            return user;
                          }
                        });
            Assert.assertNotNull(GC_USER);
            login(GC_USER);
            // should now we able to see only items linked to C_2.. units
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "IC 0", B2BCostCenterModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BCostCenterModel.CODE, "GC 0", B2BCostCenterModel.class));
            Assert.assertNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "IC BUDGET EUR 1M", B2BBudgetModel.class));
            Assert.assertNotNull(
                baseDao.findFirstByAttribute(
                    B2BBudgetModel.CODE, "GC BUDGET EUR 1M", B2BBudgetModel.class));
          }
        },
        userService.getAdminUser());
  }
 public static void resetSessionOverrides() {
   final SessionService sessionService = getStaticSessionService();
   sessionService.removeAttribute(B2B_SESSION_KEY_CHECKOUT_FLOW);
   sessionService.removeAttribute(B2B_SESSION_KEY_SUBSCRIPTION_PCI_OPTION);
 }