Esempio n. 1
0
 // WARN Watch this code, see if we can do better, maybe leverage @UnitOfWorkRetry
 @Override
 public void run() {
   System.out.println("Running Schedule");
   Usecase usecase = UsecaseBuilder.newUsecase("ScheduleRunner");
   UnitOfWork uow = module.newUnitOfWork(usecase);
   try {
     Schedule schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity);
     Task task = schedule.task().get();
     schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity);
     try {
       schedule.taskStarting();
       task.run();
       schedule.taskCompletedSuccessfully();
     } catch (RuntimeException ex) {
       schedule.taskCompletedWithException(ex);
     }
     schedulerMixin.dispatchForExecution(schedule);
     uow.complete();
   } catch (UnitOfWorkCompletionException ex) {
   } finally {
     // What should we do if we can't manage the Running flag??
     if (uow.isOpen()) {
       uow.discard();
     }
   }
 }
      public Subject authenticate(Object credentials) {

        UnitOfWork unitOfWork =
            module
                .unitOfWorkFactory()
                .newUnitOfWork(UsecaseBuilder.newUsecase("Authenticate JMX user"));
        Subject subject = null;

        try {

          if (!(credentials instanceof String[])) {
            // Special case for null so we get a more informative message
            if (credentials == null) {
              throw new SecurityException("Credentials required");
            }
            throw new SecurityException("Credentials should be String[]");
          }

          final String[] aCredentials = (String[]) credentials;
          if (aCredentials.length != 2) {
            throw new SecurityException("Credentials should have 2 elements");
          }

          String username = aCredentials[0];
          String password = aCredentials[1];

          Authentication user = unitOfWork.get(Authentication.class, username);

          if (!user.login(password)) {
            throw new SecurityException("User/password combination not valid.");
          }

          if (((UserAuthentication.Data) user).isAdministrator()) {
            subject =
                new Subject(
                    true,
                    Collections.singleton(new JMXPrincipal(username)),
                    Collections.EMPTY_SET,
                    Collections.EMPTY_SET);
          } else {
            throw new SecurityException("Invalid credentials");
          }

          unitOfWork.complete();

        } catch (Throwable e) {
          unitOfWork.discard();
          throw new SecurityException(e);
        }

        return subject;
      }
Esempio n. 3
0
    @Override
    public synchronized T get() {
      if (configuration == null) {
        Usecase usecase = UsecaseBuilder.newUsecase("Configuration:" + me.identity().get());
        uow = module.newUnitOfWork(usecase);
        try {
          configuration = this.findConfigurationInstanceFor(me, uow);
        } catch (InstantiationException e) {
          throw new IllegalStateException(e);
        }
      }

      return configuration;
    }
Esempio n. 4
0
    @SuppressWarnings("unchecked")
    private <V> V initializeConfigurationInstance(
        ServiceComposite serviceComposite,
        UnitOfWork uow,
        ServiceDescriptor serviceModel,
        String identity)
        throws InstantiationException {
      Module module = api.moduleOf(serviceComposite);
      Usecase usecase = UsecaseBuilder.newUsecase("Configuration:" + me.identity().get());
      UnitOfWork buildUow = module.newUnitOfWork(usecase);

      EntityBuilder<V> configBuilder =
          buildUow.newEntityBuilder(serviceModel.<V>configurationType(), identity);

      // Check for defaults
      String s = identity + ".properties";
      Class<?> type = first(api.serviceDescriptorFor(serviceComposite).types());
      // Load defaults from classpath root if available
      if (type.getResource(s) == null && type.getResource("/" + s) != null) {
        s = "/" + s;
      }
      InputStream asStream = type.getResourceAsStream(s);
      if (asStream != null) {
        try {
          PropertyMapper.map(asStream, (Composite) configBuilder.instance());
        } catch (IOException e1) {
          InstantiationException exception =
              new InstantiationException("Could not read underlying Properties file.");
          exception.initCause(e1);
          throw exception;
        }
      }

      try {
        configBuilder.newInstance();
        buildUow.complete();

        // Try again
        return (V) findConfigurationInstanceFor(serviceComposite, uow);
      } catch (Exception e1) {
        InstantiationException ex =
            new InstantiationException(
                "Could not instantiate configuration, and no Properties file was found ("
                    + s
                    + ")");
        ex.initCause(e1);
        throw ex;
      }
    }
Esempio n. 5
0
  @Test
  public void planActivitiesTest() throws Exception {
    UnitOfWork uow = assembler.unitOfWorkFactory().newUnitOfWork(UsecaseBuilder.newUsecase("Test"));

    try {
      ProjectData project = uow.get(ProjectData.class, PROJECT);

      new FrontloadContext(project).frontloadNetworkFrom(1); // try 2

      uow.complete();
    } catch (Exception e) {
      uow.discard();
      throw e;
    }
  }
Esempio n. 6
0
  private void printBalances() {
    UnitOfWork uow = module.newUnitOfWork(UsecaseBuilder.newUsecase("Print balances"));

    try {
      System.out.println(
          SAVINGS_ACCOUNT_ID + ":" + uow.get(BalanceData.class, SAVINGS_ACCOUNT_ID).getBalance());
      System.out.println(
          CHECKING_ACCOUNT_ID + ":" + uow.get(BalanceData.class, CHECKING_ACCOUNT_ID).getBalance());
      System.out.println(
          CREDITOR_ID1 + ":" + uow.get(BalanceData.class, CREDITOR_ID1).getBalance());
      System.out.println(
          CREDITOR_ID2 + ":" + uow.get(BalanceData.class, CREDITOR_ID2).getBalance());
    } finally {
      uow.discard();
    }
  }
Esempio n. 7
0
  @Test(expected = IllegalArgumentException.class)
  public void transferTwiceOfMoneyFromSavingsToChecking() throws Exception {
    UnitOfWork uow =
        module.newUnitOfWork(UsecaseBuilder.newUsecase("Transfer from savings to checking"));

    try {
      // Select source and destination
      BalanceData source = uow.get(BalanceData.class, SAVINGS_ACCOUNT_ID);
      BalanceData destination = uow.get(BalanceData.class, CHECKING_ACCOUNT_ID);

      // Instantiate context and execute enactments with that context
      TransferMoneyContext2 context =
          module.newTransient(TransferMoneyContext2.class).bind(source, destination);

      // Query for double the balance
      final Integer amountToTransfer = context.availableFunds() * 2;

      // Transfer from savings to checking
      context.transfer(amountToTransfer);
    } finally {
      uow.discard();
    }
  }
      public void receivedEmail(ApplicationEvent event, EmailValue email) {
        UnitOfWork uow =
            module
                .unitOfWorkFactory()
                .newUnitOfWork(UsecaseBuilder.newUsecase("Receive email in conversation"));

        try {
          String references = email.headers().get().get("References");

          if (hasStreamflowReference(references)) {
            // This is a response - handle it!

            List<String> refs =
                (List<String>)
                    Iterables.addAll(
                        (Collection<String>) new ArrayList<String>(),
                        Iterables.iterable(references.split("[ \r\n\t]")));

            // Hotmail handles refs a bit differently...
            String hotmailRefs =
                Iterables.first(
                    Iterables.filter(
                        new Specification<String>() {
                          public boolean satisfiedBy(String item) {
                            return item.contains(",") && item.endsWith("@Streamflow>");
                          }
                        },
                        refs));

            String lastRef = null;
            if (!Strings.empty(hotmailRefs)) {
              lastRef = hotmailRefs.split(",")[1];
            } else {
              Collections.reverse(refs);
              Iterable<String> filter =
                  Iterables.filter(
                      new Specification<String>() {
                        public boolean satisfiedBy(String item) {
                          return item.endsWith("@Streamflow>");
                        }
                      },
                      refs);
              lastRef = Iterables.first(filter);
            }

            if (lastRef == null) {
              ValueBuilder<EmailValue> builder =
                  module
                      .valueBuilderFactory()
                      .newValueBuilder(EmailValue.class)
                      .withPrototype(email);
              String subj = "Msg Ref missing: " + builder.prototype().subject().get();
              builder.prototype().subject().set(subj.length() > 50 ? subj.substring(0, 50) : subj);

              systemDefaults.createCaseOnEmailFailure(builder.newInstance());
              logger.error("Could not find message reference in email header:" + lastRef);
              uow.discard();
              return;
            }

            Matcher matcher = Pattern.compile("<([^/]*)/([^@]*)@[^>]*>").matcher(lastRef);

            if (matcher.find()) {
              String conversationId = matcher.group(1);
              String participantId = URLDecoder.decode(matcher.group(2), "UTF-8");

              if (!"".equals(conversationId) && !"".equals(participantId)) {
                ConversationParticipant from =
                    uow.get(ConversationParticipant.class, participantId);
                Conversation conversation = uow.get(Conversation.class, conversationId);

                CaseEntity caze = (CaseEntity) conversation.conversationOwner().get();
                String content = email.content().get();

                // If we have an assignee, ensure it is a member of the conversation first
                if (caze.isAssigned()) {
                  if (!conversation.isParticipant(
                      (ConversationParticipant) caze.assignedTo().get()))
                    conversation.addParticipant((ConversationParticipant) caze.assignedTo().get());
                }

                // Create a new role map and fill it with relevant objects
                if (RoleMap.current() == null) RoleMap.newCurrentRoleMap();
                RoleMap.current().set(from, ConversationParticipant.class);
                RoleMap.current().set(caze, CaseLoggable.Data.class);
                RoleMap.current().set(caze, Case.class);

                Message message = null;

                if (Translator.HTML.equalsIgnoreCase(email.contentType().get())) {
                  message =
                      conversation.createMessage(email.contentHtml().get(), MessageType.HTML, from);
                } else {
                  message =
                      conversation.createMessage(email.content().get(), MessageType.PLAIN, from);
                }
                // Create attachments
                for (AttachedFileValue attachedFileValue : email.attachments().get()) {
                  if (!(attachedFileValue.mimeType().get().contains("text/x-vcard")
                      || attachedFileValue.mimeType().get().contains("text/directory"))) {
                    Attachment attachment = message.createAttachment(attachedFileValue.uri().get());
                    attachment.changeDescription("New Attachment");
                    attachment.changeName(attachedFileValue.name().get());
                    attachment.changeMimeType(attachedFileValue.mimeType().get());
                    attachment.changeModificationDate(attachedFileValue.modificationDate().get());
                    attachment.changeSize(attachedFileValue.size().get());
                    attachment.changeUri(attachedFileValue.uri().get());
                  }
                }

                try {
                  if (caze.isStatus(CaseStates.CLOSED)) {
                    RoleMap.newCurrentRoleMap();
                    RoleMap.current().set(caze);
                    if (caze.assignedTo().get() != null) {
                      RoleMap.current().set(caze.assignedTo().get());
                    } else {
                      RoleMap.current()
                          .set(uow.get(UserEntity.class, UserEntity.ADMINISTRATOR_USERNAME));
                    }
                    CaseCommandsContext caseCommands =
                        module.transientBuilderFactory().newTransient(CaseCommandsContext.class);
                    caseCommands.reopen();
                    caseCommands.unassign();
                    RoleMap.clearCurrentRoleMap();
                  }
                } catch (Throwable e) {
                  ValueBuilder<EmailValue> builder =
                      module
                          .valueBuilderFactory()
                          .newValueBuilder(EmailValue.class)
                          .withPrototype(email);
                  String subj = "Create Case failed: " + builder.prototype().subject().get();
                  builder
                      .prototype()
                      .subject()
                      .set(subj.length() > 50 ? subj.substring(0, 50) : subj);

                  systemDefaults.createCaseOnEmailFailure(builder.newInstance());
                  // throw new IllegalStateException("Could not open case through new message.", e);
                }
              }
            }
          }

          uow.complete();
        } catch (Exception ex) {
          ValueBuilder<EmailValue> builder =
              module.valueBuilderFactory().newValueBuilder(EmailValue.class).withPrototype(email);
          String subj = "Conversation Response Error: " + builder.prototype().subject().get();
          builder.prototype().subject().set(subj.length() > 50 ? subj.substring(0, 50) : subj);

          StringBuilder content = new StringBuilder();
          content.append("Error Message: " + ex.getMessage());
          content.append("\n\rStackTrace:\n\r");
          for (StackTraceElement trace : Arrays.asList(ex.getStackTrace())) {
            content.append(trace.toString() + "\n\r");
          }

          builder.prototype().content().set(content.toString());
          // since we create the content of the message our self it's ok to set content type always
          // to text/plain
          builder.prototype().contentType().set("text/plain");

          // Make sure to address has some value before vi create a case!!
          if (builder.prototype().to().get() == null) {
            builder.prototype().to().set("n/a");
          }

          systemDefaults.createCaseOnEmailFailure(builder.newInstance());
          uow.discard();
          // throw new ApplicationEventReplayException(event, ex);
        }
      }
Esempio n. 9
0
    public void activate() throws Exception {
      Usecase usecase = UsecaseBuilder.newUsecase("Populate Sample Voyages");
      UnitOfWork uow = uowf.newUnitOfWork(usecase);
      try {

        final Location HONGKONG = locationRepository.findLocationByUnLocode("CNHKG");
        final Location TOKYO = locationRepository.findLocationByUnLocode("JNTKO");
        final Location NEWYORK = locationRepository.findLocationByUnLocode("USNYC");
        final Location CHICAGO = locationRepository.findLocationByUnLocode("USCHI");
        final Location STOCKHOLM = locationRepository.findLocationByUnLocode("SESTO");
        final Location ROTTERDAM = locationRepository.findLocationByUnLocode("NLRTM");
        final Location MELBOURNE = locationRepository.findLocationByUnLocode("AUMEL");
        final Location HAMBURG = locationRepository.findLocationByUnLocode("DEHAM");
        final Location HELSINKI = locationRepository.findLocationByUnLocode("FIHEL");
        final Location DALLAS = locationRepository.findLocationByUnLocode("USDAL");
        final Location HANGZOU = locationRepository.findLocationByUnLocode("CNHGH");
        final Location SHANGHAI = locationRepository.findLocationByUnLocode("CNSHA");

        Voyage v100 =
            new VoyageRepository.Builder(vbf, uow, "V100", HONGKONG)
                .addMovement(TOKYO, toDate("2009-03-03"), toDate("2009-03-05"))
                .addMovement(NEWYORK, toDate("2009-03-06"), toDate("2009-03-09"))
                .build();
        Voyage v200 =
            new VoyageRepository.Builder(vbf, uow, "V200", TOKYO)
                .addMovement(NEWYORK, toDate("2009-03-06"), toDate("2009-03-08"))
                .addMovement(CHICAGO, toDate("2009-03-10"), toDate("2009-03-14"))
                .addMovement(STOCKHOLM, toDate("2009-03-14"), toDate("2009-03-16"))
                .build();
        Voyage v300 =
            new VoyageRepository.Builder(vbf, uow, "V300", TOKYO)
                .addMovement(ROTTERDAM, toDate("2009-03-22"), toDate("2009-03-25"))
                .addMovement(HAMBURG, toDate("2009-03-25"), toDate("2009-03-26"))
                .addMovement(MELBOURNE, toDate("2009-03-28"), toDate("2009-04-03"))
                .addMovement(TOKYO, toDate("2009-04-03"), toDate("2009-04-06"))
                .build();
        Voyage v400 =
            new VoyageRepository.Builder(vbf, uow, "V400", HAMBURG)
                .addMovement(STOCKHOLM, toDate("2009-03-14"), toDate("2009-03-15"))
                .addMovement(HELSINKI, toDate("2009-03-15"), toDate("2009-03-16"))
                .addMovement(HAMBURG, toDate("2009-03-20"), toDate("2009-03-22"))
                .build();

        /*
         * Voyage number 0100S (by ship)
         * <p/>
         * Hongkong - Hangzou - Tokyo - Melbourne - New York
         */
        Voyage HONGKONG_TO_NEW_YORK =
            new VoyageRepository.Builder(vbf, uow, "0100S", HONGKONG)
                .addMovement(HANGZOU, toDate("2008-10-01", "12:00"), toDate("2008-10-03", "14:30"))
                .addMovement(TOKYO, toDate("2008-10-03", "21:00"), toDate("2008-10-06", "06:15"))
                .addMovement(
                    MELBOURNE, toDate("2008-10-06", "11:00"), toDate("2008-10-12", "11:30"))
                .addMovement(NEWYORK, toDate("2008-10-14", "12:00"), toDate("2008-10-23", "23:10"))
                .build();

        /*
         * Voyage number 0200T (by train)
         * <p/>
         * New York - Chicago - Dallas
         */
        Voyage NEW_YORK_TO_DALLAS =
            new VoyageRepository.Builder(vbf, uow, "0200T", NEWYORK)
                .addMovement(CHICAGO, toDate("2008-10-24", "07:00"), toDate("2008-10-24", "17:45"))
                .addMovement(DALLAS, toDate("2008-10-24", "21:25"), toDate("2008-10-25", "19:30"))
                .build();

        /*
         * Voyage number 0300A (by airplane)
         * <p/>
         * Dallas - Hamburg - Stockholm - Helsinki
         */
        Voyage DALLAS_TO_HELSINKI =
            new VoyageRepository.Builder(vbf, uow, "0300A", DALLAS)
                .addMovement(HAMBURG, toDate("2008-10-29", "03:30"), toDate("2008-10-31", "14:00"))
                .addMovement(
                    STOCKHOLM, toDate("2008-11-01", "15:20"), toDate("2008-11-01", "18:40"))
                .addMovement(HELSINKI, toDate("2008-11-02", "09:00"), toDate("2008-11-02", "11:15"))
                .build();

        /*
         * Voyage number 0301S (by ship)
         * <p/>
         * Dallas - Hamburg - Stockholm - Helsinki, alternate route
         */
        Voyage DALLAS_TO_HELSINKI_ALT =
            new VoyageRepository.Builder(vbf, uow, "0301S", DALLAS)
                .addMovement(HELSINKI, toDate("2008-10-29", "03:30"), toDate("2008-11-05", "15:45"))
                .build();

        /*
         * Voyage number 0400S (by ship)
         * <p/>
         * Helsinki - Rotterdam - Shanghai - Hongkong
         */
        Voyage HELSINKI_TO_HONGKONG =
            new VoyageRepository.Builder(vbf, uow, "0400S", HELSINKI)
                .addMovement(
                    ROTTERDAM, toDate("2008-11-04", "05:50"), toDate("2008-11-06", "14:10"))
                .addMovement(SHANGHAI, toDate("2008-11-10", "21:45"), toDate("2008-11-22", "16:40"))
                .addMovement(HONGKONG, toDate("2008-11-24", "07:00"), toDate("2008-11-28", "13:37"))
                .build();
        uow.complete();
      } catch (RuntimeException e) {
        uow.discard();
        throw e;
      }
    }