Example usage for javax.xml.datatype DatatypeFactory newInstance

List of usage examples for javax.xml.datatype DatatypeFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.datatype DatatypeFactory newInstance.

Prototype

public static DatatypeFactory newInstance() throws DatatypeConfigurationException 

Source Link

Document

Obtain a new instance of a DatatypeFactory .

Usage

From source file:org.ow2.aspirerfid.programmableengine.epcisclient.MasterDataCaptureClient.java

public XMLGregorianCalendar getCurrentTime() {
    // get the current time and set the eventTime
    XMLGregorianCalendar now = null;
    try {//from   w  ww  .  j a va 2s. co m
        DatatypeFactory dataFactory = DatatypeFactory.newInstance();
        now = dataFactory.newXMLGregorianCalendar(new GregorianCalendar());
        log.debug("Event Time:" + now.getHour() + ":" + now.getMinute() + ":" + ":" + now.getSecond() + "\n");
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    return now;

}

From source file:org.rifidi.edge.epcglobal.aleread.wrappers.ReportSender.java

@Override
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        try {//ww w. j a  v  a  2s  .  com
            ResultContainer container = resultQueue.take();
            ECReports reports = new ECReports();
            reports.setReports(new ECReports.Reports());
            reports.setInitiationCondition(
                    ALEReadAPI.conditionToName.get(ALEReadAPI.TriggerCondition.REPEAT_PERIOD));
            GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
            DatatypeFactory dataTypeFactory = null;
            try {
                dataTypeFactory = DatatypeFactory.newInstance();
            } catch (DatatypeConfigurationException ex) {
                logger.fatal("epic fail: " + ex);
            }
            reports.setALEID("Rifidi Edge Server");
            reports.setDate(dataTypeFactory.newXMLGregorianCalendar(gc));
            Set<DatacontainerEvent> events = new HashSet<DatacontainerEvent>();
            for (TagReadEvent tagRead : container.events) {
                events.add(tagRead.getTag());
            }
            // process the set of events
            for (RifidiReport rifidiReport : rifidiReports) {
                rifidiReport.processEvents(events);
                ECReport rep = rifidiReport.send();
                if (rep != null) {
                    reports.getReports().getReport().add(rep);
                }
            }

            reports.setInitiationCondition(ALEReadAPI.conditionToName.get(container.startReason));
            // TODO: dummy code, replace with correct typing
            if (container.startCause != null) {
                reports.setInitiationTrigger(ALEReadAPI.conditionToName.get(container.startReason));
            }
            reports.setTerminationCondition(ALEReadAPI.conditionToName.get(container.stopReason));
            // TODO: dummy code, replace with correct typing
            if (container.startCause != null) {
                reports.setTerminationTrigger(ALEReadAPI.conditionToName.get(container.startReason));
            }
            if (spec.isIncludeSpecInReports()) {
                reports.setECSpec(spec);
            }
            reports.setSpecName(specName);
            reports.setTotalMilliseconds(container.stopTime - container.startTime);
            // send it
            for (String uri : subscriptionURIs) {
                logger.debug(">>>>> Sending report to " + uri);
                System.out.println("Report sender sending ALE report to " + uri);

                try {

                    String[] str;
                    Socket socket;
                    // resolve IPv6 issues by Janggwan
                    if (uri.toString().charAt(0) == '[') {
                        str = uri.toString().split("]:");
                        socket = new Socket(str[0] + "]", Integer.parseInt(str[1]));
                    } else {
                        str = uri.toString().split(":");
                        socket = new Socket(str[0], Integer.parseInt(str[1]));
                    }

                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                    try {
                        marsh.marshal(objectFactoryALE.createECReports(reports), out);

                        StringWriter sw = new StringWriter();
                        marsh.marshal(objectFactoryALE.createECReports(reports), sw);
                        System.out.println("Sent ECReport via Report sender: \n" + sw.toString());

                    } catch (JAXBException e) {
                        logger.fatal("Problem serializing to xml: " + e);
                    }
                    out.flush();
                    out.close();
                    socket.close();
                } catch (NumberFormatException e) {
                    logger.warn(e);
                } catch (UnknownHostException e) {
                    logger.warn(e);
                } catch (IOException e) {
                    logger.warn(e);
                }
            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:org.roda_project.commons_ip.utils.Utils.java

public static Optional<XMLGregorianCalendar> getCurrentTime() {
    Optional<XMLGregorianCalendar> res = Optional.empty();
    try {//from   w  w  w  . ja v  a 2s  .c o  m
        GregorianCalendar c = new GregorianCalendar();
        Optional.of(DatatypeFactory.newInstance().newXMLGregorianCalendar(c));
    } catch (DatatypeConfigurationException e) {
        // do nothing & return empty
    }
    return res;
}

From source file:org.roda_project.commons_ip.utils.Utils.java

public static XMLGregorianCalendar getCurrentCalendar() throws DatatypeConfigurationException {
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTime(new Date());
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
}

From source file:org.sharegov.cirm.utils.GenUtils.java

public static java.util.Date parseDate(OWLLiteral literal) {
    Date result = new Date();
    String value = literal.getLiteral();
    if (xmlDatatypeFactory == null) {
        try {/*from  w w  w .j  a  v  a 2  s  . co m*/
            xmlDatatypeFactory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new RuntimeException("Failed to create xmlDataFactory", e);
        }
    }
    try {
        // parse ISO 8601 date
        synchronized (xmlDatatypeFactory) {
            try {
                result = xmlDatatypeFactory.newXMLGregorianCalendar(value).toGregorianCalendar().getTime();
            } catch (IllegalArgumentException t) {
                result = parseDate(value);
            }
        }
    } catch (Exception e) {
        ThreadLocalStopwatch.getWatch().time("Error: Could not parse date " + value + " as ISO 8601");
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.sifassociation.util.SIFAuthUtil.java

public static XMLGregorianCalendar stringToXMLGregorianCalendar(String timestamp)
        throws DatatypeConfigurationException {
    Calendar calendar = DatatypeConverter.parseDateTime(timestamp);
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTimeInMillis(calendar.getTimeInMillis());
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
}

From source file:org.sifassociation.util.SIFAuthUtil.java

public static XMLGregorianCalendar getNow() throws DatatypeConfigurationException {
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
}

From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java

/**
 * Retrieve detail data./*from www . j  a v a  2  s .  com*/
 *
 * @param request
 * @return
 */
public GetComponentDetailDataResponseType getComponentDetailDataForUser(String source,
        GetComponentDetailDataForUserRequestType request) {
    GetComponentDetailDataResponseType response = new GetComponentDetailDataResponseType();

    log.debug("Retrieving " + source + " detail for ticket for user: " + request.getUserId());

    try {
        //Query based on ticket ticket id
        AlertService service = new AlertService();
        TicketQueryParams query = new TicketQueryParams();
        query.setTicketUniqueId(request.getItemId());
        List<AlertTicket> tickets = service.ticketQuery(query);

        if ((tickets == null) || (tickets.isEmpty())) {
            log.debug("Cound not find " + source + " ticket: " + request.getItemId());
            throw new Exception(ERR_MSG_ITEM_NOT_FOUND);
        }

        //Poplulate detail data object
        GregorianCalendar cal = new GregorianCalendar();
        AlertTicket ticket = tickets.get(0);
        DetailData detailData = new DetailData();
        detailData.setAuthor(ticket.getAlertOriginator());
        detailData.setFrom(ticket.getAlertOriginator());
        detailData.setData(sanitizePayload(request.getUserId(), ticket.getPayload(), ticket));
        detailData.setDataSource(source);
        cal.setTime(ticket.getAlertTimestamp());
        detailData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
        detailData.setDescription(ticket.getDescription());
        detailData.setItemId(ticket.getTicketUniqueId());
        detailData.setPatient(ticket.getPatientName());

        //Object specific name/value pairs
        addNameValue(detailData.getItemValues(), ITEM_PRIORITY, ticket.getPriority());
        addNameValue(detailData.getItemValues(), ITEM_PATIENT_UNIT_NUMBER, ticket.getPatientUnitNumber());
        addNameValue(detailData.getItemValues(), ITEM_PATIENT_SEX, ticket.getPatientSex());
        //          addNameValue(detailData.getItemValues(), ITEM_PATIENT_FMPSSN, ticket.getPatientFMPSSN());

        //Go through action history and add to name/value
        //  Also, check if ticket is new for this user
        //  Also, hold onto last action performed by user or system user
        //  Also, hold onto last action
        int i = 1;
        boolean isNewAlert = true;
        AlertAction lastAction = null;
        AlertAction lastUserAction = null;
        for (AlertAction action : ticket.getActionHistory()) {
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_NAME,
                    action.getActionName());
            cal.setTime(action.getActionTimestamp());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_TIME,
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(cal).toString());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_ID,
                    action.getUserId());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_NAME,
                    action.getUserName());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_PROVIDER,
                    action.getUserProvider().toString());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_MESSAGE,
                    action.getMessage());
            i++;

            //Check if ticket is new for this user
            if (SYSTEM_USER_ID.equals(action.getUserId())
                    || ((request.getUserId() != null) && request.getUserId().equals(action.getUserId()))) {

                if (ActionConstants.ACTION_READ.equals(action.getActionName())) {
                    isNewAlert = false;
                }

                lastUserAction = action;
            }

            //Set last action
            lastAction = action;
        }

        //Set appropriate status value
        String status = "";
        if (isNewAlert) {
            //The ticket may be new to this user, but if it is closed and no further
            //  action can be done, then set the status to the last action
            if (AlertUtil.isTickedClosed(ticket)) {
                status = lastAction.getActionName();
            } else {
                status = ALERT_STATUS_NEW;
            }
        } else if (lastUserAction != null) {
            status = lastUserAction.getActionName();
        } else if (lastAction != null) {
            status = lastAction.getActionName();
        }
        addNameValue(detailData.getItemValues(), ITEM_STATUS, status);

        response.setDetailObject(detailData);
    } catch (Exception e) {
        log.error("Error retriving detail for alert ticket: " + request.getItemId(), e);

        ServiceError serviceError = new ServiceError();
        serviceError.setCode(ERR_CODE);
        serviceError.setText(e.getMessage());
        response.getErrorList().add(serviceError);
    }

    return response;
}

From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java

/**
 * Retreive summary objects for all alerts.
 *
 * @param request// w  ww. j  a v  a  2 s.  co  m
 * @return
 */
public GetComponentSummaryDataResponseType getComponentSummaryDataForUser(String source,
        GetComponentSummaryDataForUserRequestType request) {
    GetComponentSummaryDataResponseType response = new GetComponentSummaryDataResponseType();

    log.debug("Retrieving " + source + " summaries for user: " + request.getUserId());

    try {

        if (DATA_SOURCE_PT_ALERTS.equals(source)) {
            //If no patient id is passed, just return
            if ((request.getPatientId() == null) || request.getPatientId().isEmpty()) {
                return response;
            }
        } else { //check for provider
                 //If no provider id is passed, just return
            if ((request.getProviderId() == null) || request.getProviderId().isEmpty()) {
                return response;
            }
        }

        //Find allTickets based on data source
        List<AlertTicket> tickets = findTickets(source, request.getPatientId(), request.getProviderId(),
                request.isArchive());
        if (tickets == null) {
            throw new Exception("Null ticket query result.");
        }

        log.debug("Found " + tickets.size() + " tickets found for provider: " + request.getProviderId());

        GregorianCalendar cal = new GregorianCalendar();
        List<Long> usedIds = new LinkedList<Long>();
        for (AlertTicket ticket : tickets) {

            //If the ticket has already been added, ignore
            if (usedIds.contains(ticket.getTicketId())) {
                continue;
            }
            usedIds.add(ticket.getTicketId());

            //Poplulate summary data object
            SummaryData summaryData = new SummaryData();
            summaryData.setAuthor(ticket.getAlertOriginator());
            summaryData.setFrom(ticket.getAlertOriginator());
            summaryData.setDataSource(source);
            cal.setTime(ticket.getAlertTimestamp());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
            summaryData.setDescription(ticket.getDescription());
            summaryData.setItemId(ticket.getTicketUniqueId());
            summaryData.setPatient(ticket.getPatientName());
            Set<AlertStatus> statuses = ticket.getStatus();
            for (AlertStatus status : statuses) {
                if (status.getTicket().getTicketId().equals(ticket.getTicketId()))
                    ;
                if (status.isFlagged()) {
                    summaryData.setFolder("Starred");
                } else {
                    summaryData.setFolder("");
                }
            }

            //Object specific name/value pairs
            addNameValue(summaryData.getItemValues(), ITEM_PRIORITY, ticket.getPriority());
            addNameValue(summaryData.getItemValues(), ITEM_FOLDERS, summaryData.getFolder());

            //Go through action history and add to name/value
            //  Also, check if ticket is new for this user
            //  Also, hold onto last action
            int i = 1;
            boolean isNewAlert = true;
            AlertAction lastAction = null;
            for (AlertAction action : ticket.getActionHistory()) {
                //For mobile, we don't add actions
                if (!DATA_SOURCE_ALERTS_MOBILE.equals(source)) {
                    addNameValue(summaryData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_NAME,
                            action.getActionName());
                    cal.setTime(action.getActionTimestamp());
                    addNameValue(summaryData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_TIME,
                            DatatypeFactory.newInstance().newXMLGregorianCalendar(cal).toString());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_ID, action.getUserId());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_NAME, action.getUserName());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_PROVIDER,
                            action.getUserProvider().toString());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_MESSAGE, action.getMessage());
                    i++;
                }

                //Check if ticket is new for this user
                if ((request.getUserId() != null) && request.getUserId().equals(action.getUserId())
                        && ActionConstants.ACTION_READ.equals(action.getActionName())) {
                    isNewAlert = false;
                }

                //Set last action
                lastAction = action;
            }

            //Set appropriate status value
            String status = "";
            if (isNewAlert) {
                //The ticket may be new to this user, but if it is closed and no further
                //  action can be done, then set the status to the last action
                if (AlertUtil.isTickedClosed(ticket)) {
                    status = lastAction.getActionName();
                } else {
                    status = ALERT_STATUS_NEW;
                }
            } else {
                status = lastAction.getActionName();
            }
            addNameValue(summaryData.getItemValues(), ITEM_STATUS, status);

            //Check if we are only return new/needing action items
            if (request.isOnlyNew()) {
                //Items of concern have actions that are still allowed
                if (actionsAvailable(request.getUserId(), ticket.getPayload(), ticket)) {
                    response.getSummaryObjects().add(summaryData);
                }
            } else {
                response.getSummaryObjects().add(summaryData);
            }

        }

    } catch (Exception e) {
        log.error("Error retriving summary " + source + " for provider: " + request.getProviderId(), e);

        ServiceError serviceError = new ServiceError();
        serviceError.setCode(ERR_CODE);
        serviceError.setText(e.getMessage());
        response.getErrorList().add(serviceError);
    }

    return response;
}

From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java

public org.socraticgrid.common.task.GetAlertFactsResponseType getAlertFacts(
        org.socraticgrid.common.task.GetAlertFactsRequestType request) {
    GetAlertFactsResponseType response = new GetAlertFactsResponseType();

    log.debug("Retrieving alert facts for user: " + request.getUserId());

    try {/*from   w w w  . j  av a  2 s  . c  om*/

        //If no user id is passed, just return
        if ((request.getUserId() == null) || request.getUserId().isEmpty()) {
            throw new Exception("User id empty.");
        }

        //Find allTickets based on data source
        List<AlertTicket> tickets = null;
        if (request.isUserProvider()) {
            tickets = findTickets(DATA_SOURCE_ALERT_FACTS, null, request.getUserId(), null);
        } else {
            tickets = findTickets(DATA_SOURCE_ALERT_FACTS, request.getUserId(), null, null);
        }

        log.debug("Found " + tickets.size() + " tickets found for user: " + request.getUserId());

        GregorianCalendar cal = new GregorianCalendar();
        List<Long> usedIds = new LinkedList<Long>();
        for (AlertTicket ticket : tickets) {

            //If the ticket has already been added, ignore
            if (usedIds.contains(ticket.getTicketId())) {
                continue;
            }
            usedIds.add(ticket.getTicketId());

            //Poplulate fact object
            AlertFact fact = new AlertFact();
            fact.setTicketId(ticket.getTicketUniqueId());
            cal.setTime(ticket.getAlertTimestamp());
            fact.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
            fact.setDescription(ticket.getDescription());
            fact.setPayload(ticket.getPayload());
            fact.setPriority(ticket.getPriority());
            PatientContext ptCtx = new PatientContext();
            ptCtx.setPatientName(ticket.getPatientName());
            //     ptCtx.setPatientFMPSSN(ticket.getPatientFMPSSN());
            ptCtx.setPatientSex(ticket.getPatientSex());
            ptCtx.setPatientUnitNumber(ticket.getPatientUnitNumber());
            fact.setPatient(ptCtx);

            //Go through action history
            //   deterimine status
            boolean isNewAlert = true;
            AlertAction lastAction = null;
            for (AlertAction action : ticket.getActionHistory()) {

                //Check if ticket is new for this user
                if ((request.getUserId() != null) && request.getUserId().equals(action.getUserId())
                        && ActionConstants.ACTION_READ.equals(action.getActionName())) {
                    isNewAlert = false;
                }

                //Set last action
                lastAction = action;
            }

            //Set appropriate status value
            String status = "";
            if (isNewAlert) {
                //The ticket may be new to this user, but if it is closed and no further
                //  action can be done, then set the status to the last action
                if (AlertUtil.isTickedClosed(ticket)) {
                    status = lastAction.getActionName();
                } else {
                    status = ALERT_STATUS_NEW;
                }
            } else {
                status = lastAction.getActionName();
            }
            fact.setStatus(status);

            //Add to list of facts
            response.getFactObjects().add(fact);
        }

    } catch (Exception e) {
        log.error("Error retriving alert facts for user: " + request.getUserId(), e);
        response.setStatusCode(ERR_CODE);
        response.setStatusDetail(e.getMessage());
    }

    return response;
}