Ejemplo n.º 1
0
  @Override
  public void onStart(Application app) {
    if (Play.application().configuration().getString("app.envirement").equals("dev")) {
      AppConfig.setupDevEnv();
    } else if (Play.application().configuration().getString("app.envirement").equals("test")) {
      AppConfig.setupTestEnv();
    } else if (Play.application().configuration().getString("app.envirement").equals("prod")) {
      AppConfig.setupProdEnv();
    }

    play.libs.Akka.system()
        .scheduler()
        .schedule(
            Duration.create(0, TimeUnit.MILLISECONDS),
            Duration.create(1, TimeUnit.DAYS),
            new Runnable() {
              public void run() {
                System.out.println("tick");
                File dir = new File(AppConfig.temporaryFilesDirectory);
                for (String fname : dir.list()) {
                  if (fname.equals(".") || fname.equals("..")) continue;
                  File tmp = new File(AppConfig.temporaryFilesDirectory + fname);
                  if (tmp.exists()
                      && tmp.isFile()
                      && (new Date().getTime() - tmp.lastModified()) > (30L * 86400L * 1000L)) {
                    tmp.delete();
                  }
                }
              }
            });

    super.onStart(app);
  }
Ejemplo n.º 2
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    ActorSystem system = ActorSystem.create("faultTolerance");

    LoggingAdapter log = Logging.getLogger(system, system);

    Integer originalValue = Integer.valueOf(0);

    ActorRef supervisor = system.actorOf(new Props(SupervisorActor.class), "supervisor");

    log.info("Sending value 8, no exceptions should be thrown! ");
    supervisor.tell(Integer.valueOf(8));

    Integer result =
        (Integer)
            Await.result(
                Patterns.ask(supervisor, new Result(), 5000),
                Duration.create(5000, TimeUnit.MILLISECONDS));

    log.info("Value Received-> {}", result);
    assert result.equals(Integer.valueOf(8));

    log.info(
        "Sending value -8, ArithmeticException should be thrown! Our Supervisor strategy says resume !");
    supervisor.tell(Integer.valueOf(-8));

    result =
        (Integer)
            Await.result(
                Patterns.ask(supervisor, new Result(), 5000),
                Duration.create(5000, TimeUnit.MILLISECONDS));

    log.info("Value Received-> {}", result);
    assert result.equals(Integer.valueOf(8));

    log.info(
        "Sending value null, NullPointerException should be thrown! Our Supervisor strategy says restart !");
    supervisor.tell(null);

    result =
        (Integer)
            Await.result(
                Patterns.ask(supervisor, new Result(), 5000),
                Duration.create(5000, TimeUnit.MILLISECONDS));

    log.info("Value Received-> {}", result);
    assert originalValue.equals(result);

    log.info(
        "Sending value \"String\", IllegalArgumentException should be thrown! Our Supervisor strategy says Stop !");

    supervisor.tell(String.valueOf("Do Something"));

    log.info("Worker Actor shutdown !");
    system.shutdown();
  }
    @Override
    public void actionPerformed(ActionEvent arg0) {

      if (master == null) {
        JOptionPane.showMessageDialog(
            null,
            "Error, There is no master to perform the builds. Please configure"
                + " a remote or local master in the menu bar.");
        return;
      }

      BATCHECKOUT checkout =
          (BATCHECKOUT) view.selectedDatesTablePanel.m_combo_checkout.getSelectedItem();
      BATBUILD build = (BATBUILD) view.selectedDatesTablePanel.m_combo_build.getSelectedItem();
      BATDELETE delete = (BATDELETE) view.selectedDatesTablePanel.m_combo_delete.getSelectedItem();

      Timeout timeout = new Timeout(Duration.create(2, "seconds"));
      Future<Object> selectedDatesFuture =
          Patterns.ask(selectedActor, new RequestSelectedDatesMessage(), timeout);
      try {
        CurrentSelectedDatesResponse sdm =
            (CurrentSelectedDatesResponse) Await.result(selectedDatesFuture, timeout.duration());
        for (SelectedDate d : sdm.dates) {
          master.tell(
              new CheckoutBuildDeleteTask(master, d.getDate(), checkout, build, delete), self());
        }

        selectedActor.tell(new RemoveAllDates());
        updateAllGui(new ArrayList<SelectedDate>());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Ejemplo n.º 4
0
  @Test
  public void usePatternsAskPipeTo() {
    ActorSystem system = ActorSystem.create("MySystem");
    ActorRef actorA = system.actorOf(new Props(MyUntypedActor.class));
    ActorRef actorB = system.actorOf(new Props(MyUntypedActor.class));
    ActorRef actorC = system.actorOf(new Props(MyUntypedActor.class));
    // #ask-pipeTo
    final Timeout t = new Timeout(Duration.create(5, TimeUnit.SECONDS));

    final ArrayList<Future<Object>> futures = new ArrayList<Future<Object>>();
    futures.add(ask(actorA, "request", 1000)); // using 1000ms timeout
    futures.add(ask(actorB, "reqeest", t)); // using timeout from above

    final Future<Iterable<Object>> aggregate = Futures.sequence(futures, system.dispatcher());

    final Future<Result> transformed =
        aggregate.map(
            new akka.japi.Function<Iterable<Object>, Result>() {
              public Result apply(Iterable<Object> coll) {
                final Iterator<Object> it = coll.iterator();
                final String s = (String) it.next();
                final int x = (Integer) it.next();
                return new Result(x, s);
              }
            });

    pipeTo(transformed, actorC);
    // #ask-pipeTo
  }
Ejemplo n.º 5
0
  @Test
  public void usePatternsGracefulStop() {
    ActorSystem system = ActorSystem.create("MySystem");
    ActorRef actorRef = system.actorOf(new Props(MyUntypedActor.class));
    // #gracefulStop

    try {
      Future<Boolean> stopped =
          gracefulStop(actorRef, Duration.create(5, TimeUnit.SECONDS), system);
      Await.result(stopped, Duration.create(6, TimeUnit.SECONDS));
      // the actor has been stopped
    } catch (ActorTimeoutException e) {
      // the actor wasn't stopped within 5 seconds
    }
    // #gracefulStop
    system.shutdown();
  }
Ejemplo n.º 6
0
 @Test
 public void useWatch() {
   ActorSystem system = ActorSystem.create("MySystem");
   ActorRef myActor = system.actorOf(new Props(WatchActor.class));
   Future<Object> future = Patterns.ask(myActor, "kill", 1000);
   assert Await.result(future, Duration.parse("1 second")).equals("finished");
   system.shutdown();
 }
 private List<SelectedDate> getSelectedDates() {
   Timeout timeout = new Timeout(Duration.create(2, "seconds"));
   Future<Object> selectedDatesFuture =
       Patterns.ask(selectedActor, new RequestSelectedDatesMessage(), timeout);
   CurrentSelectedDatesResponse sdm;
   try {
     sdm = (CurrentSelectedDatesResponse) Await.result(selectedDatesFuture, timeout.duration());
     return sdm.dates;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 8
0
  // #crTest
  @Test
  public void countVotesAsIntendedNotAsInFlorida() {
    ActorRef routedActor = system.actorOf(new Props().withRouter(new VoteCountRouter()));
    routedActor.tell(DemocratVote);
    routedActor.tell(DemocratVote);
    routedActor.tell(RepublicanVote);
    routedActor.tell(DemocratVote);
    routedActor.tell(RepublicanVote);
    Timeout timeout = new Timeout(Duration.parse("1 seconds"));
    Future<Object> democratsResult = routedActor.ask(DemocratCountResult, timeout);
    Future<Object> republicansResult = routedActor.ask(RepublicanCountResult, timeout);

    assertEquals(3, Await.result(democratsResult, timeout.duration()));
    assertEquals(2, Await.result(republicansResult, timeout.duration()));
  }
Ejemplo n.º 9
0
  @Test
  public void usingAsk() {
    ActorSystem system = ActorSystem.create("MySystem");
    ActorRef myActor =
        system.actorOf(
            new Props(
                new UntypedActorFactory() {
                  public UntypedActor create() {
                    return new MyAskActor();
                  }
                }),
            "myactor");

    // #using-ask
    Future<Object> future = Patterns.ask(myActor, "Hello", 1000);
    Object result = Await.result(future, Duration.create(1, TimeUnit.SECONDS));
    // #using-ask
    system.shutdown();
  }
Ejemplo n.º 10
0
 public void onReceive(Object message) {
   if (message instanceof Calculate) {
     for (long start = 0; start < nrOfMessages; start++) {
       workerRouter.tell(new Work(start, nrOfElements), getSelf());
     }
   } else if (message instanceof Result) {
     Result result = (Result) message;
     pi += result.getValue();
     nrOfResults += 1;
     if (nrOfResults == nrOfMessages) {
       // Send the result to the listener
       Duration duration =
           Duration.create(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
       listener.tell(new PiApproximation(pi, duration), getSelf());
       // Stops this actor and all its supervised children
       getContext().stop(getSelf());
     }
   } else {
     unhandled(message);
   }
 }
Ejemplo n.º 11
0
  public static void main(String[] args) throws InterruptedException {

    ActorSystem app = ActorSystem.create("UntypedCoordinatedExample", AkkaSpec.testConf());

    ActorRef counter1 = app.actorOf(new Props().withCreator(UntypedCoordinatedCounter.class));
    ActorRef counter2 = app.actorOf(new Props().withCreator(UntypedCoordinatedCounter.class));

    counter1.tell(new Coordinated(new Increment(counter2)));

    Thread.sleep(3000);

    long timeout = 5000;
    Duration d = Duration.create(timeout, TimeUnit.MILLISECONDS);

    Future<Object> future1 = counter1.ask("GetCount", timeout);
    Future<Object> future2 = counter2.ask("GetCount", timeout);

    int count1 = (Integer) Await.result(future1, d);
    System.out.println("counter 1: " + count1);
    int count2 = (Integer) Await.result(future2, d);
    System.out.println("counter 1: " + count2);

    app.shutdown();
  }
Ejemplo n.º 12
0
  @Override
  public void preStart() {
    LOGGER.info(getSelf() + " : Starting");
    checkBalanceInteval = Duration.create(config.getBalanceCheckingInterval(), TimeUnit.SECONDS);
    checkPendingInteval =
        Duration.create(config.getPendingTransactionCheckingInterval(), TimeUnit.SECONDS);
    /*
     * Create a router with numberOfChildren children , use RoundRobin
     */
    router =
        getContext()
            .actorOf(
                new Props(
                        new UntypedActorFactory() {
                          private static final long serialVersionUID = 1L;

                          @Override
                          public Actor create() throws Exception {
                            return new XpayActor(config, getSelf());
                          }
                        })
                    .withRouter(new RoundRobinRouter(config.getNumberOfChildren())));

    // login with Xpay at start up
    router.tell(new Login(), getSelf());

    // Search for all the pending transaction and send to actor once when
    // master starts
    List<AtTransaction> transactions =
        mapper.searchTransactionByStatusAndConnType("PENDING", "XPAY");
    for (AtTransaction txn : transactions) {
      IntegrationPayload payload = new IntegrationPayload();
      payload.put("telco_id", txn.getTelco_id());
      payload.put("transaction_id", txn.getAt_txn_id().toString());
      payload.put("msisdn", txn.getMsisdn());
      payload.put("amount", txn.getAmount() + "");
      try {
        router.tell(Utils.fromIntegrationPayload(config.getPostpaidSuffix(), payload), getSelf());
      } catch (Exception e) {
        LOGGER.error(e.getMessage());
      }
    }

    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(15, TimeUnit.SECONDS), HandshakeInterval, router, new Handshake());
    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(30, TimeUnit.SECONDS),
            checkBalanceInteval,
            router,
            new BalanceRequest());

    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(30, TimeUnit.SECONDS),
            checkPendingInteval,
            getSelf(),
            new CheckUnknownRequest());
  }
Ejemplo n.º 13
0
public class XpayMaster extends UntypedActor {
  private static Logger LOGGER = Logger.getLogger(XpayMaster.class);
  private int numberOfRequestMessages = 0;
  private XpayConfig config;
  private Mapper mapper;
  ActorRef router;
  private final int MILITOHOURCONVERSION = 3600 * 1000;
  private Duration checkPendingInteval = null;
  private Duration checkBalanceInteval = null;
  private final Duration HandshakeInterval = Duration.create(300, TimeUnit.SECONDS);

  public static String sessionId = "";

  public static String getSessionId() {
    return sessionId;
  }

  public XpayMaster(XpayConfig config, Mapper mapper) {
    this.config = config;
    this.mapper = mapper;
  }

  @Override
  public void preStart() {
    LOGGER.info(getSelf() + " : Starting");
    checkBalanceInteval = Duration.create(config.getBalanceCheckingInterval(), TimeUnit.SECONDS);
    checkPendingInteval =
        Duration.create(config.getPendingTransactionCheckingInterval(), TimeUnit.SECONDS);
    /*
     * Create a router with numberOfChildren children , use RoundRobin
     */
    router =
        getContext()
            .actorOf(
                new Props(
                        new UntypedActorFactory() {
                          private static final long serialVersionUID = 1L;

                          @Override
                          public Actor create() throws Exception {
                            return new XpayActor(config, getSelf());
                          }
                        })
                    .withRouter(new RoundRobinRouter(config.getNumberOfChildren())));

    // login with Xpay at start up
    router.tell(new Login(), getSelf());

    // Search for all the pending transaction and send to actor once when
    // master starts
    List<AtTransaction> transactions =
        mapper.searchTransactionByStatusAndConnType("PENDING", "XPAY");
    for (AtTransaction txn : transactions) {
      IntegrationPayload payload = new IntegrationPayload();
      payload.put("telco_id", txn.getTelco_id());
      payload.put("transaction_id", txn.getAt_txn_id().toString());
      payload.put("msisdn", txn.getMsisdn());
      payload.put("amount", txn.getAmount() + "");
      try {
        router.tell(Utils.fromIntegrationPayload(config.getPostpaidSuffix(), payload), getSelf());
      } catch (Exception e) {
        LOGGER.error(e.getMessage());
      }
    }

    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(15, TimeUnit.SECONDS), HandshakeInterval, router, new Handshake());
    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(30, TimeUnit.SECONDS),
            checkBalanceInteval,
            router,
            new BalanceRequest());

    getContext()
        .system()
        .scheduler()
        .schedule(
            Duration.create(30, TimeUnit.SECONDS),
            checkPendingInteval,
            getSelf(),
            new CheckUnknownRequest());
  }

  @Override
  public void onReceive(Object message) throws Exception {
    LOGGER.info(getSelf() + " : Receives from " + getSender() + " message " + message);
    try {
      // handle children
      /**
       * Get TopupRequest, send TopupRequest to slave actors After 5 consecutive requests, check
       * balance of account
       */
      if (message instanceof TopupRequest) {
        router.tell(message, getSelf());
        ++numberOfRequestMessages;
        if (numberOfRequestMessages >= config.getNumberOfConsicutiveRequests()) {

          router.tell(new BalanceRequest(), getSelf());
          numberOfRequestMessages = 0;
        }
      }
      /**
       * Receive the CheckUnknownRequest. Get all the unknown XPAY transactions and send it to
       * slaves for confirmation.
       */
      else if (message instanceof CheckUnknownRequest) {
        List<AtTransaction> pendingTransactions =
            mapper.searchTransactionByStatusAndConnType("UNKNOWN", "XPAY");
        Date now = new Date();
        for (AtTransaction transaction : pendingTransactions) {
          long diff = now.getTime() - transaction.getUpdated_date().getTime();
          if (diff < 24 * MILITOHOURCONVERSION) {
            router.tell(transaction, getSelf());
          } else {
            transaction.setTxn_status("SUCCESS");
            getSelf().tell(transaction);
          }
        }
      }

      /** Handle the Query Balance result. Update new balance in database */
      else if (message instanceof BalanceResponse) {
        BalanceResponse response = (BalanceResponse) message;
        mapper.UpdateBalance(response);
      }
      /** Update the transactions to database */
      else if (message instanceof AtTransaction) {
        AtTransaction transaction = (AtTransaction) message;
        transaction.setUpdated_by("XPAY_SYS");
        transaction.setUpdated_date(new Date());
        if (transaction.getError_code() == null) {
          transaction.setError_code("");
        }
        mapper.UpdateTxn(transaction);
      }
      /** Kill self and all the children */
      else if (message instanceof Stop) {
        router.tell(PoisonPill.getInstance());
        getContext().stop(getSelf());
      }
    } catch (Exception e) {
      LOGGER.error(getSelf(), e);
    }
  }

  @Override
  public void postStop() {
    LOGGER.warn(getSelf() + " stopped");
  }
}