Java Code Examples for org.joda.time.DateTime#plusSeconds()

The following examples show how to use org.joda.time.DateTime#plusSeconds() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimeRangeUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static DateTime increment(DateTime input, TimeGranularity granularity) {
  DateTime output;
  switch (granularity.getUnit()) {
  case DAYS:
    output = input.plusDays(granularity.getSize());
    break;
  case HOURS:
    output = input.plusHours(granularity.getSize());
    break;
  case MILLISECONDS:
    output = input.plusMillis(granularity.getSize());
    break;
  case MINUTES:
    output = input.plusMinutes(granularity.getSize());
    break;
  case SECONDS:
    output = input.plusSeconds(granularity.getSize());
    break;
  default:
    throw new IllegalArgumentException("Timegranularity:" + granularity + " not supported");
  }
  return output;
}
 
Example 2
Source File: JWTTokenService.java    From securing-rest-api-spring-security with Apache License 2.0 6 votes vote down vote up
private String newToken(final Map<String, String> attributes, final int expiresInSec) {
  final DateTime now = dates.now();
  final Claims claims = Jwts
    .claims()
    .setIssuer(issuer)
    .setIssuedAt(now.toDate());

  if (expiresInSec > 0) {
    final DateTime expiresAt = now.plusSeconds(expiresInSec);
    claims.setExpiration(expiresAt.toDate());
  }
  claims.putAll(attributes);

  return Jwts
    .builder()
    .setClaims(claims)
    .signWith(HS256, secretKey)
    .compressWith(COMPRESSION_CODEC)
    .compact();
}
 
Example 3
Source File: Gh911.java    From actframework with Apache License 2.0 6 votes vote down vote up
@GetAction
public DateTime getTime(String delta) {
    DateTime now = DateTime.now();
    int seconds;
    if (null != delta) {
        if (S.isInt(delta)) {
            seconds = Integer.parseInt(delta);
        } else {
            boolean negative = false;
            if (delta.startsWith("+")) {
                delta = delta.substring(1);
            } else if (delta.startsWith("-")) {
                delta = delta.substring(1);
                negative = true;
            } else {
                throw new IllegalArgumentException("Unknown delta: " + delta);
            }
            seconds = Time.parseDuration(delta);
        }
        now = now.plusSeconds(seconds);
    }
    return now;
}
 
Example 4
Source File: KinesisMockReadTest.java    From beam with Apache License 2.0 6 votes vote down vote up
private List<List<AmazonKinesisMock.TestData>> provideTestData(
    int noOfShards, int noOfEventsPerShard) {

  int seqNumber = 0;

  List<List<AmazonKinesisMock.TestData>> shardedData = newArrayList();
  for (int i = 0; i < noOfShards; ++i) {
    List<AmazonKinesisMock.TestData> shardData = newArrayList();
    shardedData.add(shardData);

    DateTime arrival = DateTime.now();
    for (int j = 0; j < noOfEventsPerShard; ++j) {
      arrival = arrival.plusSeconds(1);

      seqNumber++;
      shardData.add(
          new AmazonKinesisMock.TestData(
              Integer.toString(seqNumber), arrival.toInstant(), Integer.toString(seqNumber)));
    }
  }

  return shardedData;
}
 
Example 5
Source File: QuestService.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
private static Timestamp countNextRepeatTime(Player player, QuestTemplate template) {
	int questCooltime = template.getQuestCoolTime();
	DateTime now = DateTime.now();
	DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 9, 0, 0);
	if (template.isDaily()) {
		if (now.isAfter(repeatDate)) {
			repeatDate = repeatDate.plusHours(24);
		}
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400855, "9"));
	}
	else if (template.getQuestCoolTime() > 0) {
		repeatDate = repeatDate.plusSeconds(template.getQuestCoolTime());
		// This quest can be re-attempted in %DURATIONDAY0s.
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1402676, +questCooltime));
	}
	else {
		int daysToAdd = 7;
		int startDay = 7;
		for (QuestRepeatCycle weekDay : template.getRepeatCycle()) {
			int diff = weekDay.getDay() - repeatDate.getDayOfWeek();
			if (diff > 0 && diff < daysToAdd) {
				daysToAdd = diff;
			}
			if (startDay > weekDay.getDay()) {
				startDay = weekDay.getDay();
			}
		}
		if (startDay == daysToAdd) {
			daysToAdd = 7;
		}
		else if (daysToAdd == 7 && startDay < 7) {
			daysToAdd = 7 - repeatDate.getDayOfWeek() + startDay;
		}
		repeatDate = repeatDate.plusDays(daysToAdd);
		PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400857, new DescriptionId(1800667), "9"));
	}
	return new Timestamp(repeatDate.getMillis());
}
 
Example 6
Source File: SAMLTokenValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Check the Conditions of the Assertion.
 */
protected boolean isConditionValid(SamlAssertionWrapper assertion, int maxClockSkew) throws WSSecurityException {
    DateTime validFrom = null;
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
        && assertion.getSaml2().getConditions() != null) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
        && assertion.getSaml1().getConditions() != null) {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validFrom != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(maxClockSkew);
        if (validFrom.isAfter(currentTime)) {
            LOG.debug("SAML Token condition (Not Before) not met");
            return false;
        }
    }

    if (validTill != null && validTill.isBeforeNow()) {
        LOG.debug("SAML Token condition (Not On Or After) not met");
        return false;
    }
    return true;
}
 
Example 7
Source File: TestUtcTimeUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testUtcTimeUtilities() throws Exception {

        String dtString = "2010-09-01 00:00";
        DateTime dt = UtcTimeUtilities.fromStringWithMinutes(dtString);
        DateTime plusSeconds = dt.plusSeconds(30);
        String dtWithSeconds = UtcTimeUtilities.toStringWithSeconds(plusSeconds);
        assertEquals(dtString + ":30", dtWithSeconds);
    }
 
Example 8
Source File: Func.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply() {
    DateTime now = null == dateTime ? DateTime.now() : dateTime;
    if (null != deltaInSeconds) {
        int delta = deltaInSeconds;
        now = delta < 0 ? now.minusSeconds(-1 * delta) : now.plusSeconds(delta);
    }
    return now;
}
 
Example 9
Source File: KinesisProducerMock.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void flush() {
  DateTime arrival = DateTime.now();
  for (int i = 0; i < addedRecords.size(); i++) {
    UserRecord record = addedRecords.get(i);
    arrival = arrival.plusSeconds(1);
    kinesisService.addShardedData(record.getData(), arrival);
    addedRecords.remove(i);
  }
}
 
Example 10
Source File: Event.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void exempt(Person responsible, EventExemptionJustificationType justificationType, String justification) {
    DateTime when = new DateTime().minusSeconds(2);

    DebtInterestCalculator debtInterestCalculator = getDebtInterestCalculator(when);
    Money dueInterestAmount = new Money(debtInterestCalculator.getDueInterestAmount());
    Money dueFineAmount = new Money(debtInterestCalculator.getDueFineAmount());
    Money dueAmount = new Money(debtInterestCalculator.getDueAmount());

    if (dueInterestAmount.isPositive()) {
        FixedAmountInterestExemption fixedAmountInterestExemption =
                new FixedAmountInterestExemption(this, responsible, dueInterestAmount,
                        justificationType, new DateTime(), justification);
        fixedAmountInterestExemption.setWhenCreated(when);
        when = when.plusSeconds(1);
    }

    if (dueFineAmount.isPositive()) {
        FixedAmountFineExemption fixedAmountFineExemption =
                new FixedAmountFineExemption(this, responsible, dueFineAmount,
                        justificationType, new DateTime(), justification);
        fixedAmountFineExemption.setWhenCreated(when);
        when = when.plusSeconds(1);
    }

    if (dueAmount.isPositive()) {
        EventExemption eventExemption = new EventExemption(this, responsible, dueAmount,
                justificationType, new DateTime(), justification);
        eventExemption.setWhenCreated(when);
    }
    
}
 
Example 11
Source File: IdentityManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public String issueJWTToken( SubutaiOrigin origin ) throws TokenCreateException

{
    final String secret = UUID.randomUUID().toString();
    DateTime issueDate = DateTime.now();
    DateTime expireDate = issueDate.plusSeconds( JWT_TOKEN_EXPIRATION_TIME );
    String token =
            new TokenHelperImpl( TOKEN_ISSUER, origin.toString(), issueDate.toDate(), expireDate.toDate(), secret )
                    .getToken();

    this.jwtTokenCache.put( origin.toString(), secret );
    return token;
}
 
Example 12
Source File: TextUnitSearcherTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatedDate() throws Exception {

    DateTime now = DateTime.now();
    DateTime secondsBefore = now.minusSeconds(2);
    DateTime secondsAfter = now.plusSeconds(2);
    
    TMTestData tmTestData = new TMTestData(testIdWatcher);
    TextUnitSearcherParameters textUnitSearcherParameters = new TextUnitSearcherParameters();
    textUnitSearcherParameters.setRepositoryIds(tmTestData.repository.getId());
    textUnitSearcherParameters.setUsedFilter(UsedFilter.USED);

    List<TextUnitDTO> search = textUnitSearcher.search(textUnitSearcherParameters);
    assertEquals(8, search.size());

    textUnitSearcherParameters.setTmTextUnitCreatedBefore(secondsBefore);
    search = textUnitSearcher.search(textUnitSearcherParameters);
    assertEquals(0, search.size());

    textUnitSearcherParameters.setTmTextUnitCreatedAfter(secondsBefore);
    textUnitSearcherParameters.setTmTextUnitCreatedBefore(null);
    search = textUnitSearcher.search(textUnitSearcherParameters);
    assertEquals(8, search.size());

    textUnitSearcherParameters.setTmTextUnitCreatedAfter(secondsBefore);
    textUnitSearcherParameters.setTmTextUnitCreatedBefore(secondsAfter);
    search = textUnitSearcher.search(textUnitSearcherParameters);
    assertEquals(8, search.size());
    
    textUnitSearcherParameters.setTmTextUnitCreatedAfter(secondsAfter);
    textUnitSearcherParameters.setTmTextUnitCreatedBefore(null);
    search = textUnitSearcher.search(textUnitSearcherParameters);
    assertEquals(0, search.size());
    
}
 
Example 13
Source File: IssueInstantRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext");
        return;
    }
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    if (samlMsgCtx.getInboundSAMLMessageIssueInstant() == null) {
        if(requiredRule){
            log.warn("Inbound SAML message issue instant not present in message context");
            throw new SecurityPolicyException("Inbound SAML message issue instant not present in message context");
        }else{
            return;
        }
    }

    DateTime issueInstant = samlMsgCtx.getInboundSAMLMessageIssueInstant();
    DateTime now = new DateTime();
    DateTime latestValid = now.plusSeconds(clockSkew);
    DateTime expiration = issueInstant.plusSeconds(clockSkew + expires);

    // Check message wasn't issued in the future
    if (issueInstant.isAfter(latestValid)) {
        log.warn("Message was not yet valid: message time was {}, latest valid is: {}", issueInstant, latestValid);
        throw new SecurityPolicyException("Message was rejected because was issued in the future");
    }

    // Check message has not expired
    if (expiration.isBefore(now)) {
        log.warn("Message was expired: message issue time was '" + issueInstant + "', message expired at: '"
                + expiration + "', current time: '" + now + "'");
        throw new SecurityPolicyException("Message was rejected due to issue instant expiration");
    }

}
 
Example 14
Source File: BeamSqlDslAggregationTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testSupportsNonGlobalWindowWithCustomTrigger() {
  DateTime startTime = parseTimestampWithoutTimeZone("2017-1-1 0:0:0");

  Schema type =
      Schema.builder()
          .addInt32Field("f_intGroupingKey")
          .addInt32Field("f_intValue")
          .addDateTimeField("f_timestamp")
          .build();

  Object[] rows =
      new Object[] {
        0, 1, startTime.plusSeconds(0),
        0, 2, startTime.plusSeconds(1),
        0, 3, startTime.plusSeconds(2),
        0, 4, startTime.plusSeconds(3),
        0, 5, startTime.plusSeconds(4),
        0, 6, startTime.plusSeconds(6)
      };

  PCollection<Row> input =
      createTestPCollection(type, rows, "f_timestamp")
          .apply(
              Window.<Row>into(FixedWindows.of(Duration.standardSeconds(3)))
                  .triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(2)))
                  .discardingFiredPanes()
                  .withAllowedLateness(Duration.ZERO)
                  .withOnTimeBehavior(Window.OnTimeBehavior.FIRE_IF_NON_EMPTY));

  String sql = "SELECT SUM(f_intValue) AS `sum` FROM PCOLLECTION GROUP BY f_intGroupingKey";

  PCollection<Row> result = input.apply("sql", SqlTransform.query(sql));

  assertEquals(
      FixedWindows.of(Duration.standardSeconds(3)), result.getWindowingStrategy().getWindowFn());

  PAssert.that(result)
      .containsInAnyOrder(rowsWithSingleIntField("sum", Arrays.asList(3, 3, 9, 6)));

  pipeline.run();
}
 
Example 15
Source File: LoadTestAction.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  validateAndLogRequest();
  DateTime initialStartSecond = DateTime.now(UTC).plusSeconds(delaySeconds);
  ImmutableList.Builder<String> preTaskXmls = new ImmutableList.Builder<>();
  ImmutableList.Builder<String> contactNamesBuilder = new ImmutableList.Builder<>();
  ImmutableList.Builder<String> hostPrefixesBuilder = new ImmutableList.Builder<>();
  for (int i = 0; i < successfulDomainCreatesPerSecond; i++) {
    String contactName = getRandomLabel(MAX_CONTACT_LENGTH);
    String hostPrefix = getRandomLabel(ARBITRARY_VALID_HOST_LENGTH);
    contactNamesBuilder.add(contactName);
    hostPrefixesBuilder.add(hostPrefix);
    preTaskXmls.add(
        xmlContactCreateTmpl.replace("%contact%", contactName),
        xmlHostCreateTmpl.replace("%host%", hostPrefix));
  }
  enqueue(createTasks(preTaskXmls.build(), DateTime.now(UTC)));
  ImmutableList<String> contactNames = contactNamesBuilder.build();
  ImmutableList<String> hostPrefixes = hostPrefixesBuilder.build();

  ImmutableList.Builder<TaskOptions> tasks = new ImmutableList.Builder<>();
  for (int offsetSeconds = 0; offsetSeconds < runSeconds; offsetSeconds++) {
    DateTime startSecond = initialStartSecond.plusSeconds(offsetSeconds);
    // The first "failed" creates might actually succeed if the object doesn't already exist, but
    // that shouldn't affect the load numbers.
    tasks.addAll(
        createTasks(
            createNumCopies(xmlContactCreateFail, failedContactCreatesPerSecond), startSecond));
    tasks.addAll(
        createTasks(createNumCopies(xmlHostCreateFail, failedHostCreatesPerSecond), startSecond));
    tasks.addAll(
        createTasks(
            createNumCopies(xmlDomainCreateFail, failedDomainCreatesPerSecond), startSecond));
    // We can do infos on the known existing objects.
    tasks.addAll(
        createTasks(createNumCopies(xmlContactInfo, contactInfosPerSecond), startSecond));
    tasks.addAll(createTasks(createNumCopies(xmlHostInfo, hostInfosPerSecond), startSecond));
    tasks.addAll(createTasks(createNumCopies(xmlDomainInfo, domainInfosPerSecond), startSecond));
    // The domain check template uses "example.TLD" which won't exist, and one existing domain.
    tasks.addAll(
        createTasks(createNumCopies(xmlDomainCheck, domainChecksPerSecond), startSecond));
    // Do successful creates on random names
    tasks.addAll(
        createTasks(
            createNumCopies(xmlContactCreateTmpl, successfulContactCreatesPerSecond)
                .stream()
                .map(randomNameReplacer("%contact%", MAX_CONTACT_LENGTH))
                .collect(toImmutableList()),
            startSecond));
    tasks.addAll(
        createTasks(
            createNumCopies(xmlHostCreateTmpl, successfulHostCreatesPerSecond)
                .stream()
                .map(randomNameReplacer("%host%", ARBITRARY_VALID_HOST_LENGTH))
                .collect(toImmutableList()),
            startSecond));
    tasks.addAll(
        createTasks(
            createNumCopies(xmlDomainCreateTmpl, successfulDomainCreatesPerSecond)
                .stream()
                .map(randomNameReplacer("%domain%", MAX_DOMAIN_LABEL_LENGTH))
                .map(listNameReplacer("%contact%", contactNames))
                .map(listNameReplacer("%host%", hostPrefixes))
                .collect(toImmutableList()),
            startSecond));
  }
  ImmutableList<TaskOptions> taskOptions = tasks.build();
  enqueue(taskOptions);
  logger.atInfo().log("Added %d total load test tasks", taskOptions.size());
}
 
Example 16
Source File: SpliceAdmin.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void SYSCS_GET_SPLICE_TOKEN(final String user, // this variable is no longer used
                                          final ResultSet[] resultSet) throws SQLException {
    try {
        EmbedConnection conn = (EmbedConnection)getDefaultConn();
        LanguageConnectionContext lcc = conn.getLanguageConnection();
        Activation lastActivation = conn.getLanguageConnection().getLastActivation();

        DataDictionary dd = lcc.getDataDictionary();
        dd.startWriting(lcc);

        final GenericColumnDescriptor[] descriptors = {
                new GenericColumnDescriptor("TOKEN", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.BINARY)),
                new GenericColumnDescriptor("EXPIRETIME", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.TIMESTAMP)),
                new GenericColumnDescriptor("MAXIMUMTIME", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.TIMESTAMP)),
        };

        List<ExecRow> rows = new ArrayList<>();

        SConfiguration config=EngineDriver.driver().getConfiguration();
        int length = config.getAuthenticationTokenLength();
        int maxLifetime = config.getAuthenticationTokenMaxLifetime();
        int renewInterval = config.getAuthenticationTokenRenewInterval();

        byte[] token = new byte[length];
        new SecureRandom().nextBytes(token);

        String username = lcc.getCurrentUserId(lastActivation);
        DateTime creationTime = new DateTime(System.currentTimeMillis());
        DateTime expireTime = creationTime.plusSeconds(renewInterval);
        DateTime maxTime = creationTime.plusSeconds(maxLifetime);

        TokenDescriptor descriptor =
                new TokenDescriptor(token, username, creationTime, expireTime, maxTime);
        lcc.getDataDictionary().addToken(descriptor, lcc.getTransactionExecute());

        ExecRow row = new ValueRow(3);
        row.setColumn(1, new SQLBit(token));
        row.setColumn(2, new SQLTimestamp(expireTime));
        row.setColumn(3, new SQLTimestamp(maxTime));
        rows.add(row);

        IteratorNoPutResultSet resultsToWrap = new IteratorNoPutResultSet(rows, descriptors, lastActivation);
        resultsToWrap.openCore();
        resultSet[0] = new EmbedResultSet40(conn, resultsToWrap, false, null, true);
    } catch (StandardException se) {
        throw PublicAPI.wrapStandardException(se);
    } catch (Exception e) {
        throw PublicAPI.wrapStandardException(Exceptions.parseException(e));
    }
}
 
Example 17
Source File: Func.java    From actframework with Apache License 2.0 4 votes vote down vote up
protected DateTime now() {
    DateTime dt = highPrecision ? DateTime.now() : DateTime.now().withMillisOfSecond(0);
    return 0 == delta ? dt : dt.plusSeconds(delta);
}
 
Example 18
Source File: AugmentBaseDataVisitor.java    From spork with Apache License 2.0 4 votes vote down vote up
Object GetLargerValue(Object v) {
    byte type = DataType.findType(v);

    if (type == DataType.BAG || type == DataType.TUPLE
            || type == DataType.MAP)
        return null;

    switch (type) {
    case DataType.CHARARRAY:
        return (String) v + "0";
    case DataType.BYTEARRAY:
        String str = ((DataByteArray) v).toString();
        str = str + "0";
        return new DataByteArray(str);
    case DataType.INTEGER:
        return Integer.valueOf((Integer) v + 1);
    case DataType.LONG:
        return Long.valueOf((Long) v + 1);
    case DataType.FLOAT:
        return Float.valueOf((Float) v + 1);
    case DataType.DOUBLE:
        return Double.valueOf((Double) v + 1);
    case DataType.BIGINTEGER:
        return ((BigInteger)v).add(BigInteger.ONE);
    case DataType.BIGDECIMAL:
        return ((BigDecimal)v).add(BigDecimal.ONE);
    case DataType.DATETIME:
        DateTime dt = (DateTime) v;
        if (dt.getMillisOfSecond() != 0) {
            return dt.plusMillis(1);
        } else if (dt.getSecondOfMinute() != 0) {
            return dt.plusSeconds(1);
        } else if (dt.getMinuteOfHour() != 0) {
            return dt.plusMinutes(1);
        } else if (dt.getHourOfDay() != 0) {
            return dt.plusHours(1);
        } else {
            return dt.plusDays(1);
        }
    default:
        return null;
    }
}
 
Example 19
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a SAML 1.1 Protocol Response
 * @param samlResponse
 * @param sigCrypto
 * @param callbackHandler
 * @throws WSSecurityException
 */
public void validateSamlResponse(
    org.opensaml.saml.saml1.core.Response samlResponse,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    // Check the Status Code
    if (samlResponse.getStatus() == null
        || samlResponse.getStatus().getStatusCode() == null
        || samlResponse.getStatus().getStatusCode().getValue() == null) {
        LOG.warning("Either the SAML Response Status or StatusCode is null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    String statusValue = samlResponse.getStatus().getStatusCode().getValue().getLocalPart();
    if (!SAML1_STATUSCODE_SUCCESS.equals(statusValue)) {
        LOG.warning(
            "SAML Status code of " + samlResponse.getStatus().getStatusCode().getValue()
            + "does not equal " + SAML1_STATUSCODE_SUCCESS
        );
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (samlResponse.getIssueInstant() != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(futureTTL);
        if (samlResponse.getIssueInstant().isAfter(currentTime)) {
            LOG.warning("SAML Response IssueInstant not met");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
    }

    if (SAMLVersion.VERSION_11 != samlResponse.getVersion()) {
        LOG.warning(
            "SAML Version of " + samlResponse.getVersion()
            + "does not equal " + SAMLVersion.VERSION_11
        );
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    validateResponseSignature(samlResponse, sigCrypto, callbackHandler);

    // Validate Assertions
    for (org.opensaml.saml.saml1.core.Assertion assertion : samlResponse.getAssertions()) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion);
        validateAssertion(
            wrapper, sigCrypto, callbackHandler, samlResponse.getDOM().getOwnerDocument(),
            samlResponse.isSigned()
        );
    }
}
 
Example 20
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testModifiedSignature() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);
    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    // Change IssueInstant attribute
    String issueInstance = token.getAttributeNS(null, "IssueInstant");
    DateTime issueDateTime = new DateTime(issueInstance, DateTimeZone.UTC);
    issueDateTime = issueDateTime.plusSeconds(1);
    token.setAttributeNS(null, "IssueInstant", issueDateTime.toString());

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                   FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                               FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    String rstr = DOM2Writer.nodeToString(doc);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on signature validation");
    } catch (ProcessingException ex) {
        // expected
    }
}