Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:DataRequestParser.java

public void inflateDataRequests(Set<DataRequest> dataRequestSet) {

    Iterator<DataRequest> iter = dataRequestSet.iterator();

    // the goal here is to expand substitutions 
    // so if start data and stop data are found 
    // then each data request template needs to be expanded 
    // to cover these dates

    String absoluteLocalPath;//from www.j  a  v  a  2 s .  c  o  m

    DateTime startDate = this.getStartDate();
    DateTime stopDate = this.getStopDate();

    // the base case is that either start date or stop date is null
    // in this instance, inflated data set is equal to the original 
    // dataRequest set
    if (startDate == null || stopDate == null) {
        // nothing to inflate
        while (iter.hasNext()) {
            this.routingServer.submitDataRequest(iter.next());
        }
        return;
    }

    // calculate the number of days between start and stop date
    int numDays = Days.daysBetween(startDate, stopDate).getDays();

    DataRequest tmpDataRequest;

    int i = 0;
    // loop 
    while (iter.hasNext()) {

        tmpDataRequest = iter.next();

        // loop between start and stop dates
        for (int j = 0; j <= numDays; j += 1) {

            // make new data request from template that has effective date set;
            DataRequest newDataRequest = tmpDataRequest.copy();

            // set new date
            newDataRequest.setEffectiveDate(startDate.plusDays(j));

            // update local path with date info
            //newDataRequest.applyDateToLocalPath();
            absoluteLocalPath = this.dateKeyPathParser.replaceWithLiterals(
                    newDataRequest.getLocalPathTemplate(), startDate.plusDays(j), newDataRequest.getKey());

            newDataRequest.setLocalPathTemplate(absoluteLocalPath);

            //newDataRequest.print();

            i += 1;

            // hand off to the routing server
            if (this.routingServer != null) {
                //newDataRequest.print();
                this.routingServer.submitDataRequest(newDataRequest);
            } else {
                //System.out.println(i);
            }
        }
    }

    DateTimeFormatter fmt = DateTimeFormat.forPattern("y::D");
    System.out.println("Start date: " + fmt.print(this.getStartDate()) + ", Stop date: "
            + fmt.print(this.getStopDate()) + ", Number of days: " + numDays);
    System.out.println("From templates " + dataRequestSet.size() + ", inflated " + i + " data requests ...");
}

From source file:DataRequestStringParser.java

public String inflateDataRequests(Set<DataRequest> dataRequestSet) {

    Iterator<DataRequest> iter = dataRequestSet.iterator();

    // the goal here is to expand substitutions 
    // so if start data and stop data are found 
    // then each data request template needs to be expanded 
    // to cover these dates

    String absoluteLocalPath;/*from  ww  w  .j a  v a  2 s . c o  m*/

    DateTime startDate = this.getStartDate();
    DateTime stopDate = this.getStopDate();

    try {
        this.xmlParser.reset();
    } catch (IPWorksException e) {
        e.printStackTrace();
    }

    // the base case is that either start date or stop date is null
    // in this instance, inflated data set is equal to the original 
    // dataRequest set
    if (this.routingServer != null && (startDate == null || stopDate == null)) {
        // nothing to inflate
        while (iter.hasNext()) {
            this.routingServer.submitDataRequest(iter.next());
        }
        return null;
    }

    // calculate the number of days between start and stop date
    int numDays = Days.daysBetween(startDate, stopDate).getDays();

    DataRequest tmpDataRequest;

    int i = 0;
    // loop 
    while (iter.hasNext()) {

        tmpDataRequest = iter.next();

        // loop between start and stop dates
        for (int j = 0; j <= numDays; j += 1) {

            // make new data request from template that has effective date set;
            DataRequest newDataRequest = tmpDataRequest.copy();

            // set new date
            newDataRequest.setEffectiveDate(startDate.plusDays(j));

            // update local path with date info
            //newDataRequest.applyDateToLocalPath();
            absoluteLocalPath = this.dateKeyPathParser.replaceWithLiterals(
                    newDataRequest.getLocalPathTemplate(), startDate.plusDays(j), newDataRequest.getKey());

            newDataRequest.setLocalPathTemplate(absoluteLocalPath);

            //newDataRequest.print();

            i += 1;

            // hand off to the routing server
            if (this.routingServer != null) {
                //newDataRequest.print();
                this.routingServer.submitDataRequest(newDataRequest);
            } else {
                //System.out.println(i);
            }
        }
    }

    DateTimeFormatter fmt = DateTimeFormat.forPattern("y::D");
    return "Start date: " + fmt.print(startDate) + ", Stop date: " + fmt.print(stopDate) + ", Number of days: "
            + numDays + "\n" + "From templates " + dataRequestSet.size() + ", inflated " + i
            + " data requests ...";
}

From source file:aDeleteME.DeleteME.java

public static void main(String[] args) {
    Random random = new Random();

    DateTime startTime = new DateTime(random.nextLong()).withMillisOfSecond(0);

    Minutes minimumPeriod = Minutes.TWO;
    int minimumPeriodInSeconds = minimumPeriod.toStandardSeconds().getSeconds();
    int maximumPeriodInSeconds = Hours.ONE.toStandardSeconds().getSeconds();

    Seconds randomPeriod = Seconds.seconds(random.nextInt(maximumPeriodInSeconds - minimumPeriodInSeconds));
    DateTime endTime = startTime.plus(minimumPeriod).plus(randomPeriod);

    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    System.out.println(dateTimeFormatter.print(startTime));
    System.out.println(dateTimeFormatter.print(endTime));
}

From source file:at.gv.egovernment.moa.util.DateTimeUtils.java

License:EUPL

public static String formatPEPSDateToMOADate(String pepsDate) {

    if (StringUtils.isEmpty(pepsDate)) {
        return null;
    }/*from ww  w.j  a  v  a  2 s  . c om*/

    DateTimeFormatter fmt = null;

    switch (pepsDate.length()) {
    case 4:
        fmt = DateTimeFormat.forPattern("yyyy");
        break;
    case 6:
        fmt = DateTimeFormat.forPattern("yyyyMM");
        break;
    case 8:
        fmt = DateTimeFormat.forPattern("yyyyMMdd");
        break;
    default:
        fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        break;
    }

    DateTime dt = fmt.parseDateTime(pepsDate);
    DateTimeFormatter fmt2 = DateTimeFormat.forPattern("yyyy-MM-dd");
    return fmt2.print(dt);

}

From source file:azkaban.common.web.GuiUtils.java

License:Apache License

public String formatDate(DateTime date, String format) {
    DateTimeFormatter f = DateTimeFormat.forPattern(format);
    return f.print(date);
}

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

License:Apache License

public String formatDate(long timestamp, String format) {
    DateTimeFormatter f = DateTimeFormat.forPattern(format);
    return f.print(timestamp);
}

From source file:backend.util.FileGroup.java

public static void main(String[] args) throws IOException {
    boolean Done = false;
    do {//from  www .  j a v a2 s. c  o  m
        DateTimeFormatter templFMT = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTimeFormatter subDirFMT = DateTimeFormat.forPattern("yyMMdd");

        JFileChooser fChooser = new JFileChooser("D:\\CGKStudio\\log");
        fChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //        fChooser.setFileFilter(new FileNameExtensionFilter("LOG File",""));
        if (fChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
            return;

        File dir = fChooser.getSelectedFile();
        List<File> files = new LinkedList(Arrays.asList(dir.listFiles()));

        DateTime d = new DateTime(2014, 11, 20, 0, 0);
        DateTime now = DateTime.now();
        while (d.compareTo(now) <= 0) {
            String templ = templFMT.print(d);

            List<File> moved = new LinkedList();
            files.stream().filter((file) -> (file.getName().contains(templ))).forEach((file) -> {
                moved.add(file);
            });

            files.removeAll(moved);
            if (moved.size() > 0) {
                String subDir = dir.getAbsolutePath() + "\\" + subDirFMT.print(d);
                File subDirFile = new File(subDir);
                if (!subDirFile.exists())
                    Files.createDirectory(subDirFile.toPath());

                moved.stream().forEach((file) -> {
                    try {
                        File target = new File(subDir + "\\" + file.getName());
                        if (!target.exists()) {
                            Files.copy(new File(dir.getAbsolutePath() + "\\" + file.getName()).toPath(),
                                    target.toPath());
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(FileGroup.class.getName()).log(Level.SEVERE, null, ex);
                    }
                });
            }

            d = d.plusDays(1);
        }

        int sel;
        sel = JOptionPane.showConfirmDialog(fChooser, "Do it again?", "Again", JOptionPane.YES_NO_OPTION);
        if (sel != JOptionPane.YES_OPTION)
            Done = true;
    } while (!Done);
}

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   w  w w. java 2  s  .  c o m*/
 * 
 * <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.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 o  m

    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.applet.service.signer.ooxml.OOXMLSignatureFacet.java

License:Open Source License

private void addSignatureTime(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<XMLStructure> objectContent) {
    /*/*from  w ww.java  2  s.  c  o  m*/
     * SignatureTime
     */
    Element signatureTimeElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:SignatureTime");
    signatureTimeElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi", OOXML_DIGSIG_NS);
    Element formatElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Format");
    formatElement.setTextContent("YYYY-MM-DDThh:mm:ssTZD");
    signatureTimeElement.appendChild(formatElement);
    Element valueElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Value");
    Date now = this.clock.getTime();
    DateTime dateTime = new DateTime(now.getTime(), DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String nowStr = fmt.print(dateTime);
    LOG.debug("now: " + nowStr);
    valueElement.setTextContent(nowStr);
    signatureTimeElement.appendChild(valueElement);

    List<XMLStructure> signatureTimeContent = new LinkedList<XMLStructure>();
    signatureTimeContent.add(new DOMStructure(signatureTimeElement));
    SignatureProperty signatureTimeSignatureProperty = signatureFactory
            .newSignatureProperty(signatureTimeContent, "#" + signatureId, "idSignatureTime");
    List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
    signaturePropertyContent.add(signatureTimeSignatureProperty);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent,
            "id-signature-time-" + UUID.randomUUID().toString());
    objectContent.add(signatureProperties);
}