/**
   * Simulates the effect of database storing a particular date.
   *
   * <p>On MySQL this means dropping all milliseconds!
   *
   * <p>On MSSQL produces a discrete values 0,3,7 on the less important position
   */
  private Date adjustToDB(final Date date) {
    if (Config.isMySQLUsed()) {
      return new Date((date.getTime() / 1000) * 1000);
    }
    // PLA-11109
    else if (Config.isSQLServerUsed()) {
      final long millis = date.getTime();
      long roundedmillis = 0;
      switch ((int) (millis % 10)) {
        case 0:
        case 1:
          roundedmillis = (millis / 10 * 10);
          break;

        case 2:
        case 3:
        case 4:
          roundedmillis = (millis / 10 * 10) + 3;
          break;
        case 5:
        case 6:
        case 7:
        case 8:
          roundedmillis = (millis / 10 * 10) + 7;
          break;
        case 9:
          roundedmillis = (millis / 10 * 10) + 10;
          break;
      }
      return new java.util.Date(roundedmillis);
    } else {
      return date;
    }
  }
  public static void startSuite() throws IOException {
    if (robotTestSuite == null) {
      final PythonAware pythonAware =
          new DefaultPythonProvider(Config.getParameter("atddengine.libraries-path"));

      final RobotSettings robotSettings = new RobotSettings();

      robotSettings.setOutputDir(
          new File(Config.getParameter("atddengine.report-path"), "quotation"));
      robotSettings.setLogName("InsuranceQuotation_Test-log");
      robotSettings.setOutputName("InsuranceQuotation_Test-output");
      robotSettings.setReportName("InsuranceQuotation_Test-report");

      final RobotTestSuiteFactory robotTestSuiteFactory =
          new PythonRobotTestSuiteFactory(pythonAware);

      robotTestSuite =
          robotTestSuiteFactory.parseTestSuite(
              robotSettings,
              new File(
                  "/opt/bamboo-agent/xml-data/build-dir/HYM-IA1-JOB1/source/financialacceleratorstorefrontatddtests/genresources/robottests/InsuranceQuotation_Test.txt"));
    }

    if (!robotTestSuite.isStarted()) {
      robotTestSuite.start();
    }
  }
  @Test
  public void shouldImportScriptWithLegacyModeOffWhenGlobalSwitchIsOnUsingImportConfig() {
    // given
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    final ImpExResource mediaRes =
        new StreamBasedImpExResource(
            new ByteArrayInputStream("INSERT Language;isocode;active\n;test;true".getBytes()),
            CSVConstants.HYBRIS_ENCODING);
    final ImportConfig config = new ImportConfig();
    config.setLegacyMode(Boolean.FALSE);
    config.setSynchronous(true);
    config.setFailOnError(true);
    config.setScript(mediaRes);
    config.setRemoveOnSuccess(false);

    // when
    final ImportResult importResult = importService.importData(config);

    // then
    assertThat(importResult.isFinished()).isTrue();
    assertThat(importResult.isError()).isFalse();
    assertThat(Boolean.parseBoolean(Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY)))
        .isTrue();
    assertThat(importResult.getCronJob().getLegacyMode()).isFalse();
  }
  @Override
  public Transition executeAction(final OrderProcessModel process) {
    LOG.info("Process: " + process.getCode() + " in step " + getClass());
    ServicesUtil.validateParameterNotNull(process, "Process can not be null");
    ServicesUtil.validateParameterNotNull(process.getOrder(), "Order can not be null");

    final double scoreLimit =
        Double.parseDouble(
            Config.getParameter(
                HybrisTestFulfilmentProcessConstants.EXTENSIONNAME + ".fraud.scoreLimitExternal"));
    final double scoreTolerance =
        Double.parseDouble(
            Config.getParameter(
                HybrisTestFulfilmentProcessConstants.EXTENSIONNAME
                    + ".fraud.scoreToleranceExternal"));

    final OrderModel order = process.getOrder();
    final FraudServiceResponse response =
        getFraudService().recognizeOrderSymptoms(getProviderName(), order);
    final double score = response.getScore();
    if (score < scoreLimit) {
      final FraudReportModel fraudReport =
          createFraudReport(providerName, response, order, FraudStatus.OK);
      final OrderHistoryEntryModel historyEntry =
          createHistoryLog(providerName, order, FraudStatus.OK, null);
      order.setFraudulent(Boolean.FALSE);
      order.setPotentiallyFraudulent(Boolean.FALSE);
      order.setStatus(OrderStatus.FRAUD_CHECKED);
      modelService.save(fraudReport);
      modelService.save(historyEntry);
      modelService.save(order);
      return Transition.OK;
    } else if (score < scoreLimit + scoreTolerance) {
      final FraudReportModel fraudReport =
          createFraudReport(providerName, response, order, FraudStatus.CHECK);
      final OrderHistoryEntryModel historyEntry =
          createHistoryLog(providerName, order, FraudStatus.CHECK, fraudReport.getCode());
      order.setFraudulent(Boolean.FALSE);
      order.setPotentiallyFraudulent(Boolean.TRUE);
      order.setStatus(OrderStatus.FRAUD_CHECKED);
      modelService.save(fraudReport);
      modelService.save(historyEntry);
      modelService.save(order);
      return Transition.POTENTIAL;
    } else {
      final FraudReportModel fraudReport =
          createFraudReport(providerName, response, order, FraudStatus.FRAUD);
      final OrderHistoryEntryModel historyEntry =
          createHistoryLog(providerName, order, FraudStatus.FRAUD, fraudReport.getCode());
      order.setFraudulent(Boolean.TRUE);
      order.setPotentiallyFraudulent(Boolean.FALSE);
      order.setStatus(OrderStatus.FRAUD_CHECKED);
      modelService.save(fraudReport);
      modelService.save(historyEntry);
      modelService.save(order);
      return Transition.FRAUD;
    }
  }
  @Before
  public void setUp() throws Exception {
    createCoreData();
    createDefaultCatalog();
    productModel01 = productService.getProduct("testProduct1");
    userModel01 = userService.getUser("anonymous");
    userModel02 = userService.getCurrentUser();

    oldMinimalRating = Config.getParameter(CustomerReviewConstants.KEYS.MINIMAL_RATING);
    oldMaximalRating = Config.getParameter(CustomerReviewConstants.KEYS.MAXIMAL_RATING);

    // Set some configuration values to be used generally in the tests
    Config.setParameter(CustomerReviewConstants.KEYS.MINIMAL_RATING, String.valueOf(0));
    Config.setParameter(CustomerReviewConstants.KEYS.MAXIMAL_RATING, String.valueOf(4));
  }
예제 #6
0
  @Override
  public void doTag() throws JspException, IOException {
    final boolean enabled = Config.getBoolean(ENABLE_TEST_IDS_PROPERTY, false);
    if (enabled) {
      final PageContext pageContext = (PageContext) getJspContext();
      final JspWriter jspWriter = pageContext.getOut();

      final int nextUniqueId = getNextUniqueId(pageContext);

      jspWriter
          .append("<div id=\"")
          .append("test_")
          .append(cleanupHtmlId(getCode()))
          .append("_$")
          .append(String.valueOf(nextUniqueId))
          .append("\" style=\"display:inline\">");

      // Write the body out
      getJspBody().invoke(jspWriter);

      jspWriter.println("</div>");
    } else {
      // Just render the contents
      getJspBody().invoke(getJspContext().getOut());
    }
  }
  protected String dumpMediaMimeInfo(final MediaModel media) {
    final PK mediaPK = media.getPk();
    final Media jaloItem = JaloSession.getCurrentSession().getItem(mediaPK);

    final boolean isNew = modelService.isNew(media);
    final boolean isDirty = modelService.isModified(media);
    final boolean txRunning = Transaction.current().isRunning();
    final boolean txCacheIsolationEnabled = Config.itemCacheIsolationActivated();
    final boolean itemCacheBound = jaloItem.isCacheBound();

    return "Media(pk:"
        + media.getPk()
        + "/"
        + jaloItem.getPK()
        + ", new="
        + isNew
        + ", modified="
        + isDirty
        + ", txRunning="
        + txRunning
        + ", txCacheIsolation="
        + txCacheIsolationEnabled
        + ", cacheBound="
        + itemCacheBound;
  }
예제 #8
0
 protected List<String> splitSkusAsList(final String skus) {
   return Arrays.asList(
       StringUtils.split(
           skus,
           Config.getString(
               ADVANCED_SEARCH_PRODUCT_IDS_DELIMITER,
               ADVANCED_SEARCH_PRODUCT_IDS_DELIMITER_DEFAULT)));
 }
  @RequestMapping(value = "/select-suggested-address", method = RequestMethod.POST)
  public String doSelectSuggestedAddress(
      final AddressForm addressForm, final RedirectAttributes redirectModel) {
    final Set<String> resolveCountryRegions =
        org.springframework.util.StringUtils.commaDelimitedListToSet(
            Config.getParameter("resolve.country.regions"));

    final AddressData selectedAddress = new AddressData();
    selectedAddress.setId(addressForm.getAddressId());
    selectedAddress.setTitleCode(addressForm.getTitleCode());
    selectedAddress.setFirstName(addressForm.getFirstName());
    selectedAddress.setLastName(addressForm.getLastName());
    selectedAddress.setLine1(addressForm.getLine1());
    selectedAddress.setLine2(addressForm.getLine2());
    selectedAddress.setTown(addressForm.getTownCity());
    selectedAddress.setPostalCode(addressForm.getPostcode());
    selectedAddress.setBillingAddress(false);
    selectedAddress.setShippingAddress(true);
    selectedAddress.setVisibleInAddressBook(true);

    final CountryData countryData = i18NFacade.getCountryForIsocode(addressForm.getCountryIso());
    selectedAddress.setCountry(countryData);

    if (resolveCountryRegions.contains(countryData.getIsocode())) {
      if (addressForm.getRegionIso() != null && !StringUtils.isEmpty(addressForm.getRegionIso())) {
        final RegionData regionData =
            getI18NFacade().getRegion(addressForm.getCountryIso(), addressForm.getRegionIso());
        selectedAddress.setRegion(regionData);
      }
    }

    if (resolveCountryRegions.contains(countryData.getIsocode())) {
      if (addressForm.getRegionIso() != null && !StringUtils.isEmpty(addressForm.getRegionIso())) {
        final RegionData regionData =
            getI18NFacade().getRegion(addressForm.getCountryIso(), addressForm.getRegionIso());
        selectedAddress.setRegion(regionData);
      }
    }

    if (Boolean.TRUE.equals(addressForm.getEditAddress())) {
      selectedAddress.setDefaultAddress(
          Boolean.TRUE.equals(addressForm.getDefaultAddress())
              || userFacade.getAddressBook().size() <= 1);
      userFacade.editAddress(selectedAddress);
    } else {
      selectedAddress.setDefaultAddress(
          Boolean.TRUE.equals(addressForm.getDefaultAddress()) || userFacade.isAddressBookEmpty());
      userFacade.addAddress(selectedAddress);
    }

    GlobalMessages.addFlashMessage(
        redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "account.confirmation.address.added");

    return REDIRECT_TO_ADDRESS_BOOK_PAGE;
  }
 protected boolean isCSRFExemptUrl(final String servletPath) {
   if (servletPath != null) {
     final String allowedUrlPatterns = Config.getParameter(CSRF_ALLOWED_URLS);
     final Set<String> allowedUrls = StringUtils.commaDelimitedListToSet(allowedUrlPatterns);
     for (final String pattern : allowedUrls) {
       if (servletPath.matches(pattern)) {
         return true;
       }
     }
   }
   return false;
 }
  @Before
  public void setUp() throws Exception {
    // final Create data for tests
    LOG.info("Creating data for DefaultChangeProductPriceBundleRuleDaoIntegrationTest ..");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);

    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "false");
    importCsv("/subscriptionservices/test/testSubscriptionCommerceCartService.impex", "utf-8");
    importCsv("/configurablebundleservices/test/testBundleCommerceCartService.impex", "utf-8");
    importCsv("/configurablebundleservices/test/testApproveAllBundleTemplates.impex", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for DefaultChangeProductPriceBundleRuleDaoIntegrationTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");

    baseSiteService.setCurrentBaseSite(baseSiteService.getBaseSiteForUID(TEST_BASESITE_UID), false);
    catalogVersionService.setSessionCatalogVersion("testCatalog", "Online");

    currencyUSD = commonI18NService.getCurrency("USD");
    currencyEUR = commonI18NService.getCurrency("EUR");
    galaxynexus = productService.getProductForCode("GALAXY_NEXUS");
    standardplan1y = productService.getProductForCode("PLAN_STANDARD_1Y");
    standardplan3y = productService.getProductForCode("PLAN_STANDARD_3Y");
    smartPhonePlanBundleTemplate =
        bundleTemplateService.getBundleTemplateForCode("SmartPhonePlanSelection");
    smartPhoneDeviceBundleTemplate =
        bundleTemplateService.getBundleTemplateForCode("SmartPhoneDeviceSelection");

    modelService.detachAll();
  }
  @Before
  public void setUp() throws Exception {
    LOG.info("Creating data for SubscriptionEntitlementTest ...");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);
    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "false");
    importCsv("/subscriptionservices/test/testSubscriptionCommerceCartService.impex", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for SubscriptionEntitlementTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");
    modelService.detachAll();
  }
  @Before
  public void setUp() throws Exception {
    // final Create data for tests
    LOG.info("Creating data for BundleSelectionCriteriaIDPrepareInterceptorIntegrationTest ...");
    userService.setCurrentUser(userService.getAdminUser());
    final long startTime = System.currentTimeMillis();
    new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);
    // importing test csv
    final String legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
    LOG.info(
        "Existing value for " + ImpExConstants.Params.LEGACY_MODE_KEY + " :" + legacyModeBackup);
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    importCsv("/commerceservices/test/testCommerceCart.csv", "utf-8");
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);

    LOG.info(
        "Finished data for BundleSelectionCriteriaIDPrepareInterceptorIntegrationTest "
            + (System.currentTimeMillis() - startTime)
            + "ms");

    baseSiteService.setCurrentBaseSite(baseSiteService.getBaseSiteForUID(TEST_BASESITE_UID), false);
    catalogVersionService.setSessionCatalogVersion("testCatalog", "Online");
  }
  /**
   * This method will be called by system creator during initialization and system update. Be sure
   * that this method can be called repeatedly.
   *
   * @param context the context provides the selected parameters and values
   */
  @SystemSetup(type = Type.ESSENTIAL, process = Process.ALL)
  public void createEssentialData(final SystemSetupContext context) {
    final boolean importCustomReports =
        getBooleanSystemSetupParameter(context, IMPORT_CUSTOM_REPORTS);

    if (importCustomReports) {
      if (MediaManager.getInstance()
              .getMediaFolderByQualifier(V2kartCockpitsConstants.JASPER_REPORTS_MEDIA_FOLDER)
              .size()
          < 1) {
        MediaManager.getInstance()
            .createMediaFolder(
                V2kartCockpitsConstants.JASPER_REPORTS_MEDIA_FOLDER,
                V2kartCockpitsConstants.JASPER_REPORTS_MEDIA_FOLDER);
      }
      try {
        String prefix = null;
        if (Config.isMySQLUsed()) {
          prefix = "mysql";
        } else if (Config.isHSQLDBUsed()) {
          prefix = "hsqldb";
        } else if (Config.isOracleUsed()) {
          prefix = "oracle";
        } else if (Config.isSQLServerUsed()) {
          prefix = "sqlserver";
        }

        if (prefix != null) {
          importImpexFile(
              context, "/v2kartcockpits/reportcockpit/import/" + prefix + "_jasperreports.impex");
        }
      } catch (final Exception e) {
        LOG.error("Error during Jasper Report files import " + e);
      }
    }
  }
  @Override
  public void beforeView(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final ModelAndView modelAndView) {
    final boolean showDebug = Config.getBoolean(SHOW_STOREFRONT_DEBUG_INFO_PROPERTY_KEY, false);

    // Store the show debug flag in a request attribute
    request.setAttribute(SHOW_STOREFRONT_DEBUG_INFO, Boolean.valueOf(showDebug));

    if (showDebug) {
      final JaloSession currentSession = JaloSession.getCurrentSession();

      final TreeMap<String, Object> attributeMap = new TreeMap<String, Object>();
      // Build up the session attributes as a request attribute
      attributeMap.putAll(currentSession.getAttributes());
      // Add the session id as an attribute
      attributeMap.put("JaloSession ID", currentSession.getSessionID());

      request.setAttribute(JALO_SESSION_ATTRIBUTES, mapToString(attributeMap));
    }
  }
 @Before
 public void setUp() throws Exception {
   legacyModeBackup = Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY);
   createCoreData();
 }
/**
 * Tests item data invalidation after updates inside and outside of transaction for both model and
 * jalo layer.
 */
@PerformanceTest
public class ItemModelTransactionPerformanceTest extends ServicelayerBaseTest {
  private static final String MIME_BEFORE = "mime";
  private static final String MIME_AFTER = "mimeNew";

  private final double timeFactor = Config.getDouble("platform.test.timefactor", 1.0);

  @Resource private ModelService modelService;

  @Before
  public void prepare() {
    // enable new tx cache isolation feature
    Config.setItemCacheIsolation(Boolean.TRUE);
  }

  @After
  public void unprepare() {
    // clear new tx cache isolation feature
    Config.setItemCacheIsolation(null);
  }

  @Test
  public void testModificationTimeUpdateTxCommitStressTest() throws Exception {
    final long end = System.currentTimeMillis() + (45 * 1000); // run for 45 seconds at most
    do {
      testModificationTimeUpdateTx(true);
    } while (end > System.currentTimeMillis());
  }

  private void testModificationTimeUpdateTx(final boolean commit) throws InterruptedException {
    final MediaModel media = setupMedia("cat", "media", MIME_BEFORE);
    try {
      final Media jaloMedia = modelService.getSource(media);
      final PK mediaPK = media.getPk();
      assertEquals(mediaPK, jaloMedia.getPK());

      final Date modModelBefore = media.getModifiedtime();
      final Date modJaloBefore = jaloMedia.getModificationTime();
      assertNotNull(modModelBefore);
      assertNotNull(modJaloBefore);
      assertEquals(modJaloBefore, modModelBefore);
      Thread.sleep((long) (1500 * timeFactor)); // Some DB (MySql) do not have milliseconds!

      Date[] innerTxMod = null;
      final Transaction tx = Transaction.current();
      try {
        innerTxMod =
            (Date[])
                tx.execute(
                    new TransactionBody() {
                      @Override
                      public Object execute() throws Exception {
                        media.setMime(MIME_AFTER);
                        modelService.save(media);
                        final Date modModelAfter = media.getModifiedtime();
                        final Date modJaloAfter = jaloMedia.getModificationTime();

                        assertNotNull(modModelAfter);
                        assertNotNull(modJaloAfter);
                        assertEquals(modModelAfter, modJaloAfter);
                        assertTrue(modJaloBefore.before(modJaloAfter));

                        final Date[] otherThreadMod = getModTimeFromOtherThread(mediaPK);

                        assertNotNull(otherThreadMod);
                        assertNotNull(otherThreadMod[0]);
                        assertNotNull(otherThreadMod[1]);
                        assertEquals(modJaloBefore, otherThreadMod[0]);
                        assertEquals(modModelBefore, otherThreadMod[1]);

                        if (commit) {
                          return new Date[] {modJaloAfter, modModelAfter};
                        } else {
                          throw new RuntimeException("rollback");
                        }
                      }
                    });
      } catch (final Exception e) {
        assertFalse("unexpected tx error " + e, commit);
      }

      modelService.refresh(media); // actually not necessary but more likely to find error

      final Date modModelAfterTx = media.getModifiedtime();
      final Date modJaloAfterTx = jaloMedia.getModificationTime();

      assertNotNull(modModelAfterTx);
      assertNotNull(modJaloAfterTx);
      assertEquals(modModelAfterTx, modJaloAfterTx);
      if (commit) {
        assertEquals(adjustToDB(innerTxMod[0]).getTime(), modJaloAfterTx.getTime());
        assertEquals(adjustToDB(innerTxMod[1]).getTime(), modModelAfterTx.getTime());
        assertTrue(modJaloBefore.before(modJaloAfterTx));
      } else {
        assertEquals(modJaloBefore.getTime(), modJaloAfterTx.getTime());
        assertEquals(modModelBefore.getTime(), modModelAfterTx.getTime());
      }
    } finally {
      destroyMedia(media);
    }
  }

  /**
   * Simulates the effect of database storing a particular date.
   *
   * <p>On MySQL this means dropping all milliseconds!
   *
   * <p>On MSSQL produces a discrete values 0,3,7 on the less important position
   */
  private Date adjustToDB(final Date date) {
    if (Config.isMySQLUsed()) {
      return new Date((date.getTime() / 1000) * 1000);
    }
    // PLA-11109
    else if (Config.isSQLServerUsed()) {
      final long millis = date.getTime();
      long roundedmillis = 0;
      switch ((int) (millis % 10)) {
        case 0:
        case 1:
          roundedmillis = (millis / 10 * 10);
          break;

        case 2:
        case 3:
        case 4:
          roundedmillis = (millis / 10 * 10) + 3;
          break;
        case 5:
        case 6:
        case 7:
        case 8:
          roundedmillis = (millis / 10 * 10) + 7;
          break;
        case 9:
          roundedmillis = (millis / 10 * 10) + 10;
          break;
      }
      return new java.util.Date(roundedmillis);
    } else {
      return date;
    }
  }

  // returns [ jaloModTime, modelModTime]
  private Date[] getModTimeFromOtherThread(final PK mediaPK) {
    return runInOtherThread(
        new Callable<Date[]>() {
          @Override
          public Date[] call() throws Exception {
            final Media jaloMedia = JaloSession.getCurrentSession().getItem(mediaPK);
            final MediaModel media = modelService.get(jaloMedia);

            return new Date[] {jaloMedia.getModificationTime(), media.getModifiedtime()};
          }
        },
        15);
  }

  @Test
  public void testBusyWaitingUpdateReload() {
    // testBusyWaitingUpdateReload(30 * 60);
    testBusyWaitingUpdateReload(2 * 60);
  }

  private void testBusyWaitingUpdateReload(final int durationSeconds) {
    final MediaModel media = setupMedia("cat", "media", MIME_BEFORE);
    final Media jaloMedia = modelService.getSource(media);
    final PK mediaPK = media.getPk();
    assertEquals(mediaPK, jaloMedia.getPK());

    final RunnerCreator<BusyWaitingUpdateReloadRunner> creator =
        new RunnerCreator<ItemModelTransactionPerformanceTest.BusyWaitingUpdateReloadRunner>() {
          @Override
          public BusyWaitingUpdateReloadRunner newRunner(final int threadNumber) {
            return new BusyWaitingUpdateReloadRunner(modelService, media, 0 == threadNumber);
          }
        };

    final TestThreadsHolder<BusyWaitingUpdateReloadRunner> threads =
        new TestThreadsHolder<ItemModelTransactionPerformanceTest.BusyWaitingUpdateReloadRunner>(
            2, creator);

    threads.startAll();

    for (int sec = 0; sec < durationSeconds && !threads.hasErrors(); sec++) {
      try {
        Thread.sleep((long) (1000 * timeFactor));
      } catch (final InterruptedException e) {
        break;
      }
    }
    threads.stopAndDestroy(5);

    assertEquals(Collections.EMPTY_MAP, threads.getErrors());
  }

  class BusyWaitingUpdateReloadRunner implements Runnable {
    private final MediaModel media;
    private final ModelService modelService;
    private final boolean isReader;
    private final Tenant tenant;

    BusyWaitingUpdateReloadRunner(
        final ModelService modelService, final MediaModel media, final boolean isReader) {
      this.media = media;
      this.modelService = modelService;
      this.isReader = isReader;
      this.tenant = Registry.getCurrentTenantNoFallback();
    }

    @Override
    public void run() {
      Registry.setCurrentTenant(tenant);
      if (isReader) {
        System.out.println("Starting in reader mode");
        runAsReader();
      } else {
        System.out.println("Starting in writer mode");
        runAsWriter();
      }
    }

    private void runAsReader() {
      final long mediaPK = media.getPk().getLongValue();
      long globalPK = 0;
      while (!Thread.currentThread().isInterrupted()) {
        final MediaModel ctx = modelService.get(PK.fromLong(mediaPK));
        modelService.refresh(ctx);
        globalPK |= ctx.getPk().getLongValue();
      }
      assertEquals(mediaPK, globalPK);
    }

    private void runAsWriter() {
      long counter = 0;
      while (!Thread.currentThread().isInterrupted()) {
        boolean success = false;
        try {
          doWrite(counter++);
          writeInTx(counter++);
          success = true;
        } finally {
          if (!success) {
            System.err.println(dumpMediaMimeInfo(media));
          }
        }
      }
    }

    private void writeInTx(final long counter) {
      final Transaction tx = Transaction.current();
      try {
        tx.execute(
            new TransactionBody() {
              @Override
              public Object execute() throws Exception {
                doWrite(counter);
                return null;
              }
            });
      } catch (final Exception e) {
        throw new RuntimeException(e);
      }
    }

    private void doWrite(final long counter) {
      final String newMime = "Mime-" + counter;
      final String oldMime = media.getMime();
      assertFalse("already got new mime before", newMime.equals(oldMime));
      media.setMime(newMime);
      modelService.save(media);
      assertEquals("new mime is not visible", newMime, media.getMime());
    }
  }

  protected String dumpMediaMimeInfo(final MediaModel media) {
    final PK mediaPK = media.getPk();
    final Media jaloItem = JaloSession.getCurrentSession().getItem(mediaPK);

    final boolean isNew = modelService.isNew(media);
    final boolean isDirty = modelService.isModified(media);
    final boolean txRunning = Transaction.current().isRunning();
    final boolean txCacheIsolationEnabled = Config.itemCacheIsolationActivated();
    final boolean itemCacheBound = jaloItem.isCacheBound();

    return "Media(pk:"
        + media.getPk()
        + "/"
        + jaloItem.getPK()
        + ", new="
        + isNew
        + ", modified="
        + isDirty
        + ", txRunning="
        + txRunning
        + ", txCacheIsolation="
        + txCacheIsolationEnabled
        + ", cacheBound="
        + itemCacheBound;
  }

  private void destroyMedia(final MediaModel media) {
    try {
      final CatalogVersionModel catalogVersion = media.getCatalogVersion();
      final CatalogModel catalog = catalogVersion.getCatalog();

      modelService.remove(media);
      modelService.remove(catalogVersion);
      modelService.remove(catalog);
    } catch (final Exception e) {
      // ignore for now
    }
  }

  private MediaModel setupMedia(
      final String catalogId, final String mediaCode, final String initialMime) {
    final CatalogVersionModel catVersion = setUpCatalog(catalogId);

    final MediaModel media = createAndSaveMedia(catVersion, mediaCode, initialMime);
    final PK mediaPk = media.getPk();
    final Media jaloMedia = modelService.getSource(media);

    assertNotNull(mediaPk);
    assertNotNull(jaloMedia);
    assertEquals(mediaPk, jaloMedia.getPK());

    assertEquals(mediaCode, media.getCode());
    assertEquals(initialMime, media.getMime());

    assertEquals(mediaCode, jaloMedia.getCode());
    assertEquals(initialMime, jaloMedia.getMime());

    return media;
  }

  private <V> V runInOtherThread(final Callable<V> callable, final int timeoutSeconds) {
    final ExecutorService pool =
        Executors.newFixedThreadPool(
            1,
            new ThreadFactory() {
              final Tenant tenant = Registry.getCurrentTenantNoFallback();

              @Override
              public Thread newThread(final Runnable r) {
                return new Thread(r) {
                  @Override
                  public void run() {
                    try {
                      Registry.setCurrentTenant(tenant);
                      super.run();
                    } finally {
                      JaloSession.deactivate();
                      Registry.unsetCurrentTenant();
                    }
                  }
                };
              }
            });
    try {
      final Future<V> future = pool.submit(callable);
      return future.get(timeoutSeconds, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
      Thread.currentThread().interrupt();
      fail("interrupted while waiting");
    } catch (final ExecutionException e) {
      fail("unexpected execution exception " + e.getCause());
    } catch (final TimeoutException e) {
      fail(
          "callable "
              + callable
              + " did not finish within maximum "
              + timeoutSeconds
              + " seconds to wait");
    } finally {
      pool.shutdownNow();
    }
    return null;
  }

  private MediaModel createAndSaveMedia(
      final CatalogVersionModel cv, final String code, final String mime) {
    final MediaModel media = modelService.create(MediaModel.class);
    media.setCode(code);
    media.setMime(mime);
    media.setCatalogVersion(cv);

    modelService.save(media);

    return media;
  }

  private CatalogVersionModel setUpCatalog(final String catId) {
    final CatalogModel catalog = modelService.create(CatalogModel.class);
    catalog.setId(catId);

    final CatalogVersionModel cv = modelService.create(CatalogVersionModel.class);
    cv.setVersion(catId + "Version");
    cv.setCatalog(catalog);

    modelService.saveAll(catalog, cv);

    return cv;
  }
}
 @Override
 protected String getStorefrontContextRoot() {
   return Config.getString("b2bStorefrontContextRoot", "/acceleratorstorefront");
 }
 @Test
 public void shouldReturnFalse() {
   Config.setParameter(CisavsConstants.AVS_SHOW_SUGGESTED_ADDRESSES_PROP, "false");
   Assert.assertFalse(defaultShowSuggestedAddressesStrategy.shouldAddressSuggestionsBeShown());
 }
 @After
 public void tearDown() {
   Config.setParameter(CustomerReviewConstants.KEYS.MINIMAL_RATING, oldMinimalRating);
   Config.setParameter(CustomerReviewConstants.KEYS.MAXIMAL_RATING, oldMaximalRating);
 }
예제 #21
0
  @RequestMapping(value = "/advanced", method = RequestMethod.GET)
  public String advanceSearchResults(
      @RequestParam(value = "keywords", required = false, defaultValue = StringUtils.EMPTY)
          String keywords,
      @RequestParam(
              value = "searchResultType",
              required = false,
              defaultValue = ADVANCED_SEARCH_RESULT_TYPE_CATALOG)
          final String searchResultType,
      @RequestParam(value = "inStockOnly", required = false, defaultValue = "false")
          final boolean inStockOnly,
      @RequestParam(value = "onlyProductIds", required = false, defaultValue = "false")
          final boolean onlyProductIds,
      @RequestParam(value = "isCreateOrderForm", required = false, defaultValue = "false")
          final boolean isCreateOrderForm,
      @RequestParam(value = "q", defaultValue = StringUtils.EMPTY) String searchQuery,
      @RequestParam(value = "page", defaultValue = "0") final int page,
      @RequestParam(value = "show", defaultValue = "Page") final ShowMode showMode,
      @RequestParam(value = "sort", required = false) final String sortCode,
      final Model model)
      throws CMSItemNotFoundException {

    if (StringUtils.isNotBlank(keywords)) {
      searchQuery = keywords;
    } else {
      if (StringUtils.isNotBlank(searchQuery)) {
        keywords = StringUtils.split(searchQuery, ":")[0];
      }
    }

    // check if it is order form (either order form was selected or "Create Order Form"
    final PageableData pageableData =
        createPageableData(page, getSearchPageSize(), sortCode, showMode);
    final SearchStateData searchState =
        createSearchStateData(searchQuery, isPopulateVariants(searchResultType, isCreateOrderForm));

    final SearchPageData<ProductData> searchPageData =
        performSearch(
            searchState, pageableData, isUseFlexibleSearch(onlyProductIds, isCreateOrderForm));
    populateModel(model, searchPageData, showMode);

    String metaInfoText = null;
    if (StringUtils.isEmpty(keywords)) {
      metaInfoText =
          MetaSanitizerUtil.sanitizeDescription(
              getMessageSource()
                  .getMessage("search.advanced.meta.description.title", null, getCurrentLocale()));
    } else {
      metaInfoText = MetaSanitizerUtil.sanitizeDescription(keywords);
    }

    model.addAttribute(
        WebConstants.BREADCRUMBS_KEY,
        searchBreadcrumbBuilder.getBreadcrumbs(null, metaInfoText, false));

    final AdvancedSearchForm form = new AdvancedSearchForm();
    form.setOnlyProductIds(Boolean.valueOf(onlyProductIds));
    form.setInStockOnly(Boolean.valueOf(inStockOnly));
    form.setKeywords(keywords);
    form.setCreateOrderForm(isCreateOrderForm);

    if (isCreateOrderForm) {
      form.setSearchResultType(ADVANCED_SEARCH_RESULT_TYPE_ORDER_FORM);
      final List<String> filterSkus = splitSkusAsList(keywords);
      form.setFilterSkus(filterSkus);
      form.setCreateOrderForm(Boolean.valueOf(false));
      form.setOnlyProductIds(Boolean.valueOf(true));
    } else {
      form.setSearchResultType(searchResultType);
    }

    model.addAttribute("advancedSearchForm", form);
    model.addAttribute(
        "futureStockEnabled", Boolean.valueOf(Config.getBoolean(FUTURE_STOCK_ENABLED, false)));

    storeCmsPageInModel(model, getContentPageForLabelOrId(NO_RESULTS_ADVANCED_PAGE_ID));

    addMetaData(
        model,
        "search.meta.description.results",
        metaInfoText,
        "search.meta.description.on",
        PageType.PRODUCTSEARCH,
        "no-index,follow");

    return getViewForPage(model);
  }
 @Before
 public void prepare() {
   // enable new tx cache isolation feature
   Config.setItemCacheIsolation(Boolean.TRUE);
 }
  @Override
  public List<PossibleAttributeValue> findPossibleAttributeValues(
      final CategoryModel category,
      final Collection<ClassAttributeAssignmentModel> assignments,
      final Map<ClassAttributeAssignmentModel, Object> filteredAttributeValues) {
    final boolean useToCharForClob = Config.isOracleUsed() || Config.isHanaUsed();
    final Map<String, Object> filterParams = new HashMap<String, Object>();

    // We select the ClassAttributeAssignment, the value of the product feature, the unit
    // and a count of all product feature value. The latter is achieved by adding a group by
    // statement
    // later on
    final StringBuilder stringBuilder =
        new StringBuilder("SELECT {pf.classificationAttributeAssignment},");
    if (useToCharForClob) {
      stringBuilder.append(" to_char({pf.stringValue}),");
    } else {
      stringBuilder.append(" {pf.stringValue},");
    }
    stringBuilder.append(" {pf.unit}, COUNT(*) ");
    stringBuilder.append("FROM {").append(ProductFeatureModel._TYPECODE).append(" AS pf ");
    stringBuilder
        .append("JOIN ")
        .append(ProductModel._TYPECODE)
        .append(" ON {Product.pk} = {pf.product} } ");

    // Restricting the search to the given ClassAttributeAssignments
    stringBuilder.append("WHERE {pf.classificationAttributeAssignment} IN (?assignments) ");

    // Add a subquery that select all products with the given filter
    // This is necessary to only find attribute values contained in the filtered attributes
    final String filterQuery =
        createQueryToFindProductsByAttributeValues(
            category, filteredAttributeValues, filterParams, false);
    stringBuilder.append(" AND {Product.pk} IN ({{").append(filterQuery).append("}}) ");

    // Group the result to count the values
    stringBuilder.append("GROUP BY {pf.classificationAttributeAssignment} ");
    if (useToCharForClob) {
      stringBuilder.append(", to_char({pf.stringValue})");
    } else {
      stringBuilder.append(", {pf.stringValue}");
    }
    stringBuilder.append(", {pf.unit}");

    // Create the actual flexible search query
    final FlexibleSearchQuery query = new FlexibleSearchQuery(stringBuilder.toString());
    query.setResultClassList(Arrays.asList(Item.class, String.class, Item.class, Long.class));
    query.addQueryParameter("assignments", assignments);
    query.addQueryParameters(filterParams);
    final SearchResult<List<Object>> result = search(query);
    final List<PossibleAttributeValue> possibleAttributeValues =
        new ArrayList<PossibleAttributeValue>(result.getCount());
    for (final List<Object> row : result.getResult()) {
      if (row.size() != 4) {
        throw new IllegalStateException("Invalid size of row: " + row.size());
      }
      final ClassAttributeAssignmentModel assignment = (ClassAttributeAssignmentModel) row.get(0);
      final String stringValue = (String) row.get(1);
      final Object value = convertValue(assignment, stringValue);
      final ClassificationAttributeUnitModel unit = (ClassificationAttributeUnitModel) row.get(2);
      final Long count = (Long) row.get(3);
      final PossibleAttributeValue possibleValue =
          new PossibleAttributeValue(assignment, value, unit, count);
      possibleAttributeValues.add(possibleValue);
    }
    return possibleAttributeValues;
  }
 @After
 public void setLegacyMode() {
   Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, legacyModeBackup);
 }
 @After
 public void unprepare() {
   // clear new tx cache isolation feature
   Config.setItemCacheIsolation(null);
 }