Example usage for org.joda.time DateTime plusMinutes

List of usage examples for org.joda.time DateTime plusMinutes

Introduction

In this page you can find the example usage for org.joda.time DateTime plusMinutes.

Prototype

public DateTime plusMinutes(int minutes) 

Source Link

Document

Returns a copy of this datetime plus the specified number of minutes.

Usage

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder.java

License:EUPL

public static LogoutRequest buildSLORequestMessage(SLOInformationImpl sloInfo)
        throws ConfigurationException, MOAIDException {
    LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class);

    SecureRandomIdentifierGenerator gen;
    try {/*from   w ww.j  av  a  2s . co m*/
        gen = new SecureRandomIdentifierGenerator();
        sloReq.setID(gen.generateIdentifier());

    } catch (NoSuchAlgorithmException e) {
        Logger.error("Internal server error", e);
        throw new AuthenticationException("pvp2.13", new Object[] {});

    }

    DateTime now = new DateTime();
    Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);
    issuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath());
    issuer.setFormat(NameID.ENTITY);
    sloReq.setIssuer(issuer);
    sloReq.setIssueInstant(now);
    sloReq.setNotOnOrAfter(now.plusMinutes(5));

    sloReq.setDestination(sloInfo.getServiceURL());

    NameID nameID = SAML2Utils.createSAMLObject(NameID.class);
    nameID.setFormat(sloInfo.getUserNameIDFormat());
    nameID.setValue(sloInfo.getUserNameIdentifier());
    sloReq.setNameID(nameID);

    return sloReq;
}

From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java

License:Apache License

private void addListing(ChannelListings channelListings, Config config, ChannelConfig channelConfig,
        String channelTag, DateTime from, DateTime to) {
    StopWatch watch = new StopWatch();
    watch.start();//from ww w .  j av  a 2 s.  c o m
    List<Event> events = getEvents(config, channelTag, from, to);
    LOGGER.debug("Found {} events between {} and {}", events.size(), from, to);
    for (Event event : events) {
        ProgrammeDetail programmeDetails;
        LOGGER.debug("Processing event id {}", event.getEventId());
        DateTime scheduleDate = new DateTime(event.getScheduledDate());
        if (scheduleDate.plusMinutes(event.getDuration()).isAfterNow()
                && scheduleDate.isBefore(from.plusDays(config.getSynopsis()))) {
            LOGGER.debug("Fetching detailed synopsis for {}", event.getEventId());
            try {
                EventDetails eventDetails = getForObject(DETAILS_URI, EventDetails.class, event.getEventId(),
                        config.getRegionId());
                programmeDetails = createProgrammeDetails(eventDetails.getEvent());
            } catch (Exception e) {
                LOGGER.debug("Failed to get detailed synopsis. Using basic details instead.");
                programmeDetails = createProgrammeDetails(event);
            }
        } else {
            programmeDetails = createProgrammeDetails(event);
        }
        channelListings.addProgram(channelConfig.getId(), programmeDetails);
    }
    watch.stop();
    String numberOfPrograms = String.valueOf(channelListings.getNumberOfPrograms(channelConfig.getId()));
    LOGGER.info("{} {} events [took {}]", rightPad(channelConfig.getId() + " - " + channelConfig.getName(), 40),
            leftPad(numberOfPrograms, 4), formatDurationWords(watch.getTime()));
}

From source file:awslabs.lab21.StudentCode.java

License:Open Source License

/**
 * Create and return a pre-signed URL for the specified item. Set the URL to expire one hour from the 
 * moment it was generated.//from   ww w  . j av a  2s .com
 * Hint: Use the generatePresignedUrl() method of the client object.
 * 
 * @param s3Client    The S3 client object.   
 * @param bucketName The name of the bucket containing the object.
 * @param key    The key used to identify the object.
 * @return        The pre-signed URL for the object.
 */
@Override
public String generatePreSignedUrl(AmazonS3 s3Client, String bucketName, String key) {
    //TODO: Replace this call to the super class with your own implementation of the method.
    DateTime dt = new DateTime();
    URL preSignedURL = s3Client.generatePresignedUrl(bucketName, key, dt.plusMinutes(30).toDate());
    System.out.println(preSignedURL);
    return preSignedURL.toString();
}

From source file:be.e_contract.dssp.client.PendingRequestFactory.java

License:Open Source License

/**
 * Creates the base64 encoded dss:PendingRequest element to be used for the
 * Browser POST phase./*from  www  . j  a v a2s  .c om*/
 * 
 * <p>
 * The content of the parameter {@code authorizedSubjects} can be
 * constructed as follows. The {@code authorizedSubjects} parameter is a set
 * of regular expressions. Suppose you have a national registration number
 * that is allowed to sign, then you can construct the
 * {@code authorizedSubjects} as follows.
 * </p>
 * 
 * <pre>
 * Set&lt;String&gt; authorizedSubjects = new HashSet&lt;String&gt;();
 * String nrn = &quot;1234&quot;;
 * X500Principal x500Principal = new X500Principal(&quot;SERIALNUMBER=&quot; + nrn);
 * String authorizedSubject = x500Principal.getName() + &quot;,.*,C=BE&quot;;
 * authorizedSubjects.add(authorizedSubject);
 * </pre>
 * 
 * @param session
 *            the session object.
 * @param destination
 *            the destination URL within your web application. This is where
 *            the DSS will return to.
 * @param language
 *            the optional language
 * @param visibleSignatureConfiguration
 *            the optional visible signature configuration.
 * @param returnSignerIdentity
 *            indicates whether the DSS should return the signatory's
 *            identity.
 * @param authorizedSubjects
 *            the optional signatory subject DNs that are authorized to
 *            sign. An authorized subject can be an regular expression.
 * @return
 * @see VisibleSignatureConfiguration
 */
public static String createPendingRequest(DigitalSignatureServiceSession session, String destination,
        String language, VisibleSignatureConfiguration visibleSignatureConfiguration,
        boolean returnSignerIdentity, Set<String> authorizedSubjects) {
    ObjectFactory asyncObjectFactory = new ObjectFactory();
    be.e_contract.dssp.ws.jaxb.dss.ObjectFactory dssObjectFactory = new be.e_contract.dssp.ws.jaxb.dss.ObjectFactory();
    be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory wsaObjectFactory = new be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory();
    be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory wsuObjectFactory = new be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory();
    be.e_contract.dssp.ws.jaxb.dss.vs.ObjectFactory vsObjectFactory = new be.e_contract.dssp.ws.jaxb.dss.vs.ObjectFactory();
    be.e_contract.dssp.ws.jaxb.xacml.policy.ObjectFactory xacmlObjectFactory = new be.e_contract.dssp.ws.jaxb.xacml.policy.ObjectFactory();

    PendingRequest pendingRequest = asyncObjectFactory.createPendingRequest();
    pendingRequest.setProfile(DigitalSignatureServiceConstants.PROFILE);
    AnyType optionalInputs = dssObjectFactory.createAnyType();
    pendingRequest.setOptionalInputs(optionalInputs);

    optionalInputs.getAny()
            .add(dssObjectFactory.createAdditionalProfile(DigitalSignatureServiceConstants.DSS_ASYNC_PROFILE));
    optionalInputs.getAny().add(asyncObjectFactory.createResponseID(session.getResponseId()));

    if (null != language) {
        optionalInputs.getAny().add(dssObjectFactory.createLanguage(language));
    }

    if (returnSignerIdentity) {
        optionalInputs.getAny().add(dssObjectFactory.createReturnSignerIdentity(null));
    }

    AttributedURIType messageId = wsaObjectFactory.createAttributedURIType();
    optionalInputs.getAny().add(wsaObjectFactory.createMessageID(messageId));
    String requestId = "uuid:" + UUID.randomUUID().toString();
    messageId.setValue(requestId);
    session.setInResponseTo(requestId);

    TimestampType timestamp = wsuObjectFactory.createTimestampType();
    optionalInputs.getAny().add(wsuObjectFactory.createTimestamp(timestamp));
    AttributedDateTime created = wsuObjectFactory.createAttributedDateTime();
    timestamp.setCreated(created);
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime()
            .withChronology(ISOChronology.getInstanceUTC());
    DateTime createdDateTime = new DateTime();
    created.setValue(dateTimeFormatter.print(createdDateTime));
    AttributedDateTime expires = wsuObjectFactory.createAttributedDateTime();
    timestamp.setExpires(expires);
    DateTime expiresDateTime = createdDateTime.plusMinutes(5);
    expires.setValue(dateTimeFormatter.print(expiresDateTime));

    EndpointReferenceType replyTo = wsaObjectFactory.createEndpointReferenceType();
    optionalInputs.getAny().add(wsaObjectFactory.createReplyTo(replyTo));
    AttributedURIType address = wsaObjectFactory.createAttributedURIType();
    replyTo.setAddress(address);
    address.setValue(destination);
    session.setDestination(destination);

    if (null != visibleSignatureConfiguration) {
        VisibleSignatureConfigurationType visSigConfig = vsObjectFactory
                .createVisibleSignatureConfigurationType();
        optionalInputs.getAny().add(vsObjectFactory.createVisibleSignatureConfiguration(visSigConfig));
        VisibleSignaturePolicyType visibleSignaturePolicy = VisibleSignaturePolicyType.DOCUMENT_SUBMISSION_POLICY;
        visSigConfig.setVisibleSignaturePolicy(visibleSignaturePolicy);
        VisibleSignatureItemsConfigurationType visibleSignatureItemsConfiguration = vsObjectFactory
                .createVisibleSignatureItemsConfigurationType();
        visSigConfig.setVisibleSignatureItemsConfiguration(visibleSignatureItemsConfiguration);
        if (visibleSignatureConfiguration.getLocation() != null) {
            VisibleSignatureItemType locationVisibleSignatureItem = vsObjectFactory
                    .createVisibleSignatureItemType();
            visibleSignatureItemsConfiguration.getVisibleSignatureItem().add(locationVisibleSignatureItem);
            locationVisibleSignatureItem.setItemName(ItemNameEnum.SIGNATURE_PRODUCTION_PLACE);
            ItemValueStringType itemValue = vsObjectFactory.createItemValueStringType();
            locationVisibleSignatureItem.setItemValue(itemValue);
            itemValue.setItemValue(visibleSignatureConfiguration.getLocation());
        }
        if (visibleSignatureConfiguration.getRole() != null) {
            VisibleSignatureItemType locationVisibleSignatureItem = vsObjectFactory
                    .createVisibleSignatureItemType();
            visibleSignatureItemsConfiguration.getVisibleSignatureItem().add(locationVisibleSignatureItem);
            locationVisibleSignatureItem.setItemName(ItemNameEnum.SIGNATURE_REASON);
            ItemValueStringType itemValue = vsObjectFactory.createItemValueStringType();
            locationVisibleSignatureItem.setItemValue(itemValue);
            itemValue.setItemValue(visibleSignatureConfiguration.getRole());
        }
        if (visibleSignatureConfiguration.getSignerImageUri() != null) {
            PixelVisibleSignaturePositionType visibleSignaturePosition = vsObjectFactory
                    .createPixelVisibleSignaturePositionType();
            visSigConfig.setVisibleSignaturePosition(visibleSignaturePosition);
            visibleSignaturePosition.setPageNumber(BigInteger.valueOf(visibleSignatureConfiguration.getPage()));
            visibleSignaturePosition.setX(BigInteger.valueOf(visibleSignatureConfiguration.getX()));
            visibleSignaturePosition.setY(BigInteger.valueOf(visibleSignatureConfiguration.getY()));

            VisibleSignatureItemType visibleSignatureItem = vsObjectFactory.createVisibleSignatureItemType();
            visibleSignatureItemsConfiguration.getVisibleSignatureItem().add(visibleSignatureItem);
            visibleSignatureItem.setItemName(ItemNameEnum.SIGNER_IMAGE);
            ItemValueURIType itemValue = vsObjectFactory.createItemValueURIType();
            itemValue.setItemValue(visibleSignatureConfiguration.getSignerImageUri());
            visibleSignatureItem.setItemValue(itemValue);
        }
        if (visibleSignatureConfiguration.getCustomText() != null) {
            VisibleSignatureItemType customTextVisibleSignatureItem = vsObjectFactory
                    .createVisibleSignatureItemType();
            visibleSignatureItemsConfiguration.getVisibleSignatureItem().add(customTextVisibleSignatureItem);
            customTextVisibleSignatureItem.setItemName(ItemNameEnum.CUSTOM_TEXT);
            ItemValueStringType itemValue = vsObjectFactory.createItemValueStringType();
            customTextVisibleSignatureItem.setItemValue(itemValue);
            itemValue.setItemValue(visibleSignatureConfiguration.getCustomText());
        }
    }

    if (null != authorizedSubjects) {
        PolicyType policy = xacmlObjectFactory.createPolicyType();
        optionalInputs.getAny().add(xacmlObjectFactory.createPolicy(policy));
        policy.setPolicyId("urn:" + UUID.randomUUID().toString());
        policy.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides");
        TargetType target = xacmlObjectFactory.createTargetType();
        policy.setTarget(target);
        RuleType rule = xacmlObjectFactory.createRuleType();
        policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
        rule.setRuleId("whatever");
        rule.setEffect(EffectType.PERMIT);
        TargetType ruleTarget = xacmlObjectFactory.createTargetType();
        rule.setTarget(ruleTarget);
        SubjectsType subjects = xacmlObjectFactory.createSubjectsType();
        ruleTarget.setSubjects(subjects);
        for (String authorizedSubject : authorizedSubjects) {
            SubjectType subject = xacmlObjectFactory.createSubjectType();
            subjects.getSubject().add(subject);
            SubjectMatchType subjectMatch = xacmlObjectFactory.createSubjectMatchType();
            subject.getSubjectMatch().add(subjectMatch);
            subjectMatch.setMatchId("urn:oasis:names:tc:xacml:2.0:function:x500Name-regexp-match");
            AttributeValueType attributeValue = xacmlObjectFactory.createAttributeValueType();
            subjectMatch.setAttributeValue(attributeValue);
            attributeValue.setDataType("http://www.w3.org/2001/XMLSchema#string");
            attributeValue.getContent().add(authorizedSubject);
            SubjectAttributeDesignatorType subjectAttributeDesigator = xacmlObjectFactory
                    .createSubjectAttributeDesignatorType();
            subjectMatch.setSubjectAttributeDesignator(subjectAttributeDesigator);
            subjectAttributeDesigator.setAttributeId("urn:oasis:names:tc:xacml:1.0:subject:subject-id");
            subjectAttributeDesigator.setDataType("urn:oasis:names:tc:xacml:1.0:data-type:x500Name");
        }
        ResourcesType resources = xacmlObjectFactory.createResourcesType();
        ruleTarget.setResources(resources);
        ResourceType resource = xacmlObjectFactory.createResourceType();
        resources.getResource().add(resource);
        ResourceMatchType resourceMatch = xacmlObjectFactory.createResourceMatchType();
        resource.getResourceMatch().add(resourceMatch);
        resourceMatch.setMatchId("urn:oasis:names:tc:xacml:1.0:function:anyURI-equal");
        AttributeValueType resourceAttributeValue = xacmlObjectFactory.createAttributeValueType();
        resourceMatch.setAttributeValue(resourceAttributeValue);
        resourceAttributeValue.setDataType("http://www.w3.org/2001/XMLSchema#anyURI");
        resourceAttributeValue.getContent().add("urn:be:e-contract:dss");
        AttributeDesignatorType resourceAttributeDesignator = xacmlObjectFactory
                .createAttributeDesignatorType();
        resourceMatch.setResourceAttributeDesignator(resourceAttributeDesignator);
        resourceAttributeDesignator.setAttributeId("urn:oasis:names:tc:xacml:1.0:resource:resource-id");
        resourceAttributeDesignator.setDataType("http://www.w3.org/2001/XMLSchema#anyURI");

        ActionsType actions = xacmlObjectFactory.createActionsType();
        ruleTarget.setActions(actions);
        ActionType action = xacmlObjectFactory.createActionType();
        actions.getAction().add(action);
        ActionMatchType actionMatch = xacmlObjectFactory.createActionMatchType();
        action.getActionMatch().add(actionMatch);
        actionMatch.setMatchId("urn:oasis:names:tc:xacml:1.0:function:string-equal");
        AttributeValueType actionAttributeValue = xacmlObjectFactory.createAttributeValueType();
        actionMatch.setAttributeValue(actionAttributeValue);
        actionAttributeValue.setDataType("http://www.w3.org/2001/XMLSchema#string");
        actionAttributeValue.getContent().add("sign");
        AttributeDesignatorType actionAttributeDesignator = xacmlObjectFactory.createAttributeDesignatorType();
        actionMatch.setActionAttributeDesignator(actionAttributeDesignator);
        actionAttributeDesignator.setAttributeId("urn:oasis:names:tc:xacml:1.0:action:action-id");
        actionAttributeDesignator.setDataType("http://www.w3.org/2001/XMLSchema#string");
    }

    // marshall to DOM
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    Document document = documentBuilder.newDocument();

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
                be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
                be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class,
                be.e_contract.dssp.ws.jaxb.dss.vs.ObjectFactory.class,
                be.e_contract.dssp.ws.jaxb.xacml.policy.ObjectFactory.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(pendingRequest, document);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    try {
        sign(document, session);
    } catch (Exception e) {
        throw new RuntimeException("error signing: " + e.getMessage(), e);
    }

    // marshall to base64 encoded
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("JAXP config error: " + e.getMessage(), e);
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (TransformerException e) {
        throw new RuntimeException("JAXP error: " + e.getMessage(), e);
    }
    String encodedPendingRequest = Base64.encode(outputStream.toByteArray());
    return encodedPendingRequest;
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

License:Open Source License

/**
 * Construct an unsigned SAML v2.0 Assertion
 * /*from w w w. ja  v  a  2 s  .  c o  m*/
 * @param issuerName
 *            assertion issuer
 * @param inResponseTo
 *            optional inResponseTo
 * @param audienceUri
 *            audience in audience restriction
 * @param recipient
 *            recipient (SubjectConfirmationData.recipient)
 * @param tokenValidity
 *            valitity in minutes of the assertion
 * @param issueInstant
 *            time of issuance
 * @param authenticationPolicy
 *            authentication policy
 * @param userId
 *            user ID
 * @param attributes
 *            map of user's attributes
 * @param secretKey
 *            optional symmetric SecretKey used for encryption
 * @param publicKey
 *            optional RSA public key used for encryption
 * @return the unsigned SAML v2.0 assertion.
 */
public static Assertion getAssertion(String issuerName, String inResponseTo, String audienceUri,
        String recipient, Integer tokenValidity, DateTime issueInstant,
        SamlAuthenticationPolicy authenticationPolicy, String userId,
        Map<String, be.fedict.eid.idp.common.Attribute> attributes, SecretKey secretKey, PublicKey publicKey) {

    int validity = 5;
    if (null != tokenValidity && tokenValidity > 0) {
        validity = tokenValidity;
    }

    Assertion assertion = buildXMLObject(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
    assertion.setVersion(SAMLVersion.VERSION_20);
    String assertionId = "assertion-" + UUID.randomUUID().toString();
    assertion.setID(assertionId);
    assertion.setIssueInstant(issueInstant);

    // issuer
    Issuer issuer = buildXMLObject(Issuer.class, Issuer.DEFAULT_ELEMENT_NAME);
    assertion.setIssuer(issuer);
    issuer.setValue(issuerName);

    // conditions
    Conditions conditions = buildXMLObject(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
    assertion.setConditions(conditions);
    DateTime notAfter = issueInstant.plusMinutes(validity);
    conditions.setNotBefore(issueInstant);
    conditions.setNotOnOrAfter(notAfter);

    if (null != inResponseTo) {
        conditions.getConditions()
                .add(Saml2Util.buildXMLObject(OneTimeUse.class, OneTimeUse.DEFAULT_ELEMENT_NAME));
    }

    // audience restriction
    List<AudienceRestriction> audienceRestrictionList = conditions.getAudienceRestrictions();
    AudienceRestriction audienceRestriction = buildXMLObject(AudienceRestriction.class,
            AudienceRestriction.DEFAULT_ELEMENT_NAME);
    audienceRestrictionList.add(audienceRestriction);
    List<Audience> audiences = audienceRestriction.getAudiences();
    Audience audience = buildXMLObject(Audience.class, Audience.DEFAULT_ELEMENT_NAME);
    audiences.add(audience);
    audience.setAudienceURI(audienceUri);

    // subject
    Subject subject = buildXMLObject(Subject.class, Subject.DEFAULT_ELEMENT_NAME);
    assertion.setSubject(subject);
    NameID nameId = buildXMLObject(NameID.class, NameID.DEFAULT_ELEMENT_NAME);
    subject.setNameID(nameId);
    nameId.setValue(userId);

    // subject confirmation
    List<SubjectConfirmation> subjectConfirmations = subject.getSubjectConfirmations();
    SubjectConfirmation subjectConfirmation = buildXMLObject(SubjectConfirmation.class,
            SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    subjectConfirmations.add(subjectConfirmation);
    subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
    if (null != inResponseTo) {
        SubjectConfirmationData subjectConfirmationData = buildXMLObject(SubjectConfirmationData.class,
                SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
        subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);
        subjectConfirmationData.setRecipient(recipient);
        subjectConfirmationData.setInResponseTo(inResponseTo);
        subjectConfirmationData.setNotBefore(issueInstant);
        subjectConfirmationData.setNotOnOrAfter(notAfter);
    }

    // authentication statement
    List<AuthnStatement> authnStatements = assertion.getAuthnStatements();
    AuthnStatement authnStatement = buildXMLObject(AuthnStatement.class, AuthnStatement.DEFAULT_ELEMENT_NAME);
    authnStatements.add(authnStatement);
    authnStatement.setAuthnInstant(issueInstant);
    AuthnContext authnContext = buildXMLObject(AuthnContext.class, AuthnContext.DEFAULT_ELEMENT_NAME);
    authnStatement.setAuthnContext(authnContext);

    AuthnContextClassRef authnContextClassRef = buildXMLObject(AuthnContextClassRef.class,
            AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    authnContextClassRef.setAuthnContextClassRef(authenticationPolicy.getUri());
    authnContext.setAuthnContextClassRef(authnContextClassRef);

    // attribute statement
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    AttributeStatement attributeStatement = buildXMLObject(AttributeStatement.class,
            AttributeStatement.DEFAULT_ELEMENT_NAME);
    attributeStatements.add(attributeStatement);

    // get encryptor if needed
    Encrypter encrypter = getEncrypter(secretKey, publicKey);

    for (Map.Entry<String, be.fedict.eid.idp.common.Attribute> attributeEntry : attributes.entrySet()) {

        addAttribute(attributeEntry.getValue(), attributeStatement, encrypter);
    }

    return assertion;
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

License:Open Source License

private static void validateTime(DateTime now, DateTime notBefore, DateTime notOnOrAfter, int maxTimeOffset)
        throws AssertionValidationException {

    LOG.debug("now: " + now.toString());
    LOG.debug("notBefore: " + notBefore.toString());
    LOG.debug("notOnOrAfter : " + notOnOrAfter.toString());

    if (maxTimeOffset >= 0) {
        if (now.isBefore(notBefore)) {
            // time skew
            if (now.plusMinutes(maxTimeOffset).isBefore(notBefore)
                    || now.minusMinutes(maxTimeOffset).isAfter(notOnOrAfter)) {
                throw new AssertionValidationException(
                        "SAML2 assertion validation: invalid SAML message timeframe");
            }/*  w w  w.j  a v a 2  s.  c  o  m*/
        } else if (now.isBefore(notBefore) || now.isAfter(notOnOrAfter)) {
            throw new AssertionValidationException(
                    "SAML2 assertion validation: invalid SAML message timeframe");
        }
    }
}

From source file:calculadora.CalculadoraDeHoras.java

License:Apache License

public Tempo quantidadeDeHoras(DateTime dataInicial, DateTime dataFinal, Janela janela) {

    long horasTrabalhadas = 0;

    int minutosDaHoraInicial = 0;
    int minutosDaHoraFinal = 0;

    if (forDiferente(dataInicial, dataFinal)) {
        minutosDaHoraInicial = tratarMinutosIniciais(dataInicial, janela);
        minutosDaHoraFinal = tratarMinutosFinais(dataFinal, janela);
    } else {//from www  . ja v  a2 s .  co  m
        minutosDaHoraInicial = dataFinal.getMinuteOfHour();
        minutosDaHoraFinal = dataInicial.getMinuteOfHour() * -1;
    }

    dataInicial = dataInicial.plusMinutes(minutosDaHoraInicial);

    while (forDiferente(dataInicial, dataFinal) && dataInicial.isBefore(dataFinal)) {

        if (janela.estaDentro(dataInicial)) {
            horasTrabalhadas++;
        }

        dataInicial = dataInicial.plusHours(1);

    }

    return criarTempo(horasTrabalhadas, minutosDaHoraInicial, minutosDaHoraFinal);
}

From source file:ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ExtendedAttributeQueryBuilder.java

License:MIT License

/**
 * Builds a complete, extended SAML attribute query with included
 * authentication statement, both of them signed, serialized to String.
 * Overrides the method from MessageBuilder.
 *
 * @return Serialized extended attribute query as String
 * @throws ConfigurationException//w  ww . ja v  a2s  .  c  o m
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws UnrecoverableEntryException
 * @throws SecurityException
 * @throws MarshallingException
 * @throws SignatureException
 * @throws TransformerException
 * @throws XMLParserException
 */
@Override
public String build() throws ConfigurationException, NoSuchAlgorithmException, IOException, KeyStoreException,
        CertificateException, UnrecoverableEntryException, SecurityException, MarshallingException,
        SignatureException, XMLParserException, TransformerException {
    logger.debug("Starting generation of extended attribute query...");

    //////////////////// Perform initial setup
    DefaultBootstrap.bootstrap();
    final SecureRandomIdentifierGenerator idGenerator = new SecureRandomIdentifierGenerator();

    final DateTime queryTime = DateTime.now();
    final DateTime authnIssueTime = queryTime.minusMinutes(4);
    final DateTime authnNotBeforeTime = queryTime.minusMinutes(5);
    final DateTime authnNotAfterTime = queryTime.plusMinutes(5);

    //////////////////// The outer AttributeQuery
    final AttributeQuery query = (AttributeQuery) buildXMLObject(AttributeQuery.DEFAULT_ELEMENT_NAME);
    query.setID(idGenerator.generateIdentifier());
    query.setVersion(SAMLVersion.VERSION_20);
    query.setIssueInstant(queryTime);
    query.setSubject(null);
    query.setDestination(config.getSAMLDestination());

    // Issuer of the AttributeQuery
    final Issuer queryIssuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
    queryIssuer.setValue(config.getSAMLIssuer());
    query.setIssuer(queryIssuer);

    // Subject of the AttributeQuery
    final Subject querySubject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    query.setSubject(querySubject);

    // --> NameID of the Subject
    NameID queryNameID = (NameID) buildXMLObject(NameID.DEFAULT_ELEMENT_NAME);
    queryNameID.setFormat(config.getSAMLNameIDFormat());
    queryNameID.setValue(config.getSAMLNameID());
    querySubject.setNameID(queryNameID);

    // Attributes of the AttributeQuery
    for (String[] attr : attributes) {
        Attribute attribute = (Attribute) buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
        attribute.setName(attr[0]);
        if (attr.length >= 2) {
            attribute.setNameFormat(attr[1]);
        }
        if (attr.length >= 3) {
            attribute.setFriendlyName(attr[2]);
        }
        query.getAttributes().add(attribute);
    }

    //////////////////// The Assertion added to the Extensions of the above query
    Assertion assertion = (Assertion) buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
    assertion.setID(idGenerator.generateIdentifier());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(authnIssueTime);

    // --> Issuer of the Assertion
    Issuer assertionIssuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
    assertionIssuer.setValue(config.getSAMLIssuer());
    assertion.setIssuer(assertionIssuer);

    // --> Subject of the Assertion
    Subject assertionSubject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    assertion.setSubject(assertionSubject);

    // --> -->  NameID for the Subject of the Assertion
    NameID assertionNameID = (NameID) buildXMLObject(NameID.DEFAULT_ELEMENT_NAME);
    assertionNameID.setFormat(config.getSAMLNameIDFormat());
    assertionNameID.setValue(config.getSAMLNameID());
    assertionSubject.setNameID(assertionNameID);

    // --> -->  SubjectConfirmation for the Subject of the Assertion
    SubjectConfirmation assertionSubjectConfirmation = (SubjectConfirmation) buildXMLObject(
            SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    assertionSubjectConfirmation.setMethod(config.getSAMLSubjectConfirmationMethod());
    assertionSubject.getSubjectConfirmations().add(assertionSubjectConfirmation);

    // --> Conditions for the Assertion
    Conditions conditions = (Conditions) buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(authnNotBeforeTime);
    conditions.setNotOnOrAfter(authnNotAfterTime);
    assertion.setConditions(conditions);

    // --> --> AudienceRestriction for the Conditions
    AudienceRestriction audienceRestriction = (AudienceRestriction) buildXMLObject(
            AudienceRestriction.DEFAULT_ELEMENT_NAME);
    conditions.getAudienceRestrictions().add(audienceRestriction);

    // --> --> --> Audience for the AudienceRestriction
    Audience audience = (Audience) buildXMLObject(Audience.DEFAULT_ELEMENT_NAME);
    audience.setAudienceURI(config.getSAMLIssuer());
    audienceRestriction.getAudiences().add(audience);

    // --> AuthnStatement for the Assertion
    AuthnStatement authnStatement = (AuthnStatement) buildXMLObject(AuthnStatement.DEFAULT_ELEMENT_NAME);
    authnStatement.setAuthnInstant(authnIssueTime);
    assertion.getAuthnStatements().add(authnStatement);

    // -->-->  AuthnContext for the AuthnStatement
    AuthnContext authnContext = (AuthnContext) buildXMLObject(AuthnContext.DEFAULT_ELEMENT_NAME);
    authnStatement.setAuthnContext(authnContext);

    // --> -->-->  AuthnContextClassRef for AuthnContext
    AuthnContextClassRef authnContextClassRef = (AuthnContextClassRef) buildXMLObject(
            AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    authnContextClassRef.setAuthnContextClassRef(config.getSAMLAssuranceLevel());
    authnContext.setAuthnContextClassRef(authnContextClassRef);

    //////////////////// Sign the assertion and add it to the query
    Credential signingCredential = StiamConfiguration.getInstance().getSignatureCredential();
    Signature assertionSignature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    assertionSignature.setSigningCredential(signingCredential);
    SecurityHelper.prepareSignatureParams(assertionSignature, signingCredential, null, null);
    assertion.setSignature(assertionSignature);
    Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);
    Signer.signObject(assertionSignature);

    // Extensions of the AttributeQuery
    // Manually build the correct QName, otherwise "md"-namespace gets marshalled...
    // see https://groups.google.com/forum/#!topic/opensaml-users/FFCQ48uqw3o for details.
    QName name = new QName(SAMLConstants.SAML20P_NS, Extensions.LOCAL_NAME, SAMLConstants.SAML20P_PREFIX);
    Extensions extensions = (Extensions) Configuration.getBuilderFactory().getBuilder(name).buildObject(name);
    extensions.getUnknownXMLObjects().add(assertion);
    query.setExtensions(extensions);

    //////////////////// Sign the query
    Signature querySignature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    querySignature.setSigningCredential(signingCredential);
    SecurityHelper.prepareSignatureParams(querySignature, signingCredential, null, null);
    query.setSignature(querySignature);
    Configuration.getMarshallerFactory().getMarshaller(query).marshall(query);
    Signer.signObject(querySignature);

    logger.debug("Extended attribute query generated!");
    return marshallToString(query);
}

From source file:ch.emad.business.schuetu.BusinessImpl.java

License:Apache License

private List<SpielZeile> createZeilen(DateTime startIn, final boolean sonntag) {
    DateTime start = startIn;

    final int millis = start.getMillisOfDay();

    start = start.minusMillis(millis);/*from  w ww . ja va 2  s. c  o m*/

    start = start.plusHours(8);

    final DateTime end = start.plusHours(11);

    final List<SpielZeile> zeilen = new ArrayList<SpielZeile>();
    while (start.isBefore(end.getMillis())) {
        final SpielZeile zeile = new SpielZeile();

        if (start.getHourOfDay() == 8) {
            zeile.setPause(true);
        }

        if (start.getHourOfDay() == MITTAG) {
            zeile.setPause(true);
        }

        if ((start.getHourOfDay() > MITTAG) && sonntag) {
            zeile.setFinale(true);
        }

        // wunsch enum wird gesetzt um spaeter die kategorie gegenpruefen zu koennen
        if (sonntag && (start.getHourOfDay() <= MITTAG)) {
            zeile.setSpieltageszeit(SpielTageszeit.SONNTAGMORGEN);
        }
        if (!sonntag && (start.getHourOfDay() < MITTAG)) {
            zeile.setSpieltageszeit(SpielTageszeit.SAMSTAGMORGEN);
        }
        if (!sonntag && (start.getHourOfDay() > MITTAG)) {
            zeile.setSpieltageszeit(SpielTageszeit.SAMSTAGNACHMITTAG);
        }

        zeile.setStart(start.toDate());
        zeilen.add(zeile);

        final DateTimeZone zone = start.getZone();
        BusinessImpl.LOG.info("zone: " + zone + " date: " + start.toDate());

        zeile.setSonntag(sonntag);

        start = start.plusMinutes(
                this.getSpielEinstellungen().getPause() + this.getSpielEinstellungen().getSpiellaenge());
    }
    return zeilen;
}

From source file:ch.emad.web.schuetu.modelwrapper.SpielBusiness.java

License:Apache License

public SpieleContainer getSpielzeilen() {

    DateTime start = new DateTime(business.getSpielEinstellungen().getStarttag());

    start = start.plusHours(7);/*  w  ww  .  ja  v  a2 s .  c o m*/
    DateTime end = start.plusHours(12);

    List<SpielZeile> zeilen = new ArrayList<SpielZeile>();
    while (start.isBefore(end.getMillis())) {
        SpielZeile zeile = new SpielZeile();
        zeile.setStart(start.toDate());
        zeilen.add(zeile);

        start = start.plusMinutes(business.getSpielEinstellungen().getPause()
                + business.getSpielEinstellungen().getSpiellaenge());

    }
    SpieleContainer c = new SpieleContainer();
    c.setSelectedZeilen(zeilen.toArray());
    return c;
}