Пример #1
0
  /**
   * Handle an account state warning produced by ldaptive account state machinery.
   *
   * <p>Override this method to provide custom warning message handling.
   *
   * @param warning the account state warning messages.
   * @param response Ldaptive authentication response.
   * @param configuration Password policy configuration.
   * @param messages Container for messages produced by account state warning handling.
   */
  protected void handleWarning(
      final AccountState.Warning warning,
      final AuthenticationResponse response,
      final LdapPasswordPolicyConfiguration configuration,
      final List<Message> messages) {

    logger.debug("Handling warning {}", warning);
    if (warning == null) {
      logger.debug("Account state warning not defined");
      return;
    }

    final Calendar expDate = warning.getExpiration();
    final Days ttl = Days.daysBetween(Instant.now(), new Instant(expDate));
    logger.debug(
        "Password expires in {} days. Expiration warning threshold is {} days.",
        ttl.getDays(),
        configuration.getPasswordWarningNumberOfDays());
    if (configuration.isAlwaysDisplayPasswordExpirationWarning()
        || ttl.getDays() < configuration.getPasswordWarningNumberOfDays()) {
      messages.add(
          new PasswordExpiringWarningMessage(
              "Password expires in {0} days. Please change your password at <href=\"{1}\">{1}</a>",
              ttl.getDays(), configuration.getPasswordPolicyUrl()));
    }
    if (warning.getLoginsRemaining() > 0) {
      messages.add(
          new Message(
              "password.expiration.loginsRemaining",
              "You have {0} logins remaining before you MUST change your password.",
              warning.getLoginsRemaining()));
    }
  }
Пример #2
0
  @Transactional
  @Override
  public LoadResponse loadGoods(final GoodPayload payload) {
    final long timeInMillis = Instant.now().getMillis();

    LoadResponse response = new LoadResponse(timeInMillis);
    for (final Map.Entry<Long, Integer> entry : payload.getGoods().entrySet()) {
      namedJdbcTemplate
          .getJdbcOperations()
          .batchUpdate(
              QUERY_INSERT_GOOD,
              new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                  ps.setTimestamp(1, new Timestamp(timeInMillis), tzUTC);
                  ps.setLong(2, entry.getKey());
                  ps.setBoolean(3, false);
                }

                @Override
                public int getBatchSize() {
                  return entry.getValue();
                }
              });
    }

    return response;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      // inflate the layout
      LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
      convertView = inflater.inflate(layoutResourceId, parent, false);
    }

    // object item based on the position
    final Event event = data.get(position);
    final TextView userNameView = (TextView) convertView.findViewById(R.id.user_text);

    cloudStore.lookUpUserByUid(
        event.getUser(),
        new Callback<User>() {
          @Override
          public void receive(User user) {
            userNameView.setText(user.getGivenName());
          }
        });

    TextView time = (TextView) convertView.findViewById(R.id.time_text);
    time.setText(
        PeriodicalFormatter.printFriendlyDate(new Instant(event.getMillis()), Instant.now()));

    return convertView;
  }
Пример #4
0
 public void pause() {
   if (!isActive()) {
     throw new IllegalStateException("already non-active");
   }
   intervals.add(new Interval(starttime, Instant.now()));
   starttime = null;
 }
Пример #5
0
  /**
   * behaviour undefined if interval list is unsorted any {@code null} input is interpreted as a
   * non-bound in that direction
   *
   * @param focusStart
   * @param focusEnd
   * @return
   */
  public Duration getTimeSpentInInterval(LocalDate focusStart, LocalDate focusEnd) {
    Instant startInst, endInst;
    if (intervals.size() == 0 && !isActive()) { // #
      return Duration.ZERO;
    }
    if (focusStart == null) {
      startInst =
          intervals.size() == 0
              ? starttime // != null because #
              : intervals.get(0).getStart().toInstant();
    } else {
      startInst = focusStart.toDateTimeAtStartOfDay().toInstant();
    }
    if (focusEnd == null) {
      endInst =
          isActive()
              ? Instant.now()
              // v intervals.size() != 0 because #
              : intervals.get(intervals.size() - 1).getEnd().toInstant(); // TODO
    } else {
      endInst = focusEnd.toDateTimeAtStartOfDay().toInstant();
    }
    Interval focus = new Interval(startInst, endInst);

    return getTimeSpentInInterval(focus);
  }
Пример #6
0
 public void setDonity(boolean done) {
   if (!isDone() && done) {
     this.done = Instant.now();
   }
   if (isDone() && !done) {
     this.done = null;
   }
 }
  @Override
  public void flatMap(IN value, Collector<WindowedValue<OUT>> out) throws Exception {

    @SuppressWarnings("unchecked")
    OUT voidValue = (OUT) VoidCoderTypeSerializer.VoidValue.INSTANCE;
    for (byte[] element : elements) {
      ByteArrayInputStream bai = new ByteArrayInputStream(element);
      OUT outValue = coder.decode(bai, Coder.Context.OUTER);

      if (outValue == null) {
        out.collect(
            WindowedValue.of(voidValue, Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING));
      } else {
        out.collect(
            WindowedValue.of(outValue, Instant.now(), GlobalWindow.INSTANCE, PaneInfo.NO_FIRING));
      }
    }

    out.close();
  }
  @Override
  protected QuartzBatchJobMetrics mmrBatchExecuteInternal(JobDataMap mergedDataMap) {
    Instant startInstant = Instant.now();

    ExecutionResultDetails executionDetails = executeJob();

    Instant endInstant = Instant.now();
    Duration duration = new Duration(startInstant, endInstant);
    QuartzBatchJobMetrics jobMetrics =
        new BaseQuartzBatchJobMetrics(
            startInstant,
            endInstant,
            duration,
            executionDetails.getNumberOfProcessedItems(),
            executionDetails.getNumberOfErroredItems(),
            executionDetails.getErrorItems());

    logger.info(
        "Finished {} finished in {} time",
        getJobDetailName(),
        ISODateTimeFormat.basicTime().print(duration.getMillis()));
    return jobMetrics;
  }
Пример #9
0
  public Duration getTimeSpentInInterval(Interval focus) {
    if (focus == null) {
      throw new IllegalArgumentException("focus == nul");
    }

    Duration timespent = Duration.ZERO;

    for (Interval i : intervals) {
      Duration ov = computeOverlap(i, focus);
      timespent = timespent.plus(ov);
    }
    if (isActive()) {
      Interval activeInterval = new Interval(starttime, Instant.now());
      Duration overlapDuration = computeOverlap(activeInterval, focus);
      timespent = timespent.plus(overlapDuration);
    }

    return timespent;
  }
Пример #10
0
  public void start() {
    log.infof("Starting HeartbeatEmitter. Observe the HeartbeatEvent to subscribe.", Instant.now());

    final Runnable emitter =
        new Runnable() {
          @Override
          public void run() {
            try {
              log.debugf("heartbeat: %s", Instant.now());
              heartbeat.fire(new HeartbeatEvent());
            } catch (Exception e) {
              log.error(e);
            }
          }
        };

    emitterHandle =
        scheduler.scheduleAtFixedRate(emitter, initialDelay, periodInSeconds, TimeUnit.SECONDS);
  }
Пример #11
0
  protected void start() throws FightException {
    state = FightStateEnum.ACTIVE;

    generateTurns();
    fighters = CollectionUtils.concat(challengers.getFighters(), defenders.getFighters());

    foreach(
        new FightHandlerAction() {
          @Override
          public void call(IFightHandler obj) throws FightException {
            obj.notifyFightStart(turns, fighters);
          }
        });

    onStarted();

    startFight = Instant.now();

    getCurrentTurn().begin();
  }
 public AbstractRequestContext(
     Instant executionStart,
     String userId,
     String tenantId,
     Long userRef,
     Long tenantRef,
     long requestRef) {
   this.tenantId = tenantId;
   this.userId = userId;
   this.tenantRef = tenantRef;
   this.userRef = userRef;
   this.requestRef = requestRef;
   this.executionStart = executionStart != null ? executionStart : Instant.now();
   if (LOGGER.isDebugEnabled())
     LOGGER.debug(
         "Starting RequestContext for user {}, tenant {}, processRef {}",
         userId,
         tenantId,
         Long.valueOf(requestRef));
 }
Пример #13
0
  @Transactional
  @Override
  public ShipResponse shipGoods(final GoodPayload payload) throws NoSuchArticleException {

    long timeInMillis = Instant.now().getMillis();

    ShipResponse response = new ShipResponse(timeInMillis);

    response =
        namedJdbcTemplate.query(
            QUERY_FETCH_ARTICLE_AMOUNT,
            new MapSqlParameterSource("list", payload.getGoods().keySet()),
            new DiffExtractor(payload.getGoods(), response));

    if (response.getNoEnoughGoods() == null) {
      doShip(payload, timeInMillis, response);
      response.setStatus(ShipResponse.ShipStatus.SHIPPED);
    } else {
      response.setStatus(ShipResponse.ShipStatus.NOT_SHIPPED);
    }

    return response;
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long orderId)
      throws Exception {
    // Get the LineItemService.
    LineItemServiceInterface lineItemService =
        dfpServices.get(session, LineItemServiceInterface.class);

    // Get the NetworkService.
    NetworkServiceInterface networkService =
        dfpServices.get(session, NetworkServiceInterface.class);

    // Get the root ad unit ID used to target the whole site.
    String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();

    // Create inventory targeting.
    InventoryTargeting inventoryTargeting = new InventoryTargeting();

    // Create ad unit targeting for the root ad unit (i.e. the whole network).
    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
    adUnitTargeting.setAdUnitId(rootAdUnitId);
    adUnitTargeting.setIncludeDescendants(true);

    inventoryTargeting.setTargetedAdUnits(new AdUnitTargeting[] {adUnitTargeting});

    // Create geographical targeting.
    GeoTargeting geoTargeting = new GeoTargeting();

    // Include the US, Quebec, Canada, and the B3P Canada postal code.
    // To determine what other geographic criteria exists,
    // run GetGeoTargets.java.
    Location countryLocation = new Location();
    countryLocation.setId(2840L);

    Location regionLocation = new Location();
    regionLocation.setId(20133L);

    Location postalCodeLocation = new Location();
    postalCodeLocation.setId(9000093L);

    geoTargeting.setTargetedLocations(
        new Location[] {countryLocation, regionLocation, postalCodeLocation});

    // Exclude Chicago and the New York metro area.
    // To determine what other geographic criteria exists, run
    // GetGeoTargets.java.
    Location cityLocation = new Location();
    cityLocation.setId(1016367L);

    Location metroLocation = new Location();
    metroLocation.setId(200501L);
    geoTargeting.setExcludedLocations(new Location[] {cityLocation, metroLocation});

    // Exclude domains that are not under the network's control.
    UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
    userDomainTargeting.setDomains(new String[] {"usa.gov"});
    userDomainTargeting.setTargeted(false);

    // Create day-part targeting.
    DayPartTargeting dayPartTargeting = new DayPartTargeting();
    dayPartTargeting.setTimeZone(DeliveryTimeZone.BROWSER);

    // Target only the weekend in the browser's timezone.
    DayPart saturdayDayPart = new DayPart();
    saturdayDayPart.setDayOfWeek(DayOfWeek.SATURDAY);
    saturdayDayPart.setStartTime(new TimeOfDay(0, MinuteOfHour.ZERO));
    saturdayDayPart.setEndTime(new TimeOfDay(24, MinuteOfHour.ZERO));

    DayPart sundayDayPart = new DayPart();
    sundayDayPart.setDayOfWeek(DayOfWeek.SUNDAY);
    sundayDayPart.setStartTime(new TimeOfDay(0, MinuteOfHour.ZERO));
    sundayDayPart.setEndTime(new TimeOfDay(24, MinuteOfHour.ZERO));
    dayPartTargeting.setDayParts(new DayPart[] {saturdayDayPart, sundayDayPart});

    // Create technology targeting.
    TechnologyTargeting technologyTargeting = new TechnologyTargeting();

    // Create browser targeting.
    BrowserTargeting browserTargeting = new BrowserTargeting();
    browserTargeting.setIsTargeted(true);

    // Target just the Chrome browser.
    // To determine what other technology criteria exists, run
    // GetAllBrowsers.java.
    Technology browserTechnology = new Technology();
    browserTechnology.setId(500072L);
    browserTargeting.setBrowsers(new Technology[] {browserTechnology});
    technologyTargeting.setBrowserTargeting(browserTargeting);

    // Create targeting.
    Targeting targeting = new Targeting();
    targeting.setGeoTargeting(geoTargeting);
    targeting.setInventoryTargeting(inventoryTargeting);
    targeting.setUserDomainTargeting(userDomainTargeting);
    targeting.setDayPartTargeting(dayPartTargeting);
    targeting.setTechnologyTargeting(technologyTargeting);

    // Create a line item.
    LineItem lineItem = new LineItem();
    lineItem.setName("Line item #" + new Random().nextInt(Integer.MAX_VALUE));
    lineItem.setOrderId(orderId);
    lineItem.setTargeting(targeting);

    // Allow the line item to be booked even if there is not enough inventory.
    lineItem.setAllowOverbook(true);

    // Set the line item type to STANDARD and priority to Normal. In this case,
    // 6 would be High, and 10 would be Low.
    lineItem.setLineItemType(LineItemType.STANDARD);
    lineItem.setPriority(8);

    // Set the creative rotation type to even.
    lineItem.setCreativeRotationType(CreativeRotationType.EVEN);

    // Create creative placeholder size.
    Size size = new Size();
    size.setWidth(300);
    size.setHeight(250);
    size.setIsAspectRatio(false);

    // Create the creative placeholder.
    CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
    creativePlaceholder.setSize(size);

    // Set the size of creatives that can be associated with this line item.
    lineItem.setCreativePlaceholders(new CreativePlaceholder[] {creativePlaceholder});

    // Set the length of the line item to run.
    lineItem.setStartDateTimeType(StartDateTimeType.IMMEDIATELY);
    lineItem.setEndDateTime(
        DateTimes.toDateTime(Instant.now().plus(Duration.standardDays(30L)), "America/New_York"));

    // Set the cost per unit to $2.
    lineItem.setCostType(CostType.CPM);
    lineItem.setCostPerUnit(new Money("USD", 2000000L));

    // Set the number of units bought to 500,000 so that the budget is
    // $1,000.
    Goal goal = new Goal();
    goal.setGoalType(GoalType.LIFETIME);
    goal.setUnits(500000L);
    goal.setUnitType(UnitType.IMPRESSIONS);
    lineItem.setPrimaryGoal(goal);

    // Create the line item on the server.
    LineItem[] lineItems = lineItemService.createLineItems(new LineItem[] {lineItem});

    for (LineItem createdLineItem : lineItems) {
      System.out.printf(
          "A line item with ID \"%d\" and name \"%s\" was created.\n",
          createdLineItem.getId(), createdLineItem.getName());
    }
  }
Пример #15
0
 public Duration getFightDuration() {
   return new Duration(startFight, Instant.now());
 }
Пример #16
0
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.out.println("usage: VitessJDBCExample <vtgate-host:port>");
      System.exit(1);
    }

    // Connect to vtgate.
    String dbURL = "jdbc:vitess://" + args[0];
    try (Connection conn = DriverManager.getConnection(dbURL, null)) {
      // Setting AutoCommit to false as VTTablet was not up with enable-autocommit
      // Not Required if enable-autocommit flag is set in VTTablet
      conn.setAutoCommit(false);

      // Insert some messages on random pages.
      System.out.println("Inserting into master...");
      Random rand = new Random();
      for (int i = 0; i < 3; i++) {
        Instant timeCreated = Instant.now();
        int page = rand.nextInt(100) + 1;

        PreparedStatement stmt =
            conn.prepareStatement(
                "INSERT INTO messages (page,time_created_ns,message) VALUES (?,?,?)");
        stmt.setInt(1, page);
        stmt.setLong(2, timeCreated.getMillis() * 1000000);
        stmt.setString(3, "V is for speed");
        stmt.execute();
      }

      // To Commit Open Transaction
      conn.commit();

      // Read it back from master.
      System.out.println("Reading from master...");
      String sql = "SELECT page, time_created_ns, message FROM messages";
      try (Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery(sql)) {
        while (rs.next()) {
          long page = rs.getLong("page");
          long timeCreated = rs.getLong("time_created_ns");
          String message = rs.getString("message");
          System.out.format("(%s, %s, %s)\n", page, timeCreated, message);
        }
      }

      // To Commit Open Transaction, as select was made on master with autocommit false a
      // transaction was open
      conn.commit();

      // Read it back from replica.
      dbURL += "/test_keyspace?TABLET_TYPE=replica";
      try (Connection connReplica = DriverManager.getConnection(dbURL, null)) {
        System.out.println("Reading from replica...");
        sql = "SELECT page, time_created_ns, message FROM messages";
        try (Statement stmt = connReplica.createStatement();
            ResultSet rs = stmt.executeQuery(sql)) {
          while (rs.next()) {
            long page = rs.getLong("page");
            long timeCreated = rs.getLong("time_created_ns");
            String message = rs.getString("message");
            System.out.format("(%s, %s, %s)\n", page, timeCreated, message);
          }
        }
      }
    } catch (Exception e) {
      System.out.println("Vitess JDBC example failed.");
      System.out.println("Error Details:");
      e.printStackTrace();
      System.exit(2);
    }
  }
Пример #17
0
  private void runCompiler() {
    if (!shouldRunCompiler()) {
      System.exit(-1);
    }

    Instant start = Instant.now();
    config.getOutputStream().println("Generating documentation...");

    int result = 0;
    try {
      result = doRun();
    } catch (FlagUsageException e) {
      System.err.println(e.getMessage());
      System.exit(-1);
    } catch (Throwable t) {
      t.printStackTrace(System.err);
      System.exit(-2);
    }

    if (result != 0) {
      System.exit(result);
    }

    DocWriter writer =
        new DocWriter(
            config.getOutput(),
            Iterables.concat(config.getSources(), config.getModules()),
            config.getSrcPrefix(),
            config.getReadme(),
            config.getCustomPages(),
            typeRegistry,
            config.getTypeFilter(),
            new Linker(
                config.getOutput(),
                config.getSrcPrefix(),
                config.getModulePrefix(),
                config.getTypeFilter(),
                typeRegistry),
            new CommentParser(config.useMarkdown()));
    try {
      writer.generateDocs();
      if (config.isZipOutput()) {
        config.getOutput().getFileSystem().close();
      }
    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(-3);
    }

    Instant stop = Instant.now();
    String output =
        new PeriodFormatterBuilder()
            .appendHours()
            .appendSuffix("h") // I hope not...
            .appendSeparator(" ")
            .appendMinutes()
            .appendSuffix("m")
            .appendSeparator(" ")
            .appendSecondsWithOptionalMillis()
            .appendSuffix("s")
            .toFormatter()
            .print(new Period(start, stop));

    config.getOutputStream().println("Finished in " + output);
  }
Пример #18
0
 public void finish() {
   if (isActive()) {
     pause();
   }
   done = Instant.now();
 }
Пример #19
0
 public void start() {
   if (isActive()) {
     throw new IllegalStateException("already active");
   }
   starttime = Instant.now();
 }