Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:azkaban.webapp.servlet.ScheduleServlet.java

License:Apache License

private void ajaxLoadHistory(HttpServletRequest req, HttpServletResponse resp, User user)
        throws ServletException, IOException {
    resp.setContentType(JSON_MIME_TYPE);
    long today = DateTime.now().withTime(0, 0, 0, 0).getMillis();
    long startTime = getLongParam(req, "startTime");
    DateTime start = new DateTime(startTime);
    // Ensure start time is 12:00 AM
    startTime = start.withTime(0, 0, 0, 0).getMillis();
    boolean useCache = false;
    if (startTime < today) {
        useCache = true;/*from ww w.  j a  v a 2 s  . c o m*/
    }
    long endTime = startTime + 24 * 3600 * 1000;
    int loadAll = getIntParam(req, "loadAll");

    // Cache file
    String cacheDir = getApplication().getServerProps().getString("cache.directory", "cache");
    File cacheDirFile = new File(cacheDir, "schedule-history");
    File cache = new File(cacheDirFile, startTime + ".cache");
    cache.getParentFile().mkdirs();

    if (useCache) {
        // Determine if cache exists
        boolean cacheExists = false;
        synchronized (this) {
            cacheExists = cache.exists() && cache.isFile();
        }
        if (cacheExists) {
            // Send the cache instead
            InputStream cacheInput = new BufferedInputStream(new FileInputStream(cache));
            try {
                IOUtils.copy(cacheInput, resp.getOutputStream());
                return;
            } finally {
                IOUtils.closeQuietly(cacheInput);
            }
        }
    }

    // Load data if not cached
    List<ExecutableFlow> history = null;
    try {
        AzkabanWebServer server = (AzkabanWebServer) getApplication();
        ExecutorManagerAdapter executorManager = server.getExecutorManager();
        history = executorManager.getExecutableFlows(null, null, null, 0, startTime, endTime, -1, -1);
    } catch (ExecutorManagerException e) {
        logger.error(e);
    }

    HashMap<String, Object> ret = new HashMap<String, Object>();
    List<HashMap<String, Object>> output = new ArrayList<HashMap<String, Object>>();
    ret.put("items", output);
    for (ExecutableFlow historyItem : history) {
        // Check if it is an scheduled execution
        if (historyItem.getScheduleId() >= 0 || loadAll != 0) {
            writeHistoryData(output, historyItem);
        }
    }

    // Make sure we're ready to cache it, otherwise output and return
    synchronized (this) {
        if (!useCache || cache.exists()) {
            JSONUtils.toJSON(ret, resp.getOutputStream(), false);
            return;
        }
    }

    // Create cache file
    File cacheTemp = new File(cacheDirFile, startTime + ".tmp");
    cacheTemp.createNewFile();
    OutputStream cacheOutput = new BufferedOutputStream(new FileOutputStream(cacheTemp));
    try {
        OutputStream outputStream = new SplitterOutputStream(cacheOutput, resp.getOutputStream());
        // Write to both the cache file and web output
        JSONUtils.toJSON(ret, outputStream, false);
    } finally {
        IOUtils.closeQuietly(cacheOutput);
    }
    // Move cache file
    synchronized (this) {
        cacheTemp.renameTo(cache);
    }
}

From source file:backend.expr.TimeCastExpr.java

@Override
public Object eval(ExprContext ctx) {
    Object o = field.eval(ctx);/*from   w w w  .  j  a va 2  s .  co  m*/
    if (o instanceof DateTime)
        return o;
    else if (o instanceof Number)
        return new DateTime(((Number) o).longValue());

    return StdRecord.DT_FMT.parseDateTime(String.valueOf(o));
}

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

License:Open Source License

/**
 * Verifies the signatures on the given document.
 * //from  ww  w.  ja va 2 s .  com
 * @param mimetype
 *            the mime-type of the document.
 * @param data
 *            the document data.
 * @param useAttachments
 *            <code>true</code> when you want to use SOAP attachments.
 * @return the verification result.
 * @throws UnsupportedDocumentTypeException
 *             for unsupported mime-types
 * @throws DocumentSignatureException
 *             when the document or signature is incorrect.
 */
public VerificationResult verify(String mimetype, byte[] data, boolean useAttachments)
        throws UnsupportedDocumentTypeException, DocumentSignatureException {
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();

    VerifyRequest verifyRequest = this.objectFactory.createVerifyRequest();
    verifyRequest.setProfile(DigitalSignatureServiceConstants.PROFILE);
    InputDocuments inputDocuments = this.objectFactory.createInputDocuments();
    verifyRequest.setInputDocuments(inputDocuments);
    addDocument(mimetype, data, useAttachments, inputDocuments);

    AnyType optionalInputs = this.objectFactory.createAnyType();
    verifyRequest.setOptionalInputs(optionalInputs);
    ReturnVerificationReport returnVerificationReport = this.vrObjectFactory.createReturnVerificationReport();
    optionalInputs.getAny().add(returnVerificationReport);
    returnVerificationReport.setIncludeVerifier(false);
    returnVerificationReport.setIncludeCertificateValues(true);

    this.wsSecuritySOAPHandler.setSession(null);
    ResponseBaseType response = this.dssPort.verify(verifyRequest);

    Result result = response.getResult();
    String resultMajor = result.getResultMajor();
    String resultMinor = result.getResultMinor();
    if (false == DigitalSignatureServiceConstants.SUCCESS_RESULT_MAJOR.equals(resultMajor)) {
        if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(resultMajor)) {
            if (DigitalSignatureServiceConstants.UNSUPPORTED_MIME_TYPE_RESULT_MINOR.equals(resultMinor)) {
                throw new UnsupportedDocumentTypeException();
            }
            if (DigitalSignatureServiceConstants.INCORRECT_SIGNATURE_RESULT_MINOR.equals(resultMinor)) {
                throw new DocumentSignatureException();
            }
        }
        throw new RuntimeException("not successfull: " + resultMajor + " " + resultMinor);
    }

    DateTime timeStampRenewalBefore = null;
    AnyType optionalOutputs = response.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutput : optionalOutputsList) {
        if (false == optionalOutput instanceof JAXBElement) {
            continue;
        }
        JAXBElement jaxbElement = (JAXBElement) optionalOutput;
        LOG.debug("optional output: " + optionalOutput.getClass().getName());
        if (jaxbElement.getValue() instanceof DeadlineType) {
            DeadlineType deadlineType = (DeadlineType) jaxbElement.getValue();
            timeStampRenewalBefore = new DateTime(deadlineType.getBefore().toGregorianCalendar());
        } else if (jaxbElement.getValue() instanceof VerificationReportType) {
            LOG.debug("found VerificationReport");
            VerificationReportType verificationReport = (VerificationReportType) jaxbElement.getValue();
            List<IndividualReportType> individualReports = verificationReport.getIndividualReport();
            for (IndividualReportType individualReport : individualReports) {

                if (!DigitalSignatureServiceConstants.SUCCESS_RESULT_MAJOR
                        .equals(individualReport.getResult().getResultMajor())) {
                    LOG.warn("some invalid VR result reported: "
                            + individualReport.getResult().getResultMajor());
                    continue;
                }
                SignedObjectIdentifierType signedObjectIdentifier = individualReport
                        .getSignedObjectIdentifier();
                Date signingTime = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties()
                        .getSigningTime().toGregorianCalendar().getTime();
                String location = signedObjectIdentifier.getSignedProperties().getSignedSignatureProperties()
                        .getLocation();
                SignerRoleType signerRole = signedObjectIdentifier.getSignedProperties()
                        .getSignedSignatureProperties().getSignerRole();
                String role = null;
                if (null != signerRole) {
                    ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles();
                    if (null != claimedRolesList) {
                        List<be.e_contract.dssp.ws.jaxb.xades.AnyType> claimedRoles = claimedRolesList
                                .getClaimedRole();
                        be.e_contract.dssp.ws.jaxb.xades.AnyType claimedRole = claimedRoles.get(0);
                        role = claimedRole.getContent().get(0).toString();
                    }
                }

                List<Object> details = individualReport.getDetails().getAny();
                X509Certificate certificate = null;
                String name = null;
                for (Object detail : details) {
                    if (detail instanceof JAXBElement<?>) {
                        JAXBElement<?> detailElement = (JAXBElement<?>) detail;
                        if (detailElement.getValue() instanceof DetailedSignatureReportType) {
                            DetailedSignatureReportType detailedSignatureReport = (DetailedSignatureReportType) detailElement
                                    .getValue();

                            List<CertificateValidityType> certificateValidities = detailedSignatureReport
                                    .getCertificatePathValidity().getPathValidityDetail()
                                    .getCertificateValidity();
                            CertificateValidityType certificateValidity = certificateValidities.get(0);
                            name = certificateValidity.getSubject();
                            byte[] encodedCertificate = certificateValidity.getCertificateValue();
                            try {
                                certificate = (X509Certificate) this.certificateFactory
                                        .generateCertificate(new ByteArrayInputStream(encodedCertificate));
                            } catch (CertificateException e) {
                                throw new RuntimeException("cert decoding error: " + e.getMessage(), e);
                            }
                        }
                    }
                }
                signatureInfos.add(new SignatureInfo(name, certificate, signingTime, role, location));
            }
        }
    }

    if (signatureInfos.isEmpty()) {
        return null;
    }
    return new VerificationResult(signatureInfos, timeStampRenewalBefore);
}

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

License:Open Source License

/**
 * Checks the signature on the SignResponse browser POST message.
 * /*from   w  w  w. j a va 2  s  . co m*/
 * @param signResponseMessage
 *            the SignResponse message.
 * @param session
 *            the session object.
 * @return the verification result object.
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws Base64DecodingException
 * @throws UserCancelException
 * @throws ClientRuntimeException
 * @throws SubjectNotAuthorizedException
 */
public static SignResponseVerificationResult checkSignResponse(String signResponseMessage,
        DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException,
        SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException,
        UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException {
    if (null == session) {
        throw new IllegalArgumentException("missing session");
    }

    byte[] decodedSignResponseMessage;
    try {
        decodedSignResponseMessage = Base64.decode(signResponseMessage);
    } catch (Base64DecodingException e) {
        throw new SecurityException("no Base64");
    }
    // JAXB parsing
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SignResponse signResponse;
    try {
        signResponse = (SignResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));
    } catch (UnmarshalException e) {
        throw new SecurityException("no valid SignResponse XML");
    }

    // DOM parsing
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);
    Document signResponseDocument = documentBuilder.parse(signResponseInputStream);

    // signature verification
    NodeList signatureNodeList = signResponseDocument
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    if (signatureNodeList.getLength() != 1) {
        throw new SecurityException("requires 1 ds:Signature element");
    }
    Element signatureElement = (Element) signatureNodeList.item(0);
    SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validSignature = xmlSignature.validate(domValidateContext);
    if (false == validSignature) {
        throw new SecurityException("invalid ds:Signature");
    }

    // verify content
    String responseId = null;
    RelatesToType relatesTo = null;
    AttributedURIType to = null;
    TimestampType timestamp = null;
    String signerIdentity = null;
    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputObject : optionalOutputsList) {
        LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName());
        if (optionalOutputObject instanceof JAXBElement) {
            JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;
            LOG.debug("optional output name: " + optionalOutputElement.getName());
            LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName());
            if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {
                responseId = (String) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof RelatesToType) {
                relatesTo = (RelatesToType) optionalOutputElement.getValue();
            } else if (TO_QNAME.equals(optionalOutputElement.getName())) {
                to = (AttributedURIType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof TimestampType) {
                timestamp = (TimestampType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {
                NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();
                signerIdentity = nameIdentifier.getValue();
            }
        }
    }

    Result result = signResponse.getResult();
    LOG.debug("result major: " + result.getResultMajor());
    LOG.debug("result minor: " + result.getResultMinor());
    if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {
        if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new UserCancelException();
        }
        if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new ClientRuntimeException();
        }
        if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR
                .equals(result.getResultMinor())) {
            throw new SubjectNotAuthorizedException(signerIdentity);
        }
    }
    if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {
        throw new SecurityException("invalid dss:ResultMajor");
    }

    if (null == responseId) {
        throw new SecurityException("missing async:ResponseID");
    }
    if (false == responseId.equals(session.getResponseId())) {
        throw new SecurityException("invalid async:ResponseID");
    }

    if (null == relatesTo) {
        throw new SecurityException("missing wsa:RelatesTo");
    }
    if (false == session.getInResponseTo().equals(relatesTo.getValue())) {
        throw new SecurityException("invalid wsa:RelatesTo");
    }

    if (null == to) {
        throw new SecurityException("missing wsa:To");
    }
    if (false == session.getDestination().equals(to.getValue())) {
        throw new SecurityException("invalid wsa:To");
    }

    if (null == timestamp) {
        throw new SecurityException("missing wsu:Timestamp");
    }
    AttributedDateTime expires = timestamp.getExpires();
    if (null == expires) {
        throw new SecurityException("missing wsu:Timestamp/wsu:Expires");
    }
    DateTime expiresDateTime = new DateTime(expires.getValue());
    DateTime now = new DateTime();
    if (now.isAfter(expiresDateTime)) {
        throw new SecurityException("wsu:Timestamp expired");
    }

    session.setSignResponseVerified(true);

    SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(
            signerIdentity);
    return signResponseVerificationResult;
}

From source file:be.e_contract.jwatchdog.datasource.rrd.RRDDatasource.java

License:Open Source License

@Override
public double[] getValues(int minutes) {
    LOG.debug("RRD file: " + this.rrdFile);
    RRDatabase rrd;//from  w ww . j ava2 s.c om
    try {
        rrd = new RRDatabase(this.rrdFile);
    } catch (IOException e) {
        throw new RuntimeException("RRD IO error: " + e.getMessage());
    }
    try {

        DateTime lastUpdate = new DateTime(rrd.getLastUpdate());
        LOG.debug("last update: " + lastUpdate);
        DateTime now = new DateTime();
        if (lastUpdate.isBefore(now.minusMinutes(minutes))) {
            LOG.warn("RRD outdated");
        }

        Header header = rrd.getHeader();
        int primaryDataPointInterval = header.getPDPStep();
        DateTime endDateTime = lastUpdate.minusSeconds(primaryDataPointInterval);
        DateTime startDateTime = endDateTime.minusMinutes(minutes);
        DataChunk dataChunk;
        try {
            dataChunk = rrd.getData(ConsolidationFunctionType.AVERAGE, startDateTime.toDate(),
                    endDateTime.toDate(), primaryDataPointInterval);
        } catch (IOException e) {
            throw new RuntimeException("RRD IO error: " + e.getMessage());
        }
        double[][] data = dataChunk.getData();
        Set<String> dataSourceNames = rrd.getDataSourcesName();
        LOG.debug("RRD datasources: " + dataSourceNames);

        int dsIdx;
        if (null != this.datasourceName) {
            if (!dataSourceNames.contains(this.datasourceName)) {
                LOG.warn("RRD datasource name not found: " + this.datasourceName);
                return new double[] {};
            }
            int size = dataSourceNames.size();
            for (dsIdx = 0; dsIdx < size; dsIdx++) {
                DataSource dataSource = rrd.getDataSource(dsIdx);
                if (dataSource.getName().equals(this.datasourceName)) {
                    break;
                }
            }
        } else {
            dsIdx = 0;
        }

        double[] values = new double[data.length];
        for (int idx = 0; idx < data.length; idx++) {
            values[data.length - idx - 1] = data[idx][dsIdx];
        }
        return values;
    } finally {
        try {
            rrd.close();
        } catch (IOException e) {
            LOG.error("error closing RRD: " + e.getMessage());
        }
    }
}

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

License:Open Source License

/**
 * Returns the value of the NotOnOrAfter element within the given SAML
 * assertion./*w w  w  . j a  v a  2  s  . co  m*/
 * 
 * @param assertionElement
 * @return
 */
public DateTime getNotAfter(Element assertionElement) {
    NodeList conditionsNodeList = assertionElement
            .getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", "Conditions");
    Element conditionsElement = (Element) conditionsNodeList.item(0);
    String notOnOrAfterAttributeValue = conditionsElement.getAttribute("NotOnOrAfter");
    Calendar calendar = DatatypeConverter.parseDateTime(notOnOrAfterAttributeValue);
    return new DateTime(calendar.getTime());
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

License:Open Source License

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }/*ww w.  j a v a2  s .  c  om*/

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.applet.service.signer.odf.OpenOfficeSignatureFacet.java

License:Open Source License

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("pre sign");

    Element dateElement = document.createElementNS("", "dc:date");
    dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    DateTime dateTime = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String now = fmt.print(dateTime);
    now = now.substring(0, now.indexOf("Z"));
    LOG.debug("now: " + now);
    dateElement.setTextContent(now);//from w ww  .j a  v a 2  s  .  c  om

    String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString();
    List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>();
    signaturePropertyContent.add(new DOMStructure(dateElement));
    SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent,
            "#" + signatureId, signaturePropertyId);

    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
    List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>();
    signaturePropertiesContent.add(signatureProperty);
    SignatureProperties signatureProperties = signatureFactory
            .newSignatureProperties(signaturePropertiesContent, null);
    objectContent.add(signatureProperties);

    objects.add(signatureFactory.newXMLObject(objectContent, null, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod);
    references.add(reference);
}

From source file:be.fedict.eid.dss.spi.utils.XAdESValidation.java

License:Open Source License

public SignatureInfo validate(Document document, XMLSignature xmlSignature, Element signatureElement,
        X509Certificate signingCertificate) throws XAdESValidationException {

    try {//from www  . j av a  2s .c om
        /*
         * Get signing time from XAdES-BES extension.
         */
        Element nsElement = getNsElement(document);

        Element qualifyingPropertiesElement = XAdESUtils.findQualifyingPropertiesElement(nsElement,
                xmlSignature, signatureElement);
        if (null == qualifyingPropertiesElement) {
            throw new XAdESValidationException("no matching xades:QualifyingProperties present");
        }
        QualifyingPropertiesType qualifyingProperties = XAdESUtils.unmarshall(qualifyingPropertiesElement,
                QualifyingPropertiesType.class);
        if (false == qualifyingProperties.getTarget().equals("#" + xmlSignature.getId())) {
            throw new XAdESValidationException("xades:QualifyingProperties/@Target incorrect");
        }

        SignedPropertiesType signedProperties = qualifyingProperties.getSignedProperties();
        SignedSignaturePropertiesType signedSignatureProperties = signedProperties
                .getSignedSignatureProperties();
        XMLGregorianCalendar signingTimeXMLGregorianCalendar = signedSignatureProperties.getSigningTime();
        DateTime signingTime = new DateTime(signingTimeXMLGregorianCalendar.toGregorianCalendar().getTime());
        LOG.debug("XAdES signing time: " + signingTime);

        /*
         * Check the XAdES signing certificate
         */
        XAdESUtils.checkSigningCertificate(signingCertificate, signedSignatureProperties);

        /*
         * Get XAdES ClaimedRole.
         */
        String role = null;
        SignerRoleType signerRole = signedSignatureProperties.getSignerRole();
        if (null != signerRole) {
            ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles();
            if (null != claimedRolesList) {
                List<AnyType> claimedRoles = claimedRolesList.getClaimedRole();
                if (!claimedRoles.isEmpty()) {
                    AnyType claimedRole = claimedRoles.get(0);
                    List<Object> claimedRoleContent = claimedRole.getContent();
                    for (Object claimedRoleContentItem : claimedRoleContent) {
                        if (claimedRoleContentItem instanceof String) {
                            role = (String) claimedRoleContentItem;
                            LOG.debug("XAdES claimed role: " + role);
                            break;
                        }
                    }
                }
            }
        }

        // XAdES-T

        // validate first SignatureTimeStamp
        Element signatureTimeStampElement = XAdESUtils
                .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SignatureTimeStamp");
        if (null == signatureTimeStampElement) {
            throw new XAdESValidationException("no xades:SignatureTimeStamp present");
        }
        XAdESTimeStampType signatureTimeStamp = XAdESUtils.unmarshall(signatureTimeStampElement,
                XAdESTimeStampType.class);
        List<TimeStampToken> signatureTimeStampTokens = XAdESSignatureTimeStampValidation
                .verify(signatureTimeStamp, signatureElement);

        // XAdES-X

        // validate first SigAndRefsTimeStamp
        Element sigAndRefsTimeStampElement = XAdESUtils
                .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SigAndRefsTimeStamp");
        if (null == sigAndRefsTimeStampElement) {
            LOG.error("No SigAndRefsTimeStamp present");
            throw new XAdESValidationException("no xades:SigAndRefsTimeStamp present");
        }
        XAdESTimeStampType sigAndRefsTimeStamp = XAdESUtils.unmarshall(sigAndRefsTimeStampElement,
                XAdESTimeStampType.class);
        List<TimeStampToken> sigAndRefsTimeStampTokens = XAdESSigAndRefsTimeStampValidation
                .verify(sigAndRefsTimeStamp, signatureElement);

        // timestamp tokens trust validation
        LOG.debug("validate SignatureTimeStamp's trust...");
        ValidationDataType signatureTimeStampValidationData = XAdESUtils.findNextSibling(
                signatureTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData",
                ValidationDataType.class);
        if (null != signatureTimeStampValidationData) {
            LOG.debug("xadesv141:TimeStampValidationData present for xades:SignatureTimeStamp");
            RevocationValuesType revocationValues = signatureTimeStampValidationData.getRevocationValues();
            List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
            List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);
            for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
                this.documentContext.validate(signatureTimeStampToken, ocspResponses, crls);
            }
        } else {
            for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
                this.documentContext.validate(signatureTimeStampToken);
            }
        }

        LOG.debug("validate SigAndRefsTimeStamp's trust...");
        ValidationDataType sigAndRefsTimeStampValidationData = XAdESUtils.findNextSibling(
                sigAndRefsTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData",
                ValidationDataType.class);
        if (null != sigAndRefsTimeStampValidationData) {
            LOG.debug("xadesv141:TimeStampValidationData present for xades:SigAndRefsTimeStamp");
            RevocationValuesType revocationValues = sigAndRefsTimeStampValidationData.getRevocationValues();
            List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
            List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);
            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                this.documentContext.validate(sigAndRefsTimeStampToken, ocspResponses, crls);
            }
        } else {
            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                this.documentContext.validate(sigAndRefsTimeStampToken);
            }
        }

        // timestamp tokens time coherence verification
        long timestampMaxOffset = this.documentContext.getTimestampMaxOffset();
        LOG.debug("validate timestamp tokens time coherence...");
        for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
            DateTime stsTokenGenTime = new DateTime(signatureTimeStampToken.getTimeStampInfo().getGenTime());
            try {
                XAdESUtils.checkCloseEnough(signingTime, stsTokenGenTime, timestampMaxOffset);
            } catch (XAdESValidationException e) {
                throw new XAdESValidationException("SignatureTimeStamp too far from SigningTime", e);
            }

            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                DateTime sigAndRefsTokenGenTime = new DateTime(
                        sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime());
                if (sigAndRefsTokenGenTime.isBefore(stsTokenGenTime)) {
                    throw new XAdESValidationException("SigAndRefsTimeStamp before SignatureTimeStamp");
                }
            }
        }

        long maxGracePeriod = this.documentContext.getMaxGracePeriod();
        for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
            DateTime sigAndRefsTokenGenTime = new DateTime(
                    sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime());
            try {
                XAdESUtils.checkCloseEnough(signingTime, sigAndRefsTokenGenTime,
                        maxGracePeriod * 1000 * 60 * 60);
            } catch (XAdESValidationException e) {
                throw new XAdESValidationException("SigAndRefsTimeStamp too far from SigningTime", e);
            }
        }

        // XAdES-X-L

        /*
         * Retrieve certificate chain and revocation data from XAdES-X-L
         * extension for trust validation.
         */
        RevocationValuesType revocationValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties,
                RevocationValuesType.class, "RevocationValues");
        List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
        List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);

        CertificateValuesType certificateValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties,
                CertificateValuesType.class, "CertificateValues");
        if (null == certificateValues) {
            throw new XAdESValidationException("no CertificateValues element found.");
        }
        List<X509Certificate> certificateChain = XAdESUtils.getCertificates(certificateValues);
        if (certificateChain.isEmpty()) {
            throw new XAdESValidationException("no cert chain in CertificateValues");
        }

        /*
         * Check certificate chain is indeed contains the signing
         * certificate.
         */
        if (!Arrays.equals(signingCertificate.getEncoded(), certificateChain.get(0).getEncoded())) {
            // throw new XAdESValidationException(
            // "XAdES certificate chain does not include actual signing certificate");
            /*
             * Not all XAdES implementations add the entire certificate
             * chain via xades:CertificateValues.
             */
            certificateChain.add(0, signingCertificate);
        }
        LOG.debug("XAdES certificate chain contains actual signing certificate");

        // XAdES-C
        CompleteCertificateRefsType completeCertificateRefs = XAdESUtils.findUnsignedSignatureProperty(
                qualifyingProperties, CompleteCertificateRefsType.class, "CompleteCertificateRefs");
        if (null == completeCertificateRefs) {
            throw new XAdESValidationException("missing CompleteCertificateRefs");
        }
        CompleteRevocationRefsType completeRevocationRefs = XAdESUtils.findUnsignedSignatureProperty(
                qualifyingProperties, CompleteRevocationRefsType.class, "CompleteRevocationRefs");
        if (null == completeRevocationRefs) {
            throw new XAdESValidationException("missing CompleteRevocationRefs");
        }
        for (OCSPResp ocspResp : ocspResponses) {
            XAdESUtils.checkReference(ocspResp, completeRevocationRefs);
        }
        for (X509CRL crl : crls) {
            XAdESUtils.checkReference(crl, completeRevocationRefs);
        }
        Iterator<X509Certificate> certIterator = certificateChain.iterator();
        certIterator.next(); // digestion of SigningCertificate already
                             // checked
        while (certIterator.hasNext()) {
            X509Certificate certificate = certIterator.next();
            XAdESUtils.checkReference(certificate, completeCertificateRefs);
        }

        /*
         * Perform trust validation via eID Trust Service
         */
        this.documentContext.validate(certificateChain, signingTime.toDate(), ocspResponses, crls);

        /*
         * Retrieve the possible eID identity signature extension data.
         */
        String firstName = null;
        String name = null;
        String middleName = null;
        SignatureInfo.Gender gender = null;
        byte[] photo = null;

        IdentityType identity = XAdESUtils.findIdentity(nsElement, xmlSignature, signatureElement);
        if (null != identity) {
            firstName = identity.getFirstName();
            name = identity.getName();
            middleName = identity.getMiddleName();
            switch (identity.getGender()) {
            case MALE:
                gender = SignatureInfo.Gender.MALE;
                break;
            case FEMALE:
                gender = SignatureInfo.Gender.FEMALE;
                break;
            }
            photo = identity.getPhoto().getValue();
        }

        /*
         * Return the result of the signature analysis.
         */
        return new SignatureInfo(signingCertificate, signingTime.toDate(), role, firstName, name, middleName,
                gender, photo);
    } catch (CertificateEncodingException e) {
        throw new XAdESValidationException(e);
    } catch (Exception e) {
        throw new XAdESValidationException(e);
    }
}

From source file:be.fedict.eid.idp.attribute.age.AgeAttributeService.java

License:Open Source License

public void addAttribute(Map<String, Attribute> attributeMap) {
    Attribute dobAttribute = attributeMap.get(DefaultAttribute.DATE_OF_BIRTH.getUri());
    if (null == dobAttribute) {
        return;//from   w w  w  .  j av a  2 s  . c  o  m
    }
    LOG.debug("Add age attribute");
    GregorianCalendar dobValue = (GregorianCalendar) dobAttribute.getValue();
    DateTime dob = new DateTime(dobValue.getTime());
    DateTime now = new DateTime();
    Years years = Years.yearsBetween(dob, now);
    int age = years.getYears();
    attributeMap.put(URI, new Attribute(URI, AttributeType.INTEGER, age));
}