Beispiel #1
0
  public Term add(String name, String shortDescription, String description) {
    name = name.replace("\"", "").replace("«", "").replace("»", "").trim();
    name =
        WordUtils.capitalize(
            name,
            new char[] {
              '@'
            }); // Делаем первую букву большой, @ - знак который не появляеться в названии, чтобы
    // поднялась только первая буква всей фразы
    Term term = termDao.getByName(name);
    if (term == null) {
      term = termDao.save(new Term(name, shortDescription, description));
      if (shortDescription != null)
        term.setTaggedShortDescription(termsMarker.mark(shortDescription));
      if (description != null) term.setTaggedDescription(termsMarker.mark(description));
      String termName = term.getName();
      log.info("Added: " + termName);
      if (TermUtils.isComposite(termName)) {
        String target = TermUtils.getNonCosmicCodePart(termName);
        if (target != null) {
          findAliases(term, target, termName.replace(target, ""));
        }
      } else if (!TermUtils.isCosmicCode(termName)) {
        findAliases(term, termName, "");
      }
      publisher.publishEvent(new NewTermEvent(term));
    } else {
      String oldShortDescription = null;
      if (shortDescription != null && !shortDescription.isEmpty()) {
        oldShortDescription = term.getShortDescription();
        term.setShortDescription(shortDescription);
        term.setTaggedShortDescription(termsMarker.mark(shortDescription));
      }
      String oldDescription = null;
      if (description != null && !description.isEmpty()) {
        oldDescription = term.getDescription();
        term.setDescription(description);
        term.setTaggedDescription(termsMarker.mark(description));
      }
      termDao.save(term);
      publisher.publishEvent(new TermUpdatedEvent(term, oldShortDescription, oldDescription));
    }

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                termsMap.reload();
              }
            })
        .start();

    return term;
  }
 private void publishNoConnectionEvent(
     MessageHandlingException messageHandlingException, String connectionId) {
   AbstractConnectionFactory cf =
       this.serverConnectionFactory != null
           ? this.serverConnectionFactory
           : this.clientConnectionFactory;
   ApplicationEventPublisher applicationEventPublisher = cf.getApplicationEventPublisher();
   if (applicationEventPublisher != null) {
     applicationEventPublisher.publishEvent(
         new TcpConnectionFailedCorrelationEvent(this, connectionId, messageHandlingException));
   }
 }
Beispiel #3
0
  @Async
  @Override
  public void enviarMailCambioContraseña(String nombre, String email, String token, Locale locale) {
    try {
      final Context ctx = new Context(locale);
      ctx.setVariable("nombre", nombre);
      ctx.setVariable("token", token);
      ctx.setVariable("lenguaje", locale.getLanguage());

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
      message.setSubject(messageSource.getMessage("reset.email.titulo", null, locale));
      message.setFrom("*****@*****.**", "Cudú");
      message.setTo(email);

      final String htmlContent = templateEngine.process("resetpassword", ctx);
      message.setText(htmlContent, true);
      mailSender.send(mimeMessage);
    } catch (Exception e) {
      String correlationId = UUID.randomUUID().toString();
      Marker marker = MarkerFactory.getMarker("ENVIO_EMAIL");
      logger.error(
          marker, "Error enviando email. Token: " + token + ", CorrelationId: " + correlationId, e);
      eventPublisher.publishEvent(new EmailErrorApplicationEvent(email, correlationId));
    }
  }
 private void notifyApprovalToWebSocket(
     int noticeId, String createdBy, String dongName, String title) throws OperationalException {
   WebSocketEvent event =
       new WebSocketEvent(
           this, noticeId, createdBy, title, WebSocketEventType.NOTICEAPPROVAL.name(), dongName);
   publisher.publishEvent(event);
 }
 private void notifyApprovedAllToWebSocket(String approvedBy, String dongName, String title)
     throws OperationalException {
   WebSocketEvent event =
       new WebSocketEvent(
           this, 0, approvedBy, title, WebSocketEventType.NOTICEAPPROVEDALL.name(), dongName);
   publisher.publishEvent(event);
 }
 private void notifyRejectedToWebSocket(
     int noticeId, String rejectedBy, String dongName, String title) throws OperationalException {
   WebSocketEvent event =
       new WebSocketEvent(
           this, noticeId, rejectedBy, title, WebSocketEventType.NOTICEREJECTED.name(), dongName);
   publisher.publishEvent(event);
 }
Beispiel #7
0
  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  @ResponseBody
  public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
    final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));

    eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
    return resourceById;
  }
Beispiel #8
0
  //    @Scheduled(cron="0 0 19 * * ?") // это 3 по Москве, так как время сервера в EST, таблица
  // соответствия
  // http://www.worldtimebuddy.com/?qm=1&lid=5,703448,524901&h=5&date=2014-12-28&sln=19-20
  public void update() throws IOException {
    long start = System.currentTimeMillis();

    termService.reload();
    updateCacheSearchResult();

    long end = System.currentTimeMillis();
    final String duration = DurationFormatUtils.formatDuration(end - start, "HH:mm:ss");
    eventPublisher.publishEvent(new SimplePushEvent("Кеш обновлён за " + duration));
  }
Beispiel #9
0
  protected final void createInternal(
      final T resource, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
    RestPreconditions.checkRequestElementNotNull(resource);
    RestPreconditions.checkRequestState(resource.getId() == null);
    try {
      getService().create(resource);
    }
    // this is so that the service layer can MANUALLY throw exceptions that get handled by the
    // exception translation mechanism
    catch (final IllegalStateException illegalState) {
      logger.error(
          "IllegalArgumentException on create operation for: "
              + resource.getClass().getSimpleName());
      logger.warn(
          "IllegalArgumentException on create operation for: "
              + resource.getClass().getSimpleName(),
          illegalState);
      throw new ConflictException(illegalState);
    } catch (final DataIntegrityViolationException ex) { // on unique constraint
      logger.error(
          "DataIntegrityViolationException on create operation for: "
              + resource.getClass().getSimpleName());
      logger.warn(
          "DataIntegrityViolationException on create operation for: "
              + resource.getClass().getSimpleName(),
          ex);
      throw new ConflictException(ex);
    } catch (
        final InvalidDataAccessApiUsageException
            dataEx) { // on saving a new Resource that also contains new/unsaved entities
      logger.error(
          "InvalidDataAccessApiUsageException on create operation for: "
              + resource.getClass().getSimpleName());
      logger.warn(
          "InvalidDataAccessApiUsageException on create operation for: "
              + resource.getClass().getSimpleName(),
          dataEx);
      throw new ConflictException(dataEx);
    } catch (final DataAccessException dataEx) {
      logger.error(
          "Generic DataAccessException on create operation for: "
              + resource.getClass().getSimpleName());
      logger.warn(
          "Generic DataAccessException on create operation for: "
              + resource.getClass().getSimpleName(),
          dataEx);
      throw new ConflictException(dataEx);
    }

    // - note: mind the autoboxing and potential NPE when the resource has null id at this point
    // (likely when working with DTOs)
    eventPublisher.publishEvent(
        new ResourceCreatedEvent<T>(clazz, uriBuilder, response, resource.getId()));
  }
  @RequestMapping(value = "/user/registration", method = RequestMethod.POST)
  @ResponseBody
  public GenericResponse registerUserAccount(
      @Valid final UserDto accountDto, final HttpServletRequest request) {
    LOGGER.debug("Registering user account with information: {}", accountDto);

    final User registered = userService.registerNewUserAccount(accountDto);
    eventPublisher.publishEvent(
        new OnRegistrationCompleteEvent(registered, request.getLocale(), getAppUrl(request)));
    return new GenericResponse("success");
  }
Beispiel #11
0
  @RequestMapping(method = RequestMethod.POST)
  @ResponseStatus(HttpStatus.CREATED)
  @ResponseBody
  public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
    Preconditions.checkNotNull(resource);
    Foo foo = service.create(resource);
    final Long idOfCreatedResource = foo.getId();

    eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));

    return foo;
  }
Beispiel #12
0
 @Override
 public void draw() {
   System.out.println(
       this.messageSource.getMessage("drawing.circle", null, "Default Drawing Message", null));
   System.out.println(
       this.messageSource.getMessage(
           "drawing.point",
           new Object[] {center.getX(), center.getY()},
           "Default Point Message",
           null));
   DrawEvent drawEvent = new DrawEvent(this);
   publisher.publishEvent(drawEvent);
 }
  @Override
  public void onApplicationEvent(DeviceErrorMsgEvent event) {
    String deviceId = event.getDeviceId();
    String status = null;
    String currentStatus = null;
    try {
      String errorType = event.getErrorType();
      LOGGER.debug(
          "Starting to update device error to " + errorType + " for the device " + deviceId);
      switch (errorType) {
        case "INTERNAL_ERROR":
          status = DeviceStatus.INTERNALERROR.name();
          currentStatus = DeviceState.INTERNALERROR.name();
          break;
        case "EXTERNAL_ERROR":
          status = DeviceStatus.PARKINGLOCKERROR.name();
          currentStatus = DeviceState.PARKINGLOCKERROR.name();
          break;
        case "BREAK_DOWN":
          status = DeviceStatus.LOSSOFCOMMUNICATION.name();
          currentStatus = DeviceState.LOSSOFCOMMUNICATION.name();
          break;
        default:
          break;
      }

      deviceDao.updateError(deviceId, status, currentStatus);
      Device device = deviceDao.findByDeviceId(deviceId);
      WebSocketEvent errorEvent =
          new WebSocketEvent(
              this,
              deviceId,
              null,
              event.getDongName(),
              device.getSpotId(),
              status,
              WebSocketEventType.DEVICEERROR.name());
      publisher.publishEvent(errorEvent);
      sendSmsToDongOperators(
          device.getDongName(), device.getSpotId(), device.getDeviceId(), currentStatus);
    } catch (OperationalException e) {
      LOGGER.error(
          "Exception "
              + e.getMessage()
              + " while updating error to "
              + currentStatus
              + " from MQTT for the device "
              + event.getDeviceId(),
          e);
    }
  }
Beispiel #14
0
  protected final T findOneInternal(
      final Long id, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
    T resource = null;
    try {
      resource = RestPreconditions.checkNotNull(getService().findOne(id));
    } catch (final InvalidDataAccessApiUsageException ex) {
      logger.error("InvalidDataAccessApiUsageException on find operation");
      logger.warn("InvalidDataAccessApiUsageException on find operation", ex);
      throw new ConflictException(ex);
    }

    eventPublisher.publishEvent(new SingleResourceRetrievedEvent<T>(clazz, uriBuilder, response));

    return resource;
  }
Beispiel #15
0
  @RequestMapping(
      params = {"page", "size"},
      method = RequestMethod.GET)
  @ResponseBody
  public List<Foo> findPaginated(
      @RequestParam("page") final int page,
      @RequestParam("size") final int size,
      final UriComponentsBuilder uriBuilder,
      final HttpServletResponse response) {
    final Page<Foo> resultPage = service.findPaginated(page, size);
    if (page > resultPage.getTotalPages()) {
      throw new MyResourceNotFoundException();
    }
    eventPublisher.publishEvent(
        new PaginatedResultsRetrievedEvent<Foo>(
            Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));

    return resultPage.getContent();
  }
Beispiel #16
0
  protected final List<T> findPaginatedInternal(
      final int page,
      final int size,
      final String sortBy,
      final UriComponentsBuilder uriBuilder,
      final HttpServletResponse response) {
    Page<T> resultPage = null;
    try {
      resultPage = getService().findPaginated(page, size, sortBy);
    } catch (final InvalidDataAccessApiUsageException apiEx) {
      logger.error("InvalidDataAccessApiUsageException on find operation");
      logger.warn("InvalidDataAccessApiUsageException on find operation", apiEx);
      throw new BadRequestException(apiEx);
    }

    if (page > resultPage.getTotalPages()) {
      throw new ResourceNotFoundException();
    }
    eventPublisher.publishEvent(
        new PaginatedResultsRetrievedEvent<T>(
            clazz, uriBuilder, response, page, resultPage.getTotalPages(), size));

    return Lists.newArrayList(resultPage.getContent());
  }
 private void publish(ApplicationEvent event) {
   if (eventPublisher != null) {
     eventPublisher.publishEvent(event);
   }
 }
 @Test(expected = RuntimeException.class)
 public void testException() {
   ErrorEvent event = new ErrorEvent();
   publisher.publishEvent(event.message("Error"));
 }
 @Test
 public void testChain() {
   ChainEvent event = new ChainEvent();
   publisher.publishEvent(event.message("Chain"));
   assertThat(3, equalTo(event.getCount()));
 }
Beispiel #20
0
 public void beforePublish() {
   BeforeInsertFilmEvent be = new BeforeInsertFilmEvent(this);
   publisher.publishEvent(be);
 }
Beispiel #21
0
 public void afterPublish() {
   AfterInsertFilmEvent ae = new AfterInsertFilmEvent(this);
   publisher.publishEvent(ae);
 }
 @AfterReturning(value = "entityCreationMethods()", returning = "entity")
 public void logMethodCall(JoinPoint jp, Object entity) throws Throwable {
   eventPublisher.publishEvent(new FooCreationEvent(entity));
 }
 @Override
 public void onApplicationEvent(ContextRefreshedEvent event) {
   eventPublisher.publishEvent(new PluginsLoadedEvent(this, pluginRegistry));
 }
 public void publish(ApplicationEvent event) {
   if (publisher != null) {
     publisher.publishEvent(event);
   }
 }
 public void sendEmail(String subject, String content) {
   EmailEvent event = new EmailEvent(this, subject, content);
   publisher.publishEvent(event);
 }
 public void publish() {
   CustomEvent ce = new CustomEvent(this);
   publisher.publishEvent(ce);
 }
 public void publish() {
   RegistrationFinishedEvent rfe = new RegistrationFinishedEvent(this);
   publisher.publishEvent(rfe);
 }
  @Override
  public void process(WebRequest request) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Customer customer = null;
    if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) {
      String userName = authentication.getName();
      customer =
          (Customer) request.getAttribute(customerRequestAttributeName, WebRequest.SCOPE_REQUEST);
      if (userName != null && (customer == null || !userName.equals(customer.getUsername()))) {
        // can only get here if the authenticated user does not match the user in session
        customer = customerService.readCustomerByUsername(userName);
        if (logger.isDebugEnabled() && customer != null) {
          logger.debug("Customer found by username " + userName);
        }
      }
      if (customer != null) {
        ApplicationEvent lastPublishedEvent =
            (ApplicationEvent)
                request.getAttribute(
                    LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, WebRequest.SCOPE_REQUEST);
        if (authentication instanceof RememberMeAuthenticationToken) {
          // set transient property of customer
          customer.setCookied(true);
          boolean publishRememberMeEvent = true;
          if (lastPublishedEvent != null
              && lastPublishedEvent instanceof CustomerAuthenticatedFromCookieEvent) {
            CustomerAuthenticatedFromCookieEvent cookieEvent =
                (CustomerAuthenticatedFromCookieEvent) lastPublishedEvent;
            if (userName.equals(cookieEvent.getCustomer().getUsername())) {
              publishRememberMeEvent = false;
            }
          }
          if (publishRememberMeEvent) {
            CustomerAuthenticatedFromCookieEvent cookieEvent =
                new CustomerAuthenticatedFromCookieEvent(customer, this.getClass().getName());
            eventPublisher.publishEvent(cookieEvent);
            request.setAttribute(
                LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME,
                cookieEvent,
                WebRequest.SCOPE_REQUEST);
          }
        } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
          customer.setLoggedIn(true);
          boolean publishLoggedInEvent = true;
          if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerLoggedInEvent) {
            CustomerLoggedInEvent loggedInEvent = (CustomerLoggedInEvent) lastPublishedEvent;
            if (userName.equals(loggedInEvent.getCustomer().getUsername())) {
              publishLoggedInEvent = false;
            }
          }
          if (publishLoggedInEvent) {
            CustomerLoggedInEvent loggedInEvent =
                new CustomerLoggedInEvent(customer, this.getClass().getName());
            eventPublisher.publishEvent(loggedInEvent);
            request.setAttribute(
                LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME,
                loggedInEvent,
                WebRequest.SCOPE_REQUEST);
          }
        } else {
          customer = resolveAuthenticatedCustomer(authentication);
        }
      }
    }

    if (customer == null) {
      // This is an anonymous customer.
      // TODO: Handle a custom cookie (different than remember me) that is just for anonymous users.
      // This can be used to remember their cart from a previous visit.
      // Cookie logic probably needs to be configurable - with TCS as the exception.

      customer = resolveAnonymousCustomer(request);
    }
    request.setAttribute(customerRequestAttributeName, customer, WebRequest.SCOPE_REQUEST);

    // Setup customer for content rule processing
    Map<String, Object> ruleMap =
        (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM, WebRequest.SCOPE_REQUEST);
    if (ruleMap == null) {
      ruleMap = new HashMap<String, Object>();
    }
    ruleMap.put("customer", customer);
    request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);
  }
Beispiel #29
0
 /**
  * Выполняет логирование и публикацию события задачи
  *
  * @param event событие задачи
  * @param needLogging флаг необходимости логирования
  */
 private void doPublishEvent(TaskEvent event, boolean needLogging) {
   if (needLogging) {
     LOG.info("Task {}", event.identity());
   }
   eventPublisher.publishEvent(event);
 }
 private void publishChange() {
   applicationEventPublisher.publishEvent(new ConfigurationModifiedEvent(hadoopConfiguration));
 }