/**
   * Does basic sanity checks to make sure the constructor can be properly invoked by our generated
   * class.
   *
   * @param clazz
   */
  private void validateClass(Class<? extends DataSerializable> clazz) {
    Assert.isTrue(
        !Modifier.isAbstract(clazz.getModifiers()), "Cannot instantiate abstract classes");
    Assert.isTrue(Modifier.isPublic(clazz.getModifiers()), "Only public classes are supported");
    try {
      Constructor<? extends DataSerializable> ctor = clazz.getConstructor();
      Assert.isTrue(Modifier.isPublic(ctor.getModifiers()), "Default constructor is not public");

    } catch (Exception ex) {
      throw new IllegalArgumentException("Class " + clazz + " unsuitable for instantiation", ex);
    }
  }
示例#2
0
  // req: 11.7
  public Order createFromShoppingCart(ShoppingCart shoppingCart, Consumer consumer) {
    Assert.notNull(shoppingCart);
    Assert.isTrue(shoppingCart.getId() != 0);
    Assert.notNull(consumer);
    Assert.isTrue(consumer.getId() != 0);

    Order result;
    Collection<OrderItem> orderItems;
    double amount;

    result = this.create();

    // Adding OrderItems
    orderItems = orderItemService.createByShoppingCart(shoppingCart, result);
    result.setOrderItems(orderItems);

    // Calculate amount
    amount = this.amountCalculate(orderItems);
    result.setAmount(amount);

    // Adding Order to Consumer
    result.setConsumer(consumer);

    return result;
  }
示例#3
0
  /** Guarda la Order desde ShoppingCart. NO USAR. Usar desde ShoppingCartService.saveCheckOut. */
  public void saveFromShoppingCart(ShoppingCart shoppingCart, Order order) {
    Assert.notNull(shoppingCart);
    Assert.notNull(order);

    Collection<OrderItem> orderItems;
    double amount;

    // Check CreditCard
    Assert.isTrue(
        this.checkCreditcard(order.getCreditCard()), "order.commit.error.creditcard.date");

    // Adding OrderItems
    orderItems = orderItemService.createByShoppingCart(shoppingCart, order);
    order.setOrderItems(orderItems);

    // Calculate amount
    amount = this.amountCalculate(orderItems);
    Assert.isTrue(amount == order.getAmount(), "order.commit.AmountChanged");

    order = this.save(order);

    // Saving OrderItems
    orderItems = orderItemService.createByShoppingCart(shoppingCart, order);
    orderItemService.save(orderItems);
  }
  @Override
  public void upgradeInternal(
      ServerHttpRequest request,
      ServerHttpResponse response,
      String selectedProtocol,
      List<Extension> selectedExtensions,
      Endpoint endpoint)
      throws HandshakeFailureException {

    Assert.isTrue(request instanceof ServletServerHttpRequest);
    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

    Assert.isTrue(response instanceof ServletServerHttpResponse);
    HttpServletResponse servletResponse =
        ((ServletServerHttpResponse) response).getServletResponse();

    StringBuffer requestUrl = servletRequest.getRequestURL();
    String path = servletRequest.getRequestURI(); // shouldn't matter
    Map<String, String> pathParams = Collections.<String, String>emptyMap();

    ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint);
    endpointConfig.setSubprotocols(Arrays.asList(selectedProtocol));
    endpointConfig.setExtensions(selectedExtensions);

    try {
      getContainer(servletRequest)
          .doUpgrade(servletRequest, servletResponse, endpointConfig, pathParams);
    } catch (ServletException ex) {
      throw new HandshakeFailureException(
          "Servlet request failed to upgrade to WebSocket, uri=" + requestUrl, ex);
    } catch (IOException ex) {
      throw new HandshakeFailureException(
          "Response update failed during upgrade to WebSocket, uri=" + requestUrl, ex);
    }
  }
  /**
   * Handle text node during validation.
   *
   * @param received
   * @param source
   */
  private void doText(Node received, Node source) {
    if (log.isDebugEnabled()) {
      log.debug("Validating node value for element: " + received.getParentNode());
    }

    if (received.getNodeValue() != null) {
      Assert.isTrue(
          source.getNodeValue() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              null,
              received.getNodeValue().trim()));

      Assert.isTrue(
          received.getNodeValue().trim().equals(source.getNodeValue().trim()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              received.getNodeValue().trim()));
    } else {
      Assert.isTrue(
          source.getNodeValue() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              null));
    }

    if (log.isDebugEnabled()) {
      log.debug("Node value '" + received.getNodeValue().trim() + "': OK");
    }
  }
  private void doElementNamespaceValidation(Node received, Node source) {
    // validate element namespace
    if (log.isDebugEnabled()) {
      log.debug("Validating namespace for element: " + received.getLocalName());
    }

    if (received.getNamespaceURI() != null) {
      Assert.isTrue(
          source.getNamespaceURI() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Element namespace not equal for element '" + received.getLocalName() + "'",
              null,
              received.getNamespaceURI()));

      Assert.isTrue(
          received.getNamespaceURI().equals(source.getNamespaceURI()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Element namespace not equal for element '" + received.getLocalName() + "'",
              source.getNamespaceURI(),
              received.getNamespaceURI()));
    } else {
      Assert.isTrue(
          source.getNamespaceURI() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Element namespace not equal for element '" + received.getLocalName() + "'",
              source.getNamespaceURI(),
              null));
    }
  }
 /**
  * If you inject the decorated interface somewhere by interface type, then the decorator class
  * instance is injected If you inject the LongSingleChain_MyServiceInterface interface into the
  * decorator, then the delegate instance gets injected If you inject the
  * LongSingleChain_MyDelegate class into the decorator, then the delegate instance gets injected
  */
 @Test
 public void testDecoratorInterfaceInjection() {
   Assert.isTrue(decoratedInterface.getClass().equals(Simple_MyDecorator.class));
   Assert.isTrue(
       Simple_MyDelegate.class.isAssignableFrom(
           decoratedInterface.getDelegateInterface().getClass()));
 }
  protected Stack<Operation> handleEqualSizeStack(
      Operation jumpCondition, Stack<Operation> beforeStack, Stack<Operation> afterStack) {
    int size = beforeStack.size();
    int unequalItems = 0;
    for (int j = size - 1; j >= 0; j--) {
      logger.debug("CHK(PREV<->NEXT): " + beforeStack.get(j) + " <-> " + afterStack.get(j));
      if (!beforeStack.get(j).equals(afterStack.get(j))) {
        Assert.isTrue(j == size - 1); // allow only stack-top items to be unequal
        unequalItems++;
      }
    }

    logger.debug("Unequal items = " + unequalItems);

    // Handle only 1 unequal item
    Assert.isTrue(unequalItems == 1);

    // Handle only boolean operations
    if (!(beforeStack.peek() instanceof BooleanOperation)) {
      //			throw new IllegalArgumentException("Not boolean: "+beforeStack.peek());
      logger.error("Not boolean: " + beforeStack.peek());
    }
    if (!(afterStack.peek() instanceof BooleanOperation)) {
      //			throw new IllegalArgumentException("Not boolean: "+afterStack.peek());
      logger.error("Not boolean: " + afterStack.peek());
    }

    logger.debug("Try to simplify if condition...");
    /*

    condition = a
    before stack = b
    after stack = c
    a&&b || !a&&c

    */
    Stack<Operation> newExecutionStack = copyExecutionStack(afterStack);
    if (jumpCondition.equals(beforeStack.peek())) {
      // a&&a || !a&&c = a || !a&&c = a||c;
      logger.debug("Simplifying to OR");
      Operation nextStackValue = newExecutionStack.pop();
      newExecutionStack.push(new OrOperation(jumpCondition, nextStackValue));
    } else if (jumpCondition.equals(new NotOperation(beforeStack.peek()))) {
      // a&&!a || !a&&c = 0 || !a&&c = !a&&c
      logger.debug("Simplifying to AND");
      Operation nextStackValue = newExecutionStack.pop();
      newExecutionStack.push(
          AndOperation.createInstance(new NotOperation(jumpCondition), nextStackValue));
    } else {
      logger.debug("Simplifying to TERNARY");
      //			Operation op1 = AndOperation.createInstance(jumpCondition,beforeStack.peek());
      //			Operation op2 = AndOperation.createInstance(new
      // NotOperation(jumpCondition),newExecutionStack.pop());
      //			newExecutionStack.push(BranchOperation.createInstance(op1, op2));
      newExecutionStack.push(
          new TernaryOperation(jumpCondition, beforeStack.peek(), newExecutionStack.pop()));
    }

    return newExecutionStack;
  }
 @Override
 @Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.RuntimeException.class)
 public void autoApply(BizOrderExitApply waitApply) {
   Assert.notNull(waitApply, "waitApply must not null.");
   BusFinancePlanOrder order = busFinancePlanOrderService.getById(waitApply.getXsOrderId());
   Assert.notNull(order, "order must not null.");
   BusFinancePlan plan = busFinancePlanService.getById(waitApply.getFinanceplanId());
   Assert.notNull(plan, "plan must not null.");
   BusUser user = busUserService.queryUser(waitApply.getUserId());
   Assert.notNull(user, "user must not null.");
   // 订单状态必须是“TRANSFERING”
   Assert.isTrue(
       BusOrderStatus.TRANSFERING.equals(order.getOrderStatus()),
       "order must is [TRANSFERING] status");
   // 理财计划配置必须是“NONFIXED_FINANCEPLAN” or “MOBILE_FINANCEPLAN” or
   // “XS_FINANCEPLAN” or “PROFITS_ADVANCE_FINANCEPLAN”
   Assert.isTrue(
       BusFinancePlanConfigType.ORDER_EXIT_NEED_APPLY_FINANCEPLANS.contains(
           plan.getFinancePlanConfigType()),
       "finance plan config type check error.");
   bizOrderExitApplyService.updateOrderExitApply(
       waitApply.getId(),
       waitApply.getVersion(),
       "system",
       new Date(),
       "system task auto apply",
       OrderExitApplyStatus.APPLY_SUCCESS);
 }
  /**
   * Specify the number of concurrent consumers to create. Default is 1.
   *
   * <p>Raising the number of concurrent consumers is recommended in order to scale the consumption
   * of messages coming in from a queue. However, note that any ordering guarantees are lost once
   * multiple consumers are registered. In general, stick with 1 consumer for low-volume queues.
   * Cannot be less than {@link #maxConcurrentConsumers} (if set).
   *
   * @see #setMaxConcurrentConsumers(int)
   * @param concurrentConsumers the minimum number of consumers to create.
   */
  public void setConcurrentConsumers(final int concurrentConsumers) {
    Assert.isTrue(concurrentConsumers > 0, "'concurrentConsumers' value must be at least 1 (one)");
    if (this.maxConcurrentConsumers != null) {
      Assert.isTrue(
          concurrentConsumers <= this.maxConcurrentConsumers,
          "'concurrentConsumers' cannot be more than 'maxConcurrentConsumers'");
    }
    synchronized (consumersMonitor) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Changing consumers from " + this.concurrentConsumers + " to " + concurrentConsumers);
      }
      int delta = this.concurrentConsumers - concurrentConsumers;
      this.concurrentConsumers = concurrentConsumers;
      if (isActive() && this.consumers != null) {
        if (delta > 0) {
          Iterator<Entry<BlockingQueueConsumer, Boolean>> entryIterator =
              consumers.entrySet().iterator();
          while (entryIterator.hasNext() && delta > 0) {
            Entry<BlockingQueueConsumer, Boolean> entry = entryIterator.next();
            if (entry.getValue()) {
              BlockingQueueConsumer consumer = entry.getKey();
              consumer.setQuiesce(this.shutdownTimeout);
              this.consumers.put(consumer, false);
              delta--;
            }
          }

        } else {
          addAndStartConsumers(-delta);
        }
      }
    }
  }
  @SuppressWarnings("rawtypes")
  public static MetaClass getExpandoMetaClass(Class clazz) {
    MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
    Assert.isTrue(
        registry.getMetaClassCreationHandler() instanceof ExpandoMetaClassCreationHandle,
        "Grails requires an instance of [ExpandoMetaClassCreationHandle] to be set in Groovy's MetaClassRegistry! (current is : "
            + registry.getMetaClassCreationHandler()
            + ")");

    MetaClass mc = registry.getMetaClass(clazz);
    AdaptingMetaClass adapter = null;
    if (mc instanceof AdaptingMetaClass) {
      adapter = (AdaptingMetaClass) mc;
      mc = ((AdaptingMetaClass) mc).getAdaptee();
    }

    if (!(mc instanceof ExpandoMetaClass)) {
      // removes cached version
      registry.removeMetaClass(clazz);
      mc = registry.getMetaClass(clazz);
      if (adapter != null) {
        adapter.setAdaptee(mc);
      }
    }
    Assert.isTrue(
        mc instanceof ExpandoMetaClass,
        "BUG! Method must return an instance of [ExpandoMetaClass]!");
    return mc;
  }
示例#12
0
  public static UserAccount getPrincipal() {
    UserAccount result;
    SecurityContext context;
    Authentication authentication;
    Object principal;

    // If the asserts in this method fail, then you're
    // likely to have your Tomcat's working directory
    // corrupt. Please, clear your browser's cache, stop
    // Tomcat, update your Maven's project configuration,
    // clean your project, clean Tomcat's working directory,
    // republish your project, and start it over.

    context = SecurityContextHolder.getContext();
    Assert.notNull(context);
    authentication = context.getAuthentication();
    Assert.notNull(authentication);
    principal = authentication.getPrincipal();
    Assert.isTrue(principal instanceof UserAccount);
    result = (UserAccount) principal;
    Assert.notNull(result);
    Assert.isTrue(result.getId() != 0);

    return result;
  }
  @Transactional
  @Rollback(true)
  @Test
  public void testUpdateWidgetInstance()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    DefaultWidgetInstance defaultWidgetInstance = prepareData(objectMapper);

    Map<String, String> responsMap = uIService.createOrUpdateWidgetInstance(defaultWidgetInstance);
    Assert.isTrue(
        responsMap.get("widgetInstanceAction").equals("update"),
        "The response action should have been 'updated'");

    Canvas retrievedPerishableCanvas = uIService.getCanvasByName("Perishable Goods Canvas");
    List<DefaultWidgetInstance> retrievedDefaultWidgetInstances =
        retrievedPerishableCanvas.getWidgetInstanceList();

    DefaultWidgetInstance retrievedRefaultWidgetInstance = retrievedDefaultWidgetInstances.get(0);
    Assert.isTrue(
        objectMapper
            .writeValueAsString(actualViewConfig)
            .equals(retrievedRefaultWidgetInstance.getActualViewConfig()));
  }
    @Override
    public void setArguments(Object[] arguments) {
      Assert.isTrue(arguments.length == 1, "An 'inRange' query requires exactly 1 argument");
      Assert.isTrue(arguments[0] instanceof Range, "An 'inRange' query requires a Range argument");

      super.setArguments(arguments);
    }
 @Override
 public final void onInit() throws Exception {
   Assert.isTrue(
       this.getBeanFactory() instanceof ListableBeanFactory, "A ListableBeanFactory is required.");
   Map<String, MBeanExporter> exporters =
       BeanFactoryUtils.beansOfTypeIncludingAncestors(
           (ListableBeanFactory) this.getBeanFactory(), MBeanExporter.class);
   Assert.isTrue(exporters.size() > 0, "No MBeanExporter is available in the current context.");
   MBeanExporter exporter = null;
   for (MBeanExporter exp : exporters.values()) {
     exporter = exp;
     if (exporter instanceof IntegrationMBeanExporter) {
       break;
     }
   }
   if (this.notificationMapper == null) {
     this.notificationMapper =
         new DefaultNotificationMapper(this.objectName, this.defaultNotificationType);
   }
   exporter.registerManagedResource(this.delegate, this.objectName);
   if (this.logger.isInfoEnabled()) {
     this.logger.info(
         "Registered JMX notification publisher as MBean with ObjectName: " + this.objectName);
   }
 }
  /**
   * Get the CompassQuery.SortDirection for the given property and optional order/direction Map
   * entry
   *
   * @param property either CompassQuery.SortImplicitType.SCORE or a class property name (String)
   * @param options a Map containg
   * @return
   */
  public CompassQuery.SortDirection getSortDirection(Object property, Map options) {
    Assert.notNull(property, "sort property cannot be null");
    Assert.notNull(options, "options Map cannot be null");
    if (!options.containsKey(ORDER) && !options.containsKey(DIRECTION)) {
      return CompassQuery.SortDirection.AUTO;
    }

    Assert.isTrue(
        (options.containsKey(ORDER) && !options.containsKey(DIRECTION))
            || (!options.containsKey(ORDER) && options.containsKey(DIRECTION)),
        "Either specify a sort '" + ORDER + "' or '" + DIRECTION + "' or neither but not both");
    String value = (String) options.get(DIRECTION);
    if (value == null) {
      value = (String) options.get(ORDER);
    }
    Assert.isTrue(
        VALID_SORT_DIRECTION_VALUES.contains(value),
        "The sort order/direction '" + value + "' is not a valid value");
    return property.equals(CompassQuery.SortImplicitType.SCORE)
        ? value.equals("asc") || value.equals("reverse")
            ? CompassQuery.SortDirection.REVERSE
            : CompassQuery.SortDirection.AUTO
        : value.equals("asc") || value.equals("auto")
            ? CompassQuery.SortDirection.AUTO
            : CompassQuery.SortDirection.REVERSE;
  }
  @Test
  public void testOrderOfReceipts() throws Exception {
    queueNameList.add("aQueueName");

    this.lucasBroadCastService.sendMessage("aQueueName", "aBindKey", "String1");
    this.lucasBroadCastService.sendMessage("aQueueName", "aBindKey", "String2");
    this.lucasBroadCastService.sendMessage("aQueueName", "aBindKey", "String3");

    String s =
        this.lucasMessageBroadcastClientService.receiveFirstMessage(
            "aQueueName", "aBindKey", 1000L);
    LOG.info("Retrieved: " + s);
    Assert.notNull(s, "retrieved string should not be null");
    Assert.isTrue(
        StringUtils.equals("String1", s),
        "The returned values do not match. \nSent: " + "String1" + "\nRecd: " + s);

    s =
        this.lucasMessageBroadcastClientService.receiveFirstMessage(
            "aQueueName", "aBindKey", 1000L);
    Assert.notNull(s, "retrieved string should not be null");
    Assert.isTrue(
        StringUtils.equals("String2", s),
        "The returned values do not match. \nSent: " + "String2" + "\nRecd: " + s);

    s =
        this.lucasMessageBroadcastClientService.receiveFirstMessage(
            "aQueueName", "aBindKey", 1000L);
    Assert.notNull(s, "retrieved string should not be null");
    Assert.isTrue(
        StringUtils.equals("String3", s),
        "The returned values do not match. \nSent: " + "String3" + "\nRecd: " + s);
  }
  @Ignore
  @Test
  public void testGetSearchUserGridWidgetDefinitionWithoutAuthentication()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    AbstractLicensableWidget searchUserGridWidget =
        uIService.getWidgetDefinition(SearchUserGridWidgetName);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(null);
    Assert.notNull(searchUserGridWidget);
    Assert.notNull(searchUserGridWidget.getDataURL());

    Assert.isTrue(
        searchUserGridWidget.getActionConfig().getActionConfig().size() == 2,
        "Search user grid widget action config does not have expected # of permissions values");

    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("delete-user"))
            == Boolean.FALSE,
        "Search user grid widget action config does not have delete-user permission false");

    Assert.isTrue(
        searchUserGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("disable-user"))
            == Boolean.FALSE,
        "Search user grid widget action config does not have disable-user permission false");
  }
示例#19
0
  public void delete(Announcement announcement) {
    assert announcement != null;
    assert announcement.getId() != 0;

    Assert.isTrue(announcementRepository.exists(announcement.getId()));
    Assert.isTrue(!registrationService.existsRegistrationForAnnouncement(announcement));

    announcementRepository.delete(announcement);
  }
 @Then(
     "^the system stores the new feature request \"([^\"]*)\" for the head version \"([^\"]*)\" of \"([^\"]*)\" with solution \"([^\"]*)\"$")
 public void the_system_stores_the_new_feature_request_for_the_head_version_of_with_solution(
     String arg1, String arg2, String arg3, String arg4) throws Throwable {
   Request r = reqRepo.findByProblem(arg1);
   Assert.isTrue(r.getProblem().equals(arg1));
   Assert.isTrue(r.getVersion().getVersion().equals(arg2));
   Assert.isTrue(r.getSolution().equals(arg4));
 }
    @Override
    public void setArguments(Object[] arguments) {
      Assert.isTrue(arguments.length > 1, "A 'between' query requires at least two arguments");
      Assert.isTrue(
          arguments[0] instanceof Comparable && arguments[1] instanceof Comparable,
          "A 'between' query requires that both arguments are comparable");

      super.setArguments(arguments);
    }
  private void validatePaths(
      String path, ResourcePatternResolver resourceLoader, boolean shouldExist) throws IOException {
    Resource res = resourceLoader.getResource(path);

    if (shouldExist) {
      Assert.isTrue(res.exists(), "The input path [" + path + "] does not exist");
    } else {
      Assert.isTrue(!res.exists(), "The output path [" + path + "] already exists");
    }
  }
示例#23
0
  public void saveToEdit(Gym gym) {
    Assert.notNull(gym);
    Assert.isTrue(actorService.checkAuthority("ADMIN"), "Only an admin can save gyms");

    Collection<ServiceEntity> services;
    Collection<ServiceEntity> servicesPreSave;
    ServiceEntity fitness;

    servicesPreSave = new ArrayList<ServiceEntity>();

    fitness = serviceService.findOneByName("Fitness");
    if (gym.getServices() == null) {
      gym.setServices(new ArrayList<ServiceEntity>());
    }
    gym.addService(fitness);

    if (gym.getId() != 0) {
      Gym gymPreSave;
      Collection<Booking> bookings;
      Collection<FeePayment> feePayments;
      Collection<Comment> comments;

      gymPreSave = gymRepository.findOne(gym.getId());

      bookings = gymPreSave.getBookings();
      feePayments = gymPreSave.getFeePayments();
      comments = gymPreSave.getComments();
      servicesPreSave = new ArrayList<ServiceEntity>(gymPreSave.getServices());

      Assert.isTrue(
          gym.getBookings().containsAll(bookings) && gym.getBookings().size() == bookings.size());
      Assert.isTrue(
          gym.getFeePayments().containsAll(feePayments)
              && gym.getFeePayments().size() == feePayments.size());
      Assert.isTrue(
          gym.getComments().containsAll(comments) && gym.getComments().size() == comments.size());
    }
    services = gym.getServices();

    gym = this.save(gym);

    for (ServiceEntity service : services) {
      if (!servicesPreSave.contains(service)) {
        service.addGym(gym);
        serviceService.save(service);
      }
    }

    for (ServiceEntity service : servicesPreSave) {
      if (!services.contains(service)) {
        service.removeGym(gym);
        serviceService.save(service);
      }
    }
  }
示例#24
0
  // ref: 18.3
  public void assignToClerkManual(Clerk clerk, Order order) {
    Assert.notNull(clerk);
    Assert.isTrue(clerk.getId() != 0);
    Assert.notNull(order);
    Assert.isTrue(order.getId() != 0);
    Assert.isNull(order.getClerk());

    order.setClerk(clerk);

    this.save(order);
  }
  protected final String getVenueNameFromNode(final Node mainNode) {
    final NodeList mainTrChildren = mainNode.getChildNodes();
    Assert.isTrue(mainTrChildren.getLength() == 2);

    final Node h3Node = mainTrChildren.item(1);
    final NodeList h3Children = h3Node.getChildNodes();
    Assert.isTrue(h3Children.getLength() == 3);
    final Node aNodeForName = h3Children.item(1);

    return aNodeForName.getTextContent();
  }
示例#26
0
  public void save(Announcement announcement) {
    assert announcement != null;

    Date currentMoment;

    currentMoment = new Date();
    Assert.isTrue(announcement.getCertification().getExtinctionDate().after(currentMoment));
    Assert.isTrue(announcement.getCertification().getExams().contains(announcement.getExam()));

    announcementRepository.save(announcement);
  }
 @Transactional
 @Rollback(true)
 @Test
 public void testSaveEventToUpdate() {
   Event eventTest = eventService.getEventById(NUMBER_ONE);
   Assert.isTrue(
       eventTest.getEventDescription().equals("Import user details to the lucas system"));
   eventTest.setEventDescription("Test Description");
   eventService.saveEvent(eventTest);
   Event eventTestNew = eventService.getEventById(NUMBER_ONE);
   Assert.isTrue(eventTestNew.getEventDescription().equals("Test Description"));
 }
示例#28
0
  // req: 24.2
  public void deleteMessageFromFolder(Message message, Folder folder) {
    Assert.notNull(message);
    Assert.isTrue(message.getId() != 0);
    Assert.notNull(folder);
    Assert.isTrue(folder.getId() != 0);

    Assert.isTrue(
        folder.getActor().equals(actorService.findByPrincipal()),
        "Only the owner of the folder can delete a message");

    folderService.removeMessage(folder, message);
  }
  private final String getVenueAddressFromNode(final Node mainNode) {
    final NodeList mainDivChildren = mainNode.getChildNodes();
    Assert.isTrue(mainDivChildren.getLength() == 4);

    final Node tdNodeForName = mainDivChildren.item(1);
    final NodeList tdChildren = tdNodeForName.getChildNodes();
    Assert.isTrue(tdChildren.getLength() == 1);

    final Node textNodeForName = tdChildren.item(0);

    return textNodeForName.getTextContent();
  }
  @Test
  @Transactional(readOnly = true)
  public void testGetEventGridWidgetDefinitionWithAuthentication()
      throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
          SecurityException, NoSuchMethodException, IOException {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(auth);
    AbstractLicensableWidget eventGridWidget = uIService.getWidgetDefinition(EventGridWidgetName);
    Assert.notNull(eventGridWidget);
    Assert.isTrue(
        eventGridWidget.getActionConfig().getActionConfig().size() == 2,
        "Event grid widget action config does not have expected # of permissions values");
    Assert.isTrue(
        eventGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("create-event"))
            == Boolean.TRUE,
        "Event grid widget action config does not have create-event permission true");
    Assert.isTrue(
        eventGridWidget
                .getActionConfig()
                .getActionConfig()
                .get("widget-actions")
                .get(new Permission("edit-event"))
            == Boolean.TRUE,
        "Event grid widget action config does not have edit-event permission true");

    // Assertions for AutoRefreshConfig
    JSONObject defaultViewConfigJSON = new JSONObject(eventGridWidget.getDefaultViewConfig());
    Assert.isTrue(
        defaultViewConfigJSON.has("autoRefreshConfig"),
        "Could not find property 'AutoRefreshConfig'");

    JSONObject autoRefreshConfigJSON =
        new JSONObject(defaultViewConfigJSON.get("autoRefreshConfig").toString());
    Assert.isTrue(
        autoRefreshConfigJSON.has("globalOverride"), "Could not find property 'globalOverride'");
    Assert.isTrue(autoRefreshConfigJSON.has("enabled"), "Could not find property 'enabled'");
    Assert.isTrue(autoRefreshConfigJSON.has("interval"), "Could not find property 'interval'");

    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("globalOverride") == false,
        "Incorrect value for property 'globalOverride'");
    Assert.isTrue(
        autoRefreshConfigJSON.getBoolean("enabled") == true,
        "Incorrect value for property 'enabled'");
    Assert.isTrue(
        autoRefreshConfigJSON.getInt("interval") == 120, "Incorrect value for property 'interval'");
  }