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() 

Source Link

Document

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:azkaban.web.pages.ExecutionHistoryServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final FlowManager allFlows = this.getApplication().getAllFlows();

    /* set runtime properties from request and response*/
    super.setRuntimeProperties(req, resp);

    if (hasParam(req, "action")) {
        if ("restart".equals(getParam(req, "action")) && hasParam(req, "id")) {
            try {
                long id = Long.parseLong(getParam(req, "id"));

                final FlowExecutionHolder holder = allFlows.loadExecutableFlow(id);

                if (holder == null) {
                    addMessage(req, String.format("Unknown flow with id[%s]", id));
                } else {
                    Flows.resetFailedFlows(holder.getFlow());
                    this.getApplication().getJobExecutorManager().execute(holder);

                    addMessage(req, String.format("Flow[%s] restarted.", id));
                }/*from w w  w. j av a  2  s.  c  o m*/
            } catch (NumberFormatException e) {
                addMessage(req, String.format("Apparently [%s] is not a valid long.", getParam(req, "id")));
            } catch (JobExecutionException e) {
                addMessage(req, "Error restarting " + getParam(req, "id") + ". " + e.getMessage());
            }
        }
    }

    long currMaxId = allFlows.getCurrMaxId();

    String beginParam = req.getParameter("begin");
    int begin = beginParam == null ? 0 : Integer.parseInt(beginParam);

    String sizeParam = req.getParameter("size");
    int size = sizeParam == null ? 20 : Integer.parseInt(sizeParam);

    List<ExecutableFlow> execs = new ArrayList<ExecutableFlow>(size);
    for (int i = begin; i < begin + size; i++) {
        final FlowExecutionHolder holder = allFlows.loadExecutableFlow(currMaxId - i);
        ExecutableFlow flow = null;
        if (holder != null)
            flow = holder.getFlow();

        if (flow != null)
            execs.add(flow);
    }

    Page page = newPage(req, resp, "azkaban/web/pages/execution_history.vm");
    page.add("executions", execs);
    page.add("begin", begin);
    page.add("size", size);
    page.add("currentTime", (new DateTime()).getMillis());
    ExecutingJobUtils utils = new ExecutingJobUtils();
    page.add("jsonExecution", utils.getExecutableFlowJSON(execs));
    page.add("timezone", ZONE_FORMATTER.print(System.currentTimeMillis()));
    page.render();
}

From source file:azkaban.web.pages.FlowExecutionServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/xhtml+xml");
    Page page = newPage(req, resp, "azkaban/web/pages/flow_instance.vm");
    final FlowManager allFlows = this.getApplication().getAllFlows();

    if (hasParam(req, "job_id")) {
        String jobID = getParam(req, "job_id");
        ExecutableFlow flow = allFlows.createNewExecutableFlow(jobID);

        page.add("id", "0");
        page.add("name", jobID);

        if (flow == null) {
            addError(req, "Job " + jobID + " not found.");
            page.render();//w w  w  .  jav a 2 s .  c o m
            return;
        }

        // This will be used the other
        Flow displayFlow = new Flow(flow.getName(), (Props) null);
        fillFlow(displayFlow, flow);
        displayFlow.validateFlow();

        String flowJSON = createJsonFlow(displayFlow);
        page.add("jsonflow", flowJSON);
        page.add("action", "run");
        page.add("joblist", createJsonJobList(displayFlow));
    } else if (hasParam(req, "id")) {
        long id = Long.parseLong(getParam(req, "id"));
        FlowExecutionHolder holder = allFlows.loadExecutableFlow(id);
        ExecutableFlow executableFlow = holder.getFlow();

        // This will be used the other
        Flow displayFlow = new Flow(executableFlow.getName(), (Props) null);
        fillFlow(displayFlow, executableFlow);
        displayFlow.validateFlow();

        String flowJSON = createJsonFlow(displayFlow);
        page.add("jsonflow", flowJSON);
        page.add("id", id);
        if (executableFlow.getStartTime() != null) {
            page.add("startTime", executableFlow.getStartTime());
            if (executableFlow.getEndTime() != null) {
                page.add("endTime", executableFlow.getEndTime());
                page.add("period",
                        new Duration(executableFlow.getStartTime(), executableFlow.getEndTime()).toPeriod());
            } else {
                page.add("period", new Duration(executableFlow.getStartTime(), new DateTime()).toPeriod());
            }
        }

        page.add("showTimes", true);
        page.add("name", executableFlow.getName());
        page.add("action", "restart");
        page.add("joblist", createJsonJobList(displayFlow));
    }

    page.render();
}

From source file:azkaban.web.pages.IndexServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    /* set runtime properties from request and response */
    super.setRuntimeProperties(req, resp);

    AzkabanApplication app = getApplication();
    @SuppressWarnings("unused")
    Map<String, JobDescriptor> descriptors = app.getJobManager().loadJobDescriptors();
    Page page = newPage(req, resp, "azkaban/web/pages/index.vm");
    page.add("logDir", app.getLogDirectory());
    page.add("flows", app.getAllFlows());
    page.add("scheduled", app.getScheduleManager().getSchedule());
    page.add("executing", app.getJobExecutorManager().getExecutingJobs());
    page.add("completed", app.getJobExecutorManager().getCompleted());
    page.add("rootJobNames", app.getAllFlows().getRootFlowNames());
    page.add("folderNames", app.getAllFlows().getFolders());
    page.add("jobDescComparator", JobDescriptor.NAME_COMPARATOR);

    ExecutingJobUtils utils = new ExecutingJobUtils();
    page.add("jsonExecution",
            utils.getExecutableJobAndInstanceJSON(app.getJobExecutorManager().getExecutingJobs()));
    page.add("timezone", ZONE_FORMATTER.print(System.currentTimeMillis()));
    page.add("currentTime", (new DateTime()).getMillis());
    page.render();//from  w  w w .j a v  a 2  s. c o m
}

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

License:Apache License

/**
 * Creates a new velocity page to use. With session.
 *
 * @param req/*from  w  ww . j  a v  a2  s  .c  o m*/
 * @param resp
 * @param template
 * @return
 */
protected Page newPage(HttpServletRequest req, HttpServletResponse resp, Session session, String template) {
    Page page = new Page(req, resp, application.getVelocityEngine(), template);
    page.add("azkaban_name", name);
    page.add("azkaban_label", label);
    page.add("azkaban_color", color);
    page.add("utils", utils);
    page.add("timezone", ZONE_FORMATTER.print(System.currentTimeMillis()));
    page.add("currentTime", (new DateTime()).getMillis());
    if (session != null && session.getUser() != null) {
        page.add("user_id", session.getUser().getUserId());
    }
    page.add("context", req.getContextPath());

    String errorMsg = getErrorMessageFromCookie(req);
    page.add("error_message", errorMsg == null || errorMsg.isEmpty() ? "null" : errorMsg);
    setErrorMessageInCookie(resp, null);

    String warnMsg = getWarnMessageFromCookie(req);
    page.add("warn_message", warnMsg == null || warnMsg.isEmpty() ? "null" : warnMsg);
    setWarnMessageInCookie(resp, null);

    String successMsg = getSuccessMessageFromCookie(req);
    page.add("success_message", successMsg == null || successMsg.isEmpty() ? "null" : successMsg);
    setSuccessMessageInCookie(resp, null);

    // @TODO, allow more than one type of viewer. For time sake, I only install
    // the first one
    if (viewerPlugins != null && !viewerPlugins.isEmpty()) {
        page.add("viewers", viewerPlugins);
    }

    if (triggerPlugins != null && !triggerPlugins.isEmpty()) {
        page.add("triggerPlugins", triggerPlugins);
    }

    return page;
}

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

License:Apache License

/**
 * Creates a new velocity page to use./*w  ww .j  a v a  2s.c o m*/
 *
 * @param req
 * @param resp
 * @param template
 * @return
 */
protected Page newPage(HttpServletRequest req, HttpServletResponse resp, String template) {
    Page page = new Page(req, resp, application.getVelocityEngine(), template);
    page.add("azkaban_name", name);
    page.add("azkaban_label", label);
    page.add("azkaban_color", color);
    page.add("timezone", ZONE_FORMATTER.print(System.currentTimeMillis()));
    page.add("currentTime", (new DateTime()).getMillis());
    page.add("context", req.getContextPath());

    // @TODO, allow more than one type of viewer. For time sake, I only install
    // the first one
    if (viewerPlugins != null && !viewerPlugins.isEmpty()) {
        page.add("viewers", viewerPlugins);
        ViewerPlugin plugin = viewerPlugins.get(0);
        page.add("viewerName", plugin.getPluginName());
        page.add("viewerPath", plugin.getPluginPath());
    }

    if (triggerPlugins != null && !triggerPlugins.isEmpty()) {
        page.add("triggers", triggerPlugins);
    }

    return page;
}

From source file:bali.registry.Context.java

License:Open Source License

/**
 * This constructor takes the account identifier and the signature for the request and creates a
 * account context that can be used by the services implementing the API to authenticate and
 * authorize the request before executing it.
 *
 * @param accountTag The identifier for the account making the request.
 * @param signature A signature generated using the private key of the account.
 *//*from ww  w  . j  a  v a 2s .co  m*/
public Context(Tag accountTag, byte[] signature) {
    this.accountTag = accountTag;
    this.requestTag = new Tag();
    this.signature = signature;
    this.timestamp = new DateTime();
    this.attempt = 1;
}

From source file:bamons.process.batch.task.BatchScheduledTasks.java

License:Open Source License

public void sampleJob() throws Exception {

    try {/*ww  w  . j a  v  a 2 s  .  c  om*/

        DateTime dt = new DateTime();
        dt = dt.minusDays(1);
        String targetDate = dt.toString(DateTimeFormat.forPattern("yyyy-MM-dd"));

        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
                .addString("targetDate", targetDate).toJobParameters();
        JobExecution execution = jobLauncher.run(sampleJob, jobParameters);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:be.agiv.security.AGIVSecurity.java

License:Open Source License

private boolean requireNewToken(SecurityToken securityToken) {
    if (null == securityToken) {
        return true;
    }/* ww w.  j  av  a  2s. c  o  m*/
    DateTime now = new DateTime();
    DateTime expires = new DateTime(securityToken.getExpires());
    Duration duration = new Duration(now, expires);
    LOG.debug("token validity: " + duration);
    if (duration.isLongerThan(new Duration(this.tokenRetirementDuration))) {
        LOG.debug("reusing security token: " + securityToken.getAttachedReference());
        return false;
    }
    return true;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

License:Open Source License

private RequestType createRequest() {
    RequestType request = this.samlpObjectFactory.createRequestType();
    String requestId = "request-" + UUID.randomUUID().toString();
    request.setRequestID(requestId);//  www .  j av  a  2  s.  c  om
    request.setMajorVersion(BigInteger.ONE);
    request.setMinorVersion(BigInteger.ONE);
    DateTime now = new DateTime();
    request.setIssueInstant(toXMLGregorianCalendar(now));
    return request;
}