Java Code Examples for org.joda.time.DateTime

The following are top voted examples for showing how to use org.joda.time.DateTime. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: oma-riista-android   File: GameLogFragment.java   View source code 6 votes vote down vote up
private List<GameHarvest> filterCurrentYearItems(List<GameHarvest> items) {
    List<GameHarvest> filtered = new ArrayList<>();

    DateTime startDate = DateTimeUtils.getHuntingYearStart(mCalendarYear);
    DateTime endDate = DateTimeUtils.getHuntingYearEnd(mCalendarYear);

    for (GameHarvest event : items) {
        DateTime eventTime = new DateTime(event.mTime);

        if (LogEventBase.TYPE_SRVA.equals(event.mType)) {
            if (eventTime.getYear() == mCalendarYear) {
                filtered.add(event);
            }
        } else {
            if (eventTime.isAfter(startDate) && eventTime.isBefore(endDate)) {
                filtered.add(event);
            }
        }
    }
    return filtered;
}
 
Example 2
Project: pdf-converter   File: EpubCreator.java   View source code 6 votes vote down vote up
public void create(String title, File imgsDir, File output) throws IOException {
    timestamp = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ssSZZ").print(DateTime.now());
    uuid = UUID.randomUUID().toString();
    this.title = title;
    this.imgsDir = imgsDir;

    try {
        basedir = File.createTempFile(uuid,"");
        basedir.delete();
        basedir.mkdirs();
    } catch (IOException e) {
        e.printStackTrace();
    }
    classLoader = getClass().getClassLoader();

    copyImages();
    copyStandardFilez();
    createOPFFile();
    createIndex();
    createTitlePage();
    createTOC();
    pack(basedir.getAbsolutePath(), output.getAbsolutePath());
    FileUtils.deleteDirectory(basedir);
}
 
Example 3
Project: verify-service-provider   File: AuthnRequestFactory.java   View source code 6 votes vote down vote up
public AuthnRequest build(LevelOfAssurance levelOfAssurance, String serviceEntityId) {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID(String.format("_%s", UUID.randomUUID()));
    authnRequest.setIssueInstant(DateTime.now());
    authnRequest.setForceAuthn(false);
    authnRequest.setDestination(destination.toString());
    authnRequest.setExtensions(createExtensions());

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(serviceEntityId);
    authnRequest.setIssuer(issuer);

    authnRequest.setSignature(createSignature());

    try {
        XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest).marshall(authnRequest);
        Signer.signObject(authnRequest.getSignature());
    } catch (SignatureException | MarshallingException e) {
        throw new SAMLRuntimeException("Unknown problem while signing SAML object", e);
    }

    return authnRequest;
}
 
Example 4
Project: Android-Scrapper   File: SofaScoreParser.java   View source code 6 votes vote down vote up
private void init() {
    Log.i(TAG, "init: fetched");
    try {
        Document document = Jsoup.connect(game.getLeagueType().getBaseScoreUrl() + DateUtils.getDate(game.getGameAddDate(), "yyyy-MM-dd") + "/json")
                .timeout(60 * 1000)
                .maxBodySize(0)
                .header("Accept", "text/javascript")
                .ignoreContentType(true)
                .get();
        SofaScoreJson espnJson = new Gson().fromJson(document.text(), SofaScoreJson.class);
        for (Event event : espnJson.getEvents()) {
            if (gameStatusMap.contains(event)) {
                gameStatusMap.remove(event);
            }
            gameStatusMap.add(event);
        }
        MultiProcessPreference.getDefaultSharedPreferences().edit().putLong(LAST_UPDATE, new DateTime().getMillis()).commit();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: springboot-shiro-cas-mybatis   File: TimeBasedRegisteredServiceAccessStrategy.java   View source code 6 votes vote down vote up
@Override
public boolean isServiceAccessAllowed() {
    final DateTime now = DateTime.now();

    if (this.startingDateTime != null) {
        final DateTime st = DateTime.parse(this.startingDateTime);

        if (now.isBefore(st)) {
            LOGGER.warn("Service access not allowed because it starts at {}. Now is {}",
                    this.startingDateTime, now);
            return false;
        }
    }

    if (this.endingDateTime != null) {
        final DateTime et = DateTime.parse(this.endingDateTime);
        if  (now.isAfter(et)) {
            LOGGER.warn("Service access not allowed because it ended at {}. Now is {}",
                    this.endingDateTime, now);
            return false;
        }
    }

    return super.isServiceAccessAllowed();
}
 
Example 6
Project: exam   File: ReservationPollerActor.java   View source code 6 votes vote down vote up
@Override
public Receive createReceive() {
    return receiveBuilder().match(String.class, s -> {
        Logger.debug("{}: Running no-show check ...", getClass().getCanonicalName());
        DateTime now = AppUtil.adjustDST(DateTime.now());
        List<Reservation> reservations = Ebean.find(Reservation.class)
                .fetch("enrolment")
                .fetch("enrolment.exam")
                .fetch("enrolment.externalExam")
                .where()
                .eq("noShow", false)
                .lt("endAt", now.toDate())
                .isNull("externalReservation")
                .findList();

        if (reservations.isEmpty()) {
            Logger.debug("{}: ... none found.", getClass().getCanonicalName());
        } else {
            handler.handleNoShows(reservations);
        }

    }).build();
}
 
Example 7
Project: QDrill   File: ShowFilesCommandResult.java   View source code 6 votes vote down vote up
public ShowFilesCommandResult(String name,
                              boolean isDirectory,
                              boolean isFile,
                              long length,
                              String owner,
                              String group,
                              String permissions,
                              long accessTime,
                              long modificationTime) {
  this.name = name;
  this.isDirectory = isDirectory;
  this.isFile = isFile;
  this.length = length;
  this.owner = owner;
  this.group = group;
  this.permissions = permissions;

  // Get the timestamp in UTC because Drill's internal TIMESTAMP stores time in UTC
  DateTime at = new DateTime(accessTime).withZoneRetainFields(DateTimeZone.UTC);
  this.accessTime = new Timestamp(at.getMillis());

  DateTime mt = new DateTime(modificationTime).withZoneRetainFields(DateTimeZone.UTC);
  this.modificationTime = new Timestamp(mt.getMillis());
}
 
Example 8
Project: alexa-skill   File: RestCurseProvider.java   View source code 6 votes vote down vote up
private BitcoinCurse convert(Response raw) {
  final Double coin = 1d;
  Double euro = 0d;

  Matcher matcher = MONEY_PATTERN.matcher(raw.price_eur);
  if(matcher.find()) {
    final String rawEuro = matcher.group(1)
        .replace(".", ";")
        .replace(",", ".")
        .replace(";", "");

    euro = Double.parseDouble(rawEuro);
  }

  final DateTime date = DateTimeFormat.forPattern("dd.MM.yy HH:mm").parseDateTime(raw.date_de);

  return new BitcoinCurse(date, coin, euro);
}
 
Example 9
Project: CustomizableCalendar   File: MonthGridView.java   View source code 5 votes vote down vote up
private void init(Context context, AttributeSet attrs) {
    monthDateTime = new DateTime();
    layoutResId = R.layout.calendar_view;

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomizableCalendar);
    if (typedArray != null) {
        layoutResId = typedArray.getResourceId(R.styleable.CustomizableCalendar_month_layout, R.layout.calendar_view);
        dayLayoutResId = typedArray.getResourceId(R.styleable.CustomizableCalendar_cell_layout, R.layout.calendar_cell);
        typedArray.recycle();
    }

}
 
Example 10
Project: dataflow-opinion-analysis   File: IndexerPipelineUtils.java   View source code 5 votes vote down vote up
public static DateTime parseDateString(DateTimeFormatter formatter, String s) {
	DateTime result = null;
	try {
		result = formatter.parseDateTime(s);
	} catch (Exception e) {
		result = null;
	}
	return result;
}
 
Example 11
Project: powsybl-core   File: IdentifiableExtensionXmlTest.java   View source code 5 votes vote down vote up
private Network createMultipleExtensionsNetwork() {
    Network network = NetworkFactory.create("test", "test");
    network.setCaseDate(DateTime.parse("2017-11-17T12:00:00+01:00"));
    Substation s = network.newSubstation()
        .setId("S")
        .setCountry(Country.FR)
        .add();
    VoltageLevel vl = s.newVoltageLevel()
        .setId("VL")
        .setTopologyKind(TopologyKind.BUS_BREAKER)
        .setNominalV(20.0f)
        .setLowVoltageLimit(15.0f)
        .setHighVoltageLimit(25.0f)
        .add();
    vl.getBusBreakerView().newBus()
        .setId("BUS")
        .add();
    Load load = vl.newLoad()
        .setId("LOAD")
        .setP0(0.0f)
        .setQ0(0.0f)
        .setBus("BUS")
        .setConnectableBus("BUS")
        .add();
    load.addExtension(LoadFooExt.class, new LoadFooExt(load));
    load.addExtension(LoadBarExt.class, new LoadBarExt(load));

    return network;
}
 
Example 12
Project: aem-orchestrator   File: AemInstanceHelperServiceTest.java   View source code 5 votes vote down vote up
@Test
public void testGetPublishIdToSnapshotFrom() throws Exception {
    String excludeInstanceId = "exclude-352768";
    List<String> instanceIds = new ArrayList<>();
    instanceIds.add(excludeInstanceId);
    instanceIds.add(instanceId);
    instanceIds.add("extra-89351");

    Date dt = new Date();

    DateTime originalDateTime = new DateTime(dt);
    Date originalDate = originalDateTime.toDate();
    DateTime originalPlusOneDateTime = originalDateTime.plusDays(1);
    Date originalPlusOneDate = originalPlusOneDateTime.toDate();

    when(awsHelperService.getInstanceIdsForAutoScalingGroup(
        envValues.getAutoScaleGroupNameForPublish())).thenReturn(instanceIds);

    Map<String, String> instanceTags1 = new HashMap<>();
    instanceTags1.put(InstanceTags.SNAPSHOT_ID.getTagName(), "");

    when(awsHelperService.getTags(anyString())).thenReturn(instanceTags1);

    when(awsHelperService.getLaunchTime(instanceId)).thenReturn(originalDate);
    when(awsHelperService.getLaunchTime("extra-89351")).thenReturn(originalPlusOneDate);

    when(httpUtil.isHttpGetResponseOk(anyString())).thenReturn(true);
    
    String resultInstanceId = aemHelperService.getPublishIdToSnapshotFrom(excludeInstanceId);
    
    assertThat(resultInstanceId, equalTo(instanceId));
}
 
Example 13
Project: Android-Scrapper   File: GridViewAdapter.java   View source code 5 votes vote down vote up
protected void setGridMarker(int position) {
    if (data.get(position).getGameAddDate() == new DateTime(Constants.DATE.VEGAS_TIME_ZONE).withTimeAtStartOfDay().getMillis()) {
        gridMarker.setText(String.valueOf(data.get(position).getGridCount()));
        switch (data.get(position).getPreviousGridStatus()) {
            case NEUTRAL:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorDraw));
                break;
            case NEGATIVE:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorError));
                break;
            case DRAW:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorDraw));
                break;
            case POSITIVE:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorAccent));
                break;
            default:
                break;
        }
    } else {
        switch (data.get(position).getBidResult()) {
            case NEUTRAL:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.white));
                break;
            case NEGATIVE:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorError));
                break;
            case DRAW:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorDraw));
                break;
            case POSITIVE:
                gridMarker.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorAccent));
                break;
            default:
                break;
        }
        gridMarker.setText("");
    }
}
 
Example 14
Project: springboot-spwa-gae-demo   File: StringToDateTest.java   View source code 5 votes vote down vote up
@Test
public void shouldTransformLeniently() {
    assertThat(transformer.from("2014-06-01T12:34:56"), is(new DateTime(2014, 6, 1, 12, 34, 56).toDate()));
    assertThat(transformer.from("2014-06-01T12:34"), is(new DateTime(2014, 6, 1, 12, 34, 0).toDate()));
    assertThat(transformer.from("2014-06-01T12"), is(new DateTime(2014, 6, 1, 12, 0, 0).toDate()));
    assertThat(transformer.from("2014-06-01"), is(new DateTime(2014, 6, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014-06"), is(new DateTime(2014, 6, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014"), is(new DateTime(2014, 1, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014-06-01T12:34:56+08:00"), is(new DateTime(2014, 6, 1, 12, 34, 56).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
    assertThat(transformer.from("2014-06-01T12:34+08:00"), is(new DateTime(2014, 6, 1, 12, 34, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
    assertThat(transformer.from("2014-06-01T12+08:00"), is(new DateTime(2014, 6, 1, 12, 0, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
}
 
Example 15
Project: soundwave   File: SqsClient.java   View source code 5 votes vote down vote up
public boolean processMessage(Message msg) {
  try {
    MessageProcessingResult result = null;
    NotificationEvent event =
        objectMapper.readValue(msg.getBody(), NotificationEvent.class);

    logger.info("Receive event {} with state {} created at {}",
        event.getDetail().getInstanceId(),
        event.getDetail().getState(), event.getTime());

    sqsEventLogger.info(objectMapper.writeValueAsString(event));
    Map<String, String> attributes = msg.getAttributes();

    if (attributes.containsKey("SentTimestamp")) {
      DateTime sentTime = new DateTime(Long.parseLong(attributes.get("SentTimestamp")),
          DateTimeZone.UTC);
      event.setSqsSentTime(sentTime.toDate());
    }

    if (handler != null) {
      result = handler.processEvent(event);
      if (result != null) {
        messageProcessingLogger.info(objectMapper.writeValueAsString(result));
        return result.isSucceed();
      }
    }
  } catch (Exception e) {
    logger.warn("Error Process message:{}", ExceptionUtils.getRootCauseMessage(e));
  }
  return false;
}
 
Example 16
Project: verify-matching-service-adapter   File: SubjectConfirmationDataValidatorTest.java   View source code 5 votes vote down vote up
@Test
public void shouldGenerateErrorWhenSubjectConfirmationDataNotOnOrAfterIsInThePast() throws Exception {
    SubjectConfirmationData subjectConfirmationData = aSubjectConfirmationData().withNotOnOrAfter(DateTime.now().minusMinutes(5)).withNotBefore(DateTime.now()).build();

    Messages messages = validator.validate(subjectConfirmationData, messages());

    assertThat(messages.hasErrorLike(NOT_ON_OR_AFTER_INVALID)).isTrue();
}
 
Example 17
Project: cat-is-a-dog   File: HabitEvent.java   View source code 5 votes vote down vote up
public HabitEvent(String key, String habitKey, String comment, String photoUrl, double lat, double lon, DateTime eventDate, String userId) {
    this.key = key;
    this.userId = userId;
    this.habitKey = habitKey;
    this.comment = comment;
    this.photoUrl = photoUrl;
    this.latitude = lat;
    this.longitude = lon;
    this.eventDate = eventDate;
}
 
Example 18
Project: dataflow-opinion-analysis   File: IndexerPipelineUtils.java   View source code 5 votes vote down vote up
public static Long parseDateToLong(DateTimeFormatter formatter, String s) {
	Long result = null;
	DateTime date = parseDateString(formatter, s);
	if (date != null)
		result = date.getMillis();
	return result;
}
 
Example 19
Project: flink-stream-processing-refarch   File: TripEvent.java   View source code 5 votes vote down vote up
public TripEvent(String payload)  {
  super(payload);

  JsonNode json = Jackson.fromJsonString(payload, JsonNode.class);
  this.tripId = json.get("trip_id").asLong();
  this.timestamp = new DateTime(json.get("dropoff_datetime").asText()).getMillis();
}
 
Example 20
Project: Biliomi   File: ModerationRecordService.java   View source code 5 votes vote down vote up
public void recordModeration(User user, ModerationReason reason, ModerationAction action, String message) {
  ModerationRecord record = new ModerationRecord();
  record.setUser(user);
  record.setReason(reason);
  record.setAction(action);
  record.setMessage(message);
  record.setDate(DateTime.now());
  moderationRecordDao.save(record);
}
 
Example 21
Project: exam   File: AppUtil.java   View source code 5 votes vote down vote up
private static DateTime doAdjustDST(DateTime dateTime, ExamRoom room) {
    DateTimeZone dtz;
    DateTime result = dateTime;
    if (room == null) {
        dtz = getDefaultTimeZone();
    } else {
        dtz = DateTimeZone.forID(room.getLocalTimezone());
    }
    if (!dtz.isStandardOffset(System.currentTimeMillis())) {
        result = dateTime.plusHours(1);
    }
    return result;
}
 
Example 22
Project: DicomViewer   File: SliderTimeComponent.java   View source code 5 votes vote down vote up
/**
 * Appele apres mouvement des slider min ou max
 * Corrige les limites puis communique les nouvelles valeurs aux propertyChangeListeners
 * @param min
 * @param max
 * @param isChanging 
 */
private void onMinMaxChanged(double min, double max, final boolean isChanging) {
 //   min = validateValueInLimits(min);
 //   max = validateValueInLimits(max);
    dateMinAsValue = Math.min(min, max);
    dateMaxAsValue = Math.max(min, max);
    firePropertyChange(isChanging ? EVT_LIMITS_CHANGING : EVT_LIMITS_CHANGED, null, new DateTime[] {
            new DateTime((long)(double)dateMinAsValue),
            new DateTime((long)(double)dateMaxAsValue)});
}
 
Example 23
Project: tg-eventstore   File: EndToEndTest.java   View source code 5 votes vote down vote up
@Test
public void processes_only_category_events() throws Exception {
    NewEvent event1 = newEvent();
    NewEvent event2 = newEvent();
    NewEvent event3 = newEvent();
    store.write(streamId("alpha", "1"), singletonList(event1));
    store.write(streamId("beta", "1"), singletonList(event2));
    store.write(streamId("alpha", "2"), singletonList(event3));
    @SuppressWarnings("unchecked")
    EventHandler<DeserialisedEvent> eventHandler = Mockito.mock(EventHandler.class);
    subscription = new EventSubscription<>("test", store, "alpha", EndToEndTest::deserialize, eventHandler, clock, 1024, Duration.ofMillis(1L), store.emptyStorePosition(), DurationThreshold.warningThresholdWithCriticalRatio(Duration.ofSeconds(320), 1.25), new DurationThreshold(Duration.ofSeconds(1), Duration.ofSeconds(60)), emptyList());
    subscription.start();

    eventually(() -> {
        assertThat(subscription.health().get(), is(healthy));
    });

    verify(eventHandler).apply(
            Matchers.argThat(inMemoryPosition(1)),
            Matchers.eq(new DateTime(clock.millis(), DateTimeZone.getDefault())),
            Matchers.eq(new DeserialisedEvent(eventRecord(clock.instant(), streamId("alpha", "1"), 0, event1.type(), event1.data(), event1.metadata()))),
            Matchers.anyBoolean());

    verify(eventHandler).apply(
            Matchers.argThat(inMemoryPosition(3)),
            Matchers.eq(new DateTime(clock.millis(), DateTimeZone.getDefault())),
            Matchers.eq(new DeserialisedEvent(eventRecord(clock.instant(), streamId("alpha", "2"), 0, event3.type(), event3.data(), event3.metadata()))),
            Matchers.eq(true));

    verifyNoMoreInteractions(eventHandler);
}
 
Example 24
Project: azure-libraries-for-java   File: FunctionAppImpl.java   View source code 5 votes vote down vote up
@Override
public String getToken(Request request) {
    if (token == null || expire < DateTime.now().getMillis()) {
        token = functionApp.manager().inner().webApps()
                .getFunctionsAdminToken(functionApp.resourceGroupName(), functionApp.name());
        String jwt = new String(BaseEncoding.base64Url().decode(token.split("\\.")[1]));
        Pattern pattern = Pattern.compile("\"exp\": *([0-9]+),");
        Matcher matcher = pattern.matcher(jwt);
        matcher.find();
        expire = Long.parseLong(matcher.group(1));
    }
    return token;
}
 
Example 25
Project: Sense-Hub-Android-Things   File: MqttAuthentication.java   View source code 5 votes vote down vote up
public char[] createJwt(String projectId)
    throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
  DateTime now = new DateTime();

  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always
  // be set to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(60).toDate())
          .setAudience(projectId);

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, privateKey).compact().toCharArray();
}
 
Example 26
Project: autorest.java   File: DatetimesImpl.java   View source code 5 votes vote down vote up
/**
 * Get max datetime value with positive num offset 9999-12-31T23:59:59.9999999+14:00.
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the observable to the DateTime object
 */
public Observable<DateTime> getLocalPositiveOffsetUppercaseMaxDateTimeAsync() {
    return getLocalPositiveOffsetUppercaseMaxDateTimeWithServiceResponseAsync().map(new Func1<ServiceResponse<DateTime>, DateTime>() {
        @Override
        public DateTime call(ServiceResponse<DateTime> response) {
            return response.body();
        }
    });
}
 
Example 27
Project: DicomViewer   File: SliderTimeComponent.java   View source code 5 votes vote down vote up
/**
 * Changement des dates utilisees dans la barre de temps
 * @param availableDates liste des dates existantes
 * @param validDates liste des dates utilisee par l'animation
 * @param special liste des dates filtrees
 * @param inCache liste des dates qui sont dans le cache
 */
public void setValidDates(final List<DateTime> availableDates, final List<DateTime> validDates, final List<DateTime> validTimesWithoutFiltredFrames,
                          final Set<DateTime> special, final List<DateTime> inCache) {
    this.availableDates = availableDates;
    this.validDates = validDates;
    this.validTimesWithoutFiltredFrames = validTimesWithoutFiltredFrames;
    this.specialDates = special;
    this.inCacheDates = inCache;
    updateDisplayLimit();
    repaint();
}
 
Example 28
Project: device-telemetry-java   File: IMessages.java   View source code 5 votes vote down vote up
MessageListServiceModel getList(
DateTime from,
DateTime to,
String order,
int skip,
int limit,
String[] devices);
 
Example 29
Project: verify-hub   File: ExternalCommunicationEventLoggerTest.java   View source code 5 votes vote down vote up
@Test
public void logAuthenticationRequest_shouldPassHubEventToEventSinkProxy() {

    final String serviceName = "some-service-name";
    final SessionId sessionId = SessionId.createNewSessionId();
    final String messageId = "some-message-id";
    final String endpoint = "http://someurl.com";
    final URI endpointUrl = URI.create(endpoint);
    final String principalIpAddress = "some-ip-address";

    final String endpointIpAddress = "1.2.3.4";
    when(ipAddressResolver.lookupIpAddress(endpointUrl)).thenReturn(endpointIpAddress);

    final ExternalCommunicationEventLogger externalCommunicationEventLogger = new ExternalCommunicationEventLogger(aServiceInfo().withName(serviceName).build(), eventSinkProxy, ipAddressResolver);
    externalCommunicationEventLogger.logIdpAuthnRequest(messageId, sessionId, endpointUrl, principalIpAddress);

    final ArgumentCaptor<EventSinkHubEvent> logHubEvent = ArgumentCaptor.forClass(EventSinkHubEvent.class);
    verify(eventSinkProxy).logHubEvent(logHubEvent.capture());

    final EventSinkHubEvent loggedEvent = logHubEvent.getValue();
    assertThat(loggedEvent.getOriginatingService()).isEqualTo(serviceName);
    assertThat(loggedEvent.getEventType()).isEqualTo(EXTERNAL_COMMUNICATION_EVENT);
    assertThat(loggedEvent.getTimestamp().isEqual(DateTime.now())).isTrue();
    assertThat(loggedEvent.getSessionId()).isEqualTo(sessionId.toString());
    final Map<EventDetailsKey, String> eventDetails = loggedEvent.getDetails();
    assertThat(eventDetails.get(external_communication_type)).isEqualTo(AUTHN_REQUEST);
    assertThat(eventDetails.get(message_id)).isEqualTo(messageId);
    assertThat(eventDetails.get(external_endpoint)).isEqualTo(endpoint);
    assertThat(eventDetails.get(external_ip_address)).isNull();
    assertThat(eventDetails.get(principal_ip_address_as_seen_by_hub)).isEqualTo(principalIpAddress);
}
 
Example 30
Project: springboot-shiro-cas-mybatis   File: JpaLockingStrategy.java   View source code 5 votes vote down vote up
@Override
public boolean acquire() {
    final Lock lock;
    try {
        lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE);
    } catch (final PersistenceException e) {
        logger.debug("{} failed querying for {} lock.", uniqueId, applicationId, e);
        return false;
    }

    boolean result = false;
    if (lock != null) {
        final DateTime expDate = new DateTime(lock.getExpirationDate());
        if (lock.getUniqueId() == null) {
            // No one currently possesses lock
            logger.debug("{} trying to acquire {} lock.", uniqueId, applicationId);
            result = acquire(entityManager, lock);
        } else if (new DateTime().isAfter(expDate)) {
            // Acquire expired lock regardless of who formerly owned it
            logger.debug("{} trying to acquire expired {} lock.", uniqueId, applicationId);
            result = acquire(entityManager, lock);
        }
    } else {
        // First acquisition attempt for this applicationId
        logger.debug("Creating {} lock initially held by {}.", applicationId, uniqueId);
        result = acquire(entityManager, new Lock());
    }
    return result;
}
 
Example 31
Project: verify-hub   File: IdaAuthnRequestFromHubDto.java   View source code 5 votes vote down vote up
public IdaAuthnRequestFromHubDto(
    String id,
    Optional<Boolean> forceAuthentication,
    DateTime sessionExpiryTimestamp,
    String idpEntityId,
    List<LevelOfAssurance> levelsOfAssurance,
    Boolean useExactComparisonType,
    URI overriddenSsoUrl) {
    this(id, forceAuthentication, sessionExpiryTimestamp, idpEntityId, levelsOfAssurance, useExactComparisonType);
    this.overriddenSsoUrl = overriddenSsoUrl;
}
 
Example 32
Project: lams   File: ConditionsUnmarshaller.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {

    Conditions conditions = (Conditions) samlObject;

    if (Conditions.NOTBEFORE_ATTRIB_NAME.equals(attribute.getLocalName())
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        conditions.setNotBefore(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (Conditions.NOTONORAFTER_ATTRIB_NAME.equals(attribute.getLocalName())
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        conditions.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else {
        processAttribute(samlObject, attribute);
    }
}
 
Example 33
Project: justintrain-client-android   File: JourneyResultsPresenter.java   View source code 5 votes vote down vote up
@Override
public void searchJourney(boolean isNewSearch, String departureStationId, String arrivalStationId, DateTime timestamp, boolean isPreemptive, boolean withDelays, boolean includeTrainToBeTaken, OnJourneySearchFinishedListener listener) {
    APINetworkingFactory.createRetrofitService(JourneyService.class).getJourneyBeforeTime(departureStationId, arrivalStationId, timestamp.toString("yyyy-MM-dd'T'HH:mmZ"), withDelays, isPreemptive, SettingsPreferences.isIncludeChangesEnabled(listener.getViewContext()), SettingsPreferences.getEnabledCategoriesAsStringArray(listener.getViewContext()))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(journey -> {
                if (journey.getSolutions().size() > 0) {
                    journeySolutions.addAll(0, journey.getSolutions());
                    listener.onSuccess();
                } else {
                    listener.onJourneyBeforeNotFound();
                }
            }, throwable -> {
                listener.onServerError(throwable);
            });
}
 
Example 34
Project: Biliomi   File: SpotifyApiImpl.java   View source code 5 votes vote down vote up
/**
 * Update the persisted access token and the authorization header if necessary
 *
 * @return The id of the currently linked user
 */
@SuppressWarnings("Duplicates")
private synchronized String executeTokenPreflight() throws Exception {
  AuthToken token = authTokenDao.get(TokenGroup.INTEGRATIONS, "spotify");

  if (StringUtils.isEmpty(token.getToken())) {
    throw new UnavailableException("The Spotify Api is not connected to an account");
  }

  DateTime expiryTime = token.getExpiryTime();
  DateTime now = DateTime.now();
  if (expiryTime != null && now.isAfter(expiryTime)) {
    SpotifyOAuthFlowDirector director = new SpotifyOAuthFlowDirector(configService.getConsumerKey(), configService.getConsumerSecret(), webClient);
    boolean refreshSuccess = director.awaitRefreshedAccessToken(token.getRefreshToken());

    if (refreshSuccess) {
      token.setToken(director.getAccessToken());
      token.setIssuedAt(now);
      token.setTimeToLive(director.getTimeToLive());
      authTokenDao.save(token);
    } else {
      throw new UnavailableException("The Spotify Api failed to refresh the access token");
    }
  } else {
    headers.put(HttpHeader.AUTHORIZATION, OAUTH_HEADER_PREFIX + token.getToken());
  }
  return token.getUserId();
}
 
Example 35
Project: elasticsearch_my   File: TimeZoneRoundingTests.java   View source code 5 votes vote down vote up
/**
 * randomized test on {@link TimeIntervalRounding} with random interval and time zone offsets
 */
public void testIntervalRoundingRandom() {
    for (int i = 0; i < 1000; i++) {
        TimeUnit unit = randomFrom(new TimeUnit[] {TimeUnit.MINUTES, TimeUnit.HOURS, TimeUnit.DAYS});
        long interval = unit.toMillis(randomIntBetween(1, 365));
        DateTimeZone tz = randomDateTimeZone();
        Rounding rounding = new Rounding.TimeIntervalRounding(interval, tz);
        long mainDate = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00
        if (randomBoolean()) {
            mainDate = nastyDate(mainDate, tz, interval);
        }
        // check two intervals around date
        long previousRoundedValue = Long.MIN_VALUE;
        for (long date = mainDate - 2 * interval; date < mainDate + 2 * interval; date += interval / 2) {
            try {
                final long roundedDate = rounding.round(date);
                final long nextRoundingValue = rounding.nextRoundingValue(roundedDate);
                assertThat("Rounding should be idempotent", roundedDate, equalTo(rounding.round(roundedDate)));
                assertThat("Rounded value smaller or equal than unrounded", roundedDate, lessThanOrEqualTo(date));
                assertThat("Values smaller than rounded value should round further down", rounding.round(roundedDate - 1),
                        lessThan(roundedDate));
                assertThat("Rounding should be >= previous rounding value", roundedDate, greaterThanOrEqualTo(previousRoundedValue));

                if (tz.isFixed()) {
                    assertThat("NextRounding value should be greater than date", nextRoundingValue, greaterThan(roundedDate));
                    assertThat("NextRounding value should be interval from rounded value", nextRoundingValue - roundedDate,
                            equalTo(interval));
                    assertThat("NextRounding value should be a rounded date", nextRoundingValue,
                            equalTo(rounding.round(nextRoundingValue)));
                }
                previousRoundedValue = roundedDate;
            } catch (AssertionError e) {
                logger.error("Rounding error at {}, timezone {}, interval: {},", new DateTime(date, tz), tz, interval);
                throw e;
            }
        }
    }
}
 
Example 36
Project: elasticsearch_my   File: DateDerivativeIT.java   View source code 4 votes vote down vote up
private static String format(DateTime date, String pattern) {
    return DateTimeFormat.forPattern(pattern).print(date);
}
 
Example 37
Project: elasticsearch_my   File: BaseXContentTestCase.java   View source code 4 votes vote down vote up
public void testObjects() throws Exception {
    Map<String, Object[]> objects = new HashMap<>();
    objects.put("{'objects':[false,true,false]}", new Object[]{false, true, false});
    objects.put("{'objects':[1,1,2,3,5,8,13]}", new Object[]{(byte) 1, (byte) 1, (byte) 2, (byte) 3, (byte) 5, (byte) 8, (byte) 13});
    objects.put("{'objects':[1.0,1.0,2.0,3.0,5.0,8.0,13.0]}", new Object[]{1.0d, 1.0d, 2.0d, 3.0d, 5.0d, 8.0d, 13.0d});
    objects.put("{'objects':[1.0,1.0,2.0,3.0,5.0,8.0,13.0]}", new Object[]{1.0f, 1.0f, 2.0f, 3.0f, 5.0f, 8.0f, 13.0f});
    objects.put("{'objects':[{'lat':45.759429931640625,'lon':4.8394775390625}]}", new Object[]{GeoPoint.fromGeohash("u05kq4k")});
    objects.put("{'objects':[1,1,2,3,5,8,13]}", new Object[]{1, 1, 2, 3, 5, 8, 13});
    objects.put("{'objects':[1,1,2,3,5,8,13]}", new Object[]{1L, 1L, 2L, 3L, 5L, 8L, 13L});
    objects.put("{'objects':[1,1,2,3,5,8]}", new Object[]{(short) 1, (short) 1, (short) 2, (short) 3, (short) 5, (short) 8});
    objects.put("{'objects':['a','b','c']}", new Object[]{"a", "b", "c"});
    objects.put("{'objects':['a','b','c']}", new Object[]{new Text("a"), new Text(new BytesArray("b")), new Text("c")});
    objects.put("{'objects':null}", null);
    objects.put("{'objects':[null,null,null]}", new Object[]{null, null, null});
    objects.put("{'objects':['OPEN','CLOSE']}", IndexMetaData.State.values());
    objects.put("{'objects':[{'f1':'v1'},{'f2':'v2'}]}", new Object[]{singletonMap("f1", "v1"), singletonMap("f2", "v2")});
    objects.put("{'objects':[[1,2,3],[4,5]]}", new Object[]{Arrays.asList(1, 2, 3), Arrays.asList(4, 5)});

    final String paths = Constants.WINDOWS ? "{'objects':['a\\\\b\\\\c','d\\\\e']}" : "{'objects':['a/b/c','d/e']}";
    objects.put(paths, new Object[]{PathUtils.get("a", "b", "c"), PathUtils.get("d", "e")});

    final DateTimeFormatter formatter = XContentBuilder.DEFAULT_DATE_PRINTER;
    final Date d1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
    final Date d2 = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
    objects.put("{'objects':['" + formatter.print(d1.getTime()) + "','" + formatter.print(d2.getTime()) + "']}", new Object[]{d1, d2});

    final DateTime dt1 = DateTime.now();
    final DateTime dt2 = new DateTime(2016, 12, 25, 7, 59, 42, 213, DateTimeZone.UTC);
    objects.put("{'objects':['" + formatter.print(dt1) + "','2016-12-25T07:59:42.213Z']}", new Object[]{dt1, dt2});

    final Calendar c1 = new DateTime(2012, 7, 7, 10, 23, DateTimeZone.UTC).toCalendar(Locale.ROOT);
    final Calendar c2 = new DateTime(2014, 11, 16, 19, 36, DateTimeZone.UTC).toCalendar(Locale.ROOT);
    objects.put("{'objects':['2012-07-07T10:23:00.000Z','2014-11-16T19:36:00.000Z']}", new Object[]{c1, c2});

    final ToXContent x1 = (builder, params) -> builder.startObject().field("f1", "v1").field("f2", 2).array("f3", 3, 4, 5).endObject();
    final ToXContent x2 = (builder, params) -> builder.startObject().field("f1", "v1").field("f2", x1).endObject();
    objects.put("{'objects':[{'f1':'v1','f2':2,'f3':[3,4,5]},{'f1':'v1','f2':{'f1':'v1','f2':2,'f3':[3,4,5]}}]}", new Object[]{x1, x2});

    for (Map.Entry<String, Object[]> o : objects.entrySet()) {
        final String expected = o.getKey();
        assertResult(expected, () -> builder().startObject().field("objects", o.getValue()).endObject());
        assertResult(expected, () -> builder().startObject().field("objects").value(o.getValue()).endObject());
        assertResult(expected, () -> builder().startObject().field("objects").values(o.getValue()).endObject());
        assertResult(expected, () -> builder().startObject().array("objects", o.getValue()).endObject());
    }
}
 
Example 38
Project: justintrain-client-android   File: TrainHeader.java   View source code 4 votes vote down vote up
public DateTime getJourneyArrivalTime() {
    return journeyArrivalTime;
}
 
Example 39
Project: springboot-spwa-gae-demo   File: ReadableInstantToDateTest.java   View source code 4 votes vote down vote up
@Test
public void shouldTransform() {
    verifyTransform(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHours(10)));
    verifyTransform(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHours(-10)));
}
 
Example 40
Project: upgradeToy   File: ExportDaoTest.java   View source code 4 votes vote down vote up
@Test
public void testqueryAlarmInRange() throws ParseException{
    List<Set<String>> list = new ArrayList<>();
    List<String> gpsnotime = readFile("D://in.txt");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < gpsnotime.size(); i++) {  //i=10;i< 20;i++
        int gpsnoi = Integer.valueOf(gpsnotime.get(i).split(",")[0]);
        GpsCard gpsCardi = gpsCardService.getByGpsNo(gpsnoi);
        Date timei = sdf.parse(gpsnotime.get(i).split(",")[1]);
        DateTime endi = new DateTime(timei);
        DateTime starti = new DateTime(timei).minusDays(1);
        List<TerminalAlarmInfo> alarmi = exportDao.queryAlarm0(gpsCardi.getGpsid(),starti.toDate(),endi.toDate());
        if (alarmi == null||alarmi.isEmpty()) {
            if (i/10 ==0) {
                System.out.println("inneri:"+gpsnoi);
            }
            continue;
        }
        
        for (int j = i+1; j < gpsnotime.size(); j++) {  //j=11;j<20;j++
            Set<String> set = new HashSet<>();
            int gpsnoj = Integer.valueOf(gpsnotime.get(j).split(",")[0]);
            GpsCard gpsCardj = gpsCardService.getByGpsNo(gpsnoj);
            Date timej = sdf.parse(gpsnotime.get(j).split(",")[1]);
            DateTime endj = new DateTime(timej);
            DateTime startj = new DateTime(timej).minusDays(1);
            List<TerminalAlarmInfo> alarmj = exportDao.queryAlarm1(gpsCardj.getGpsid(),startj.toDate(),endj.toDate());
            if (alarmj == null || alarmj.isEmpty()) {
                if (j/10 == 0) {
                    System.out.println("innerj:"+gpsnoj);
                }
                continue;
            }
            for (TerminalAlarmInfo alarmiout : alarmi) {
                for (TerminalAlarmInfo alarmjout : alarmj) {
                    if (j/20 == 0) {
                        System.out.println("calc:"+alarmiout.getStart_time()+","+alarmjout.getStart_time());
                    }
                    if (Math.abs(alarmiout.getStart_time().getTime() -alarmjout.getStart_time().getTime()) <=5000) {
                        set.add(gpsnotime.get(i).split(",")[0]);
                        set.add(gpsnotime.get(j).split(",")[0]);
                        System.out.println("set:"+set+","+(alarmiout.getStart_time().getTime() -alarmjout.getStart_time().getTime()));
                        list.add(set);
                    }
                }
            }
        }
    }
    System.out.println("result:"+list);
}