Example usage for org.joda.time DateTime plusHours

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

Introduction

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

Prototype

public DateTime plusHours(int hours) 

Source Link

Document

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

Usage

From source file:DDTDate.java

License:Apache License

public MutableDateTime getReferenceDateAdjustedForTimeZone() {
    DateTime result = getReferenceDate().toDateTime();
    int timeZoneAdjustmentInHours = DDTSettings.Settings().getTimeZoneAdjustmentInHours();
    result = result.plusHours(timeZoneAdjustmentInHours);
    return result.toMutableDateTime();
}

From source file:DDTDate.java

License:Apache License

/**
 * Initializes the instance's referenceDate with the 'Server' date (datetime stamp adjusted by timezone adjustment)
 *//*from   w  ww  . j a v a  2 s .c  om*/
private void initializeReferenceDate() {
    initializeLocale();
    DateTime result = new DateTime();
    int timeZoneAdjustmentInHours = DDTSettings.Settings().getTimeZoneAdjustmentInHours();
    setReferenceDate(result.plusHours(timeZoneAdjustmentInHours).toMutableDateTime());
}

From source file:aplicacion.control.util.Fechas.java

public static String differenceBetweenHours(Time time1, Time time2) {
    DateTime dateTime1 = new DateTime(time1.getTime());
    dateTime1 = dateTime1.plus(1);/*  ww  w.j a  v a2s .  c o  m*/
    DateTime dateTime2 = new DateTime(time2.getTime());
    dateTime2 = dateTime2.plus(1);
    long c = dateTime2.getMillis() - dateTime1.getMillis();
    DateTime dateTime = new DateTime(c);
    dateTime = dateTime.plusHours(4);
    Time diff = new Time(dateTime.getMillis());
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    return formatter.format(getLocalFromTime(diff));
}

From source file:app.service.AuthService.java

License:Apache License

public int refreshExpireToken(CryptoToken cryptoToken, AccessResponse accessResponse) {
    AccountSession refreshSession = getSessionWithCheck(cryptoToken, false);
    if (refreshSession == null) {
        return ResultCode.INVALID_TOKEN;
    }/*  ww w.ja  v  a2 s . c  o  m*/

    // ? refreshToken
    DateTime now = DateTime.now();
    DateTime deadline = new DateTime(refreshSession.getRefreshTime());
    if (now.isAfter(deadline)) {
        return ResultCode.OVERDUE_TOKEN;
    }

    //  expireToken
    final long expireTime = now.plusHours(EXPIRE_TIME).getMillis();
    refreshSession.setExpireTime(expireTime);
    CryptoToken expireToken = newSessionToken(refreshSession, true);
    if (expireToken == null) {
        return ResultCode.ENCRYPT_TOKEN_FAILED;
    }

    accessResponse.setExpireTime(expireTime);
    accessResponse.setExpireToken(expireToken);
    return BaseResponse.COMMON_SUCCESS;
}

From source file:app.service.AuthService.java

License:Apache License

protected int refreshAccessResponse(String userId, AccessResponse accessResponse) {
    DateTime now = DateTime.now();
    final long expireTime = now.plusHours(EXPIRE_TIME).getMillis();
    final long refreshTime = now.plusDays(REFRESH_TIME).getMillis();

    AccountSession session = new AccountSession();
    session.setUserId(userId);/*  w w  w.j  a v a 2s  . com*/
    session.setExpireTime(expireTime);
    session.setRefreshTime(refreshTime);

    CryptoToken expireToken = newSessionToken(session, true);
    if (expireToken == null) {
        return ResultCode.ENCRYPT_TOKEN_FAILED;
    }

    CryptoToken refreshToken = newSessionToken(session, false);
    if (refreshToken == null) {
        return ResultCode.ENCRYPT_TOKEN_FAILED;
    }

    accessResponse.setExpireTime(expireTime);
    accessResponse.setExpireToken(expireToken);
    accessResponse.setRefreshTime(refreshTime);
    accessResponse.setRefreshToken(refreshToken);
    return BaseResponse.COMMON_SUCCESS;
}

From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.BuildMetadata.java

License:EUPL

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/*w  ww . j  a  va  2s.  c om*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ConfigurationProvider config = ConfigurationProvider.getInstance();

        //config.initializePVP2Login();

        SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator();

        EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class);

        DateTime date = new DateTime();
        spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS));

        String name = config.getPVP2MetadataEntitiesName();
        if (MiscUtil.isEmpty(name)) {
            log.info("NO Metadata EntitiesName configurated");
            throw new ConfigurationException("NO Metadata EntitiesName configurated");
        }

        spEntitiesDescriptor.setName(name);
        spEntitiesDescriptor.setID(idGen.generateIdentifier());

        EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class);

        spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS));

        spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";

        log.debug("Set OnlineApplicationURL to " + serviceURL);
        spEntityDescriptor.setEntityID(serviceURL);

        SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class);

        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.setWantAssertionsSigned(true);

        X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory();
        keyInfoFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance();

        KeyStore keyStore = config.getPVP2KeyStore();

        X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreMetadataKeyAlias(),
                config.getPVP2KeystoreMetadataKeyPassword().toCharArray());

        log.debug("Set Metadata key information");
        //Set MetaData Signing key
        KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        entitiesSignKeyDescriptor.setUse(UsageType.SIGNING);
        entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential));
        Signature entitiesSignature = getSignature(signingcredential);
        spEntitiesDescriptor.setSignature(entitiesSignature);

        //Set AuthRequest Signing certificate
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());
        KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        signKeyDescriptor.setUse(UsageType.SIGNING);
        signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential));
        spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);

        //set AuthRequest encryption certificate
        if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias())) {
            X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore,
                    config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(),
                    config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray());
            KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
            encryKeyDescriptor.setUse(UsageType.ENCRYPTION);
            encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential));
            spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor);

        } else {
            log.warn("No Assertion Encryption-Key defined. This setting is not recommended!");

        }

        NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        persistentnameIDFormat.setFormat(NameIDType.PERSISTENT);

        spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat);

        NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        transientnameIDFormat.setFormat(NameIDType.TRANSIENT);

        spSSODescriptor.getNameIDFormats().add(transientnameIDFormat);

        NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED);

        spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat);

        AssertionConsumerService postassertionConsumerService = SAML2Utils
                .createSAMLObject(AssertionConsumerService.class);

        postassertionConsumerService.setIndex(0);
        postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION);

        spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService);

        //add SLO services
        SingleLogoutService postBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        postBindingService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT);
        spSSODescriptor.getSingleLogoutServices().add(postBindingService);

        SingleLogoutService redirectBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        redirectBindingService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        redirectBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT);
        spSSODescriptor.getSingleLogoutServices().add(redirectBindingService);

        SingleLogoutService soapBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        soapBindingService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
        soapBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_BACK);
        spSSODescriptor.getSingleLogoutServices().add(soapBindingService);

        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

        spSSODescriptor.setWantAssertionsSigned(true);
        spSSODescriptor.setAuthnRequestsSigned(true);

        AttributeConsumingService attributeService = SAML2Utils
                .createSAMLObject(AttributeConsumingService.class);

        attributeService.setIndex(0);
        attributeService.setIsDefault(true);
        ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class);
        serviceName.setName(new LocalizedString("Default Service", "de"));
        attributeService.getNames().add(serviceName);

        attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes());

        spSSODescriptor.getAttributeConsumingServices().add(attributeService);

        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor);
        out.marshall(spEntitiesDescriptor, document);

        Signer.signObject(entitiesSignature);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, sr);
        sw.close();

        String metadataXML = sw.toString();

        response.setContentType("text/xml");
        response.getOutputStream().write(metadataXML.getBytes());

        response.getOutputStream().close();

    } catch (ConfigurationException e) {
        log.warn("Configuration can not be loaded.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (NoSuchAlgorithmException e) {
        log.warn("Requested Algorithm could not found.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (KeyStoreException e) {
        log.warn("Requested KeyStoreType is not implemented.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (CertificateException e) {
        log.warn("KeyStore can not be opend or userd.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (SecurityException e) {
        log.warn("KeyStore can not be opend or used", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (ParserConfigurationException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (MarshallingException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (SignatureException e) {
        log.warn("PVP2 Metadata can not be signed", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerConfigurationException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerFactoryConfigurationError e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

    catch (Exception e) {
        log.warn("Unspecific PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

}

From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.BuildMetadata.java

License:EUPL

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//  w  w  w.  j  a va 2  s .  c  om
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        Configuration config = Configuration.getInstance();

        SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator();

        EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class);

        DateTime date = new DateTime();
        spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS));

        String name = config.getPVP2MetadataEntitiesName();
        if (MiscUtil.isEmpty(name)) {
            Logger.info("NO Metadata EntitiesName configurated");
            throw new ConfigurationException("NO Metadata EntitiesName configurated");
        }

        spEntitiesDescriptor.setName(name);
        spEntitiesDescriptor.setID(idGen.generateIdentifier());

        //set period of validity for metadata information
        DateTime validUntil = new DateTime();
        spEntitiesDescriptor.setValidUntil(validUntil.plusDays(7));

        EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class);

        spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS));

        spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor);

        //set OA-ID (PublicURL Prefix) as identifier
        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";

        Logger.debug("Set OnlineApplicationURL to " + serviceURL);
        spEntityDescriptor.setEntityID(serviceURL);

        SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class);

        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.setWantAssertionsSigned(true);

        X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory();
        keyInfoFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance();

        KeyStore keyStore = config.getPVP2KeyStore();

        X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreMetadataKeyAlias(),
                config.getPVP2KeystoreMetadataKeyPassword().toCharArray());

        Logger.debug("Set Metadata key information");
        //Set MetaData Signing key
        KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        entitiesSignKeyDescriptor.setUse(UsageType.SIGNING);
        entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential));
        Signature entitiesSignature = getSignature(signingcredential);
        spEntitiesDescriptor.setSignature(entitiesSignature);

        //Set AuthRequest Signing certificate
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());
        KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);

        signKeyDescriptor.setUse(UsageType.SIGNING);
        signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential));

        spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);

        //set AuthRequest encryption certificate
        if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias())
                || MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyPassword())) {
            X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore,
                    config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(),
                    config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray());
            KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
            encryKeyDescriptor.setUse(UsageType.ENCRYPTION);
            encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential));

            //set encryption methode
            //            EncryptionMethod encMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class);
            //            encMethode.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM);            
            //            encryKeyDescriptor.getEncryptionMethods().add(encMethode);
            //            
            //            EncryptionMethod keyencMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class);
            //            keyencMethode.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);            
            //            encryKeyDescriptor.getEncryptionMethods().add(keyencMethode);

            spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor);

        } else {
            Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!");

        }

        NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        persistentnameIDFormat.setFormat(NameIDType.PERSISTENT);

        spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat);

        NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        transientnameIDFormat.setFormat(NameIDType.TRANSIENT);

        spSSODescriptor.getNameIDFormats().add(transientnameIDFormat);

        NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED);

        spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat);

        //set HTTP-POST Binding assertion consumer service
        AssertionConsumerService postassertionConsumerService = SAML2Utils
                .createSAMLObject(AssertionConsumerService.class);

        postassertionConsumerService.setIndex(0);
        postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION);
        spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService);

        //set Single Log-Out service
        SingleLogoutService sloService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        sloService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        sloService.setLocation(serviceURL + Constants.SERVLET_PVPSINGLELOGOUT);
        spSSODescriptor.getSingleLogoutServices().add(sloService);

        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

        AttributeConsumingService attributeService = SAML2Utils
                .createSAMLObject(AttributeConsumingService.class);

        attributeService.setIndex(0);
        attributeService.setIsDefault(true);
        ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class);
        serviceName.setName(new LocalizedString("Default Service", "de"));
        attributeService.getNames().add(serviceName);

        //set attributes which are requested
        attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes());
        spSSODescriptor.getAttributeConsumingServices().add(attributeService);

        //build metadata
        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor);
        out.marshall(spEntitiesDescriptor, document);

        Signer.signObject(entitiesSignature);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, sr);
        sw.close();

        String metadataXML = sw.toString();

        response.setContentType("text/xml");
        response.getOutputStream().write(metadataXML.getBytes());

        response.getOutputStream().close();

    } catch (ConfigurationException e) {
        Logger.warn("Configuration can not be loaded.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (NoSuchAlgorithmException e) {
        Logger.warn("Requested Algorithm could not found.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (ParserConfigurationException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerConfigurationException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerFactoryConfigurationError e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

    catch (Exception e) {
        Logger.warn("Unspecific PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

}

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

License:EUPL

public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
        HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
    try {//  w w w . j  a va 2 s  .com

        EntitiesDescriptor idpEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class);

        idpEntitiesDescriptor.setName(PVPConfiguration.getInstance().getIDPIssuerName());

        idpEntitiesDescriptor.setID(SAML2Utils.getSecureIdentifier());

        DateTime date = new DateTime();

        idpEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS));

        EntityDescriptor idpEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class);

        idpEntitiesDescriptor.getEntityDescriptors().add(idpEntityDescriptor);

        //TODO: maybe change EntityID to Metadata URL
        //idpEntityDescriptor
        //      .setEntityID(PVPConfiguration.getInstance().getIDPSSOMetadataService());

        idpEntityDescriptor.setEntityID(PVPConfiguration.getInstance().getIDPPublicPath());

        idpEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS));

        List<ContactPerson> persons = PVPConfiguration.getInstance().getIDPContacts();

        idpEntityDescriptor.getContactPersons().addAll(persons);

        idpEntityDescriptor.setOrganization(PVPConfiguration.getInstance().getIDPOrganisation());

        X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory();
        //keyInfoFactory.setEmitPublicKeyValue(true);
        keyInfoFactory.setEmitEntityIDAsKeyName(true);
        keyInfoFactory.setEmitEntityCertificate(true);

        KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance();

        Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential();
        Signature signature = CredentialProvider.getIDPSignature(metadataSigningCredential);

        //set KeyInfo Element
        SecurityHelper.prepareSignatureParams(signature, metadataSigningCredential, null, null);

        idpEntitiesDescriptor.setSignature(signature);

        //set IDP metadata
        idpEntityDescriptor.getRoleDescriptors().add(generateIDPMetadata(keyInfoGenerator));

        //set SP metadata for interfederation
        idpEntityDescriptor.getRoleDescriptors().add(generateSPMetadata(keyInfoGenerator));

        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(idpEntitiesDescriptor);
        out.marshall(idpEntitiesDescriptor, document);

        Signer.signObject(signature);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, sr);
        sw.close();

        String metadataXML = sw.toString();
        Logger.debug("METADATA: " + metadataXML);

        httpResp.setContentType("text/xml");
        httpResp.getOutputStream().write(metadataXML.getBytes("UTF-8"));

        httpResp.getOutputStream().close();

        return null;

    } catch (Exception e) {
        Logger.error("Failed to generate metadata", e);
        throw new MOAIDException("pvp2.13", null);
    }
}

From source file:be.e_contract.mycarenet.sts.RequestFactory.java

License:Open Source License

private void createConditions(AssertionType assertion) {
    ConditionsType conditions = this.samlObjectFactory.createConditionsType();
    DateTime notBefore = new DateTime();
    conditions.setNotBefore(toXMLGregorianCalendar(notBefore));
    DateTime notAfter = notBefore.plusHours(24);
    conditions.setNotOnOrAfter(toXMLGregorianCalendar(notAfter));
    assertion.setConditions(conditions);
}

From source file:be.e_contract.mycarenet.xkms2.XKMS2Client.java

License:Open Source License

private String addPrototypeKeyBinding(RegisterRequestType registerRequest, SessionKey sessionKey) {
    PrototypeKeyBindingType prototypeKeyBinding = this.objectFactory.createPrototypeKeyBindingType();
    registerRequest.setPrototypeKeyBinding(prototypeKeyBinding);

    String prototypeKeyBindingId = "keybinding-" + UUID.randomUUID().toString();
    prototypeKeyBinding.setId(prototypeKeyBindingId);

    KeyInfoType keyInfo = this.xmldsigObjectFactory.createKeyInfoType();
    prototypeKeyBinding.setKeyInfo(keyInfo);

    KeyValueType keyValue = this.xmldsigObjectFactory.createKeyValueType();
    keyInfo.getContent().add(this.xmldsigObjectFactory.createKeyValue(keyValue));

    RSAKeyValueType rsaKeyValue = this.xmldsigObjectFactory.createRSAKeyValueType();
    keyValue.getContent().add(this.xmldsigObjectFactory.createRSAKeyValue(rsaKeyValue));

    rsaKeyValue.setModulus(sessionKey.getModulus());
    rsaKeyValue.setExponent(sessionKey.getExponent());

    prototypeKeyBinding.getKeyUsage().add(SIGNATURE_KEY_USAGE);

    ValidityIntervalType validityInterval = this.objectFactory.createValidityIntervalType();
    prototypeKeyBinding.setValidityInterval(validityInterval);

    DateTime notBefore = new DateTime();
    validityInterval.setNotBefore(toXMLGregorianCalendar(notBefore));
    DateTime notAfter = notBefore.plusHours(12);
    validityInterval.setNotOnOrAfter(toXMLGregorianCalendar(notAfter));

    return prototypeKeyBindingId;
}