Example usage for javax.xml.datatype XMLGregorianCalendar setTimezone

List of usage examples for javax.xml.datatype XMLGregorianCalendar setTimezone

Introduction

In this page you can find the example usage for javax.xml.datatype XMLGregorianCalendar setTimezone.

Prototype

public abstract void setTimezone(int offset);

Source Link

Document

Set the number of minutes in the timezone offset.

Usage

From source file:DatatypeAPIUsage.java

public static void main(String[] args) {
    try {// w  ww  .  ja  v  a  2 s .  com
        DatatypeFactory df = DatatypeFactory.newInstance();
        // my work number in milliseconds:
        Duration myPhone = df.newDuration(9054133519l);
        Duration myLife = df.newDuration(true, 29, 2, 15, 13, 45, 0);
        int compareVal = myPhone.compare(myLife);
        switch (compareVal) {
        case DatatypeConstants.LESSER:
            System.out.println("There are fewer milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.EQUAL:
            System.out.println("The same number of milliseconds are in my phone number and my lifespan.");
            break;
        case DatatypeConstants.GREATER:
            System.out.println("There are more milliseconds in my phone number than my lifespan.");
            break;
        case DatatypeConstants.INDETERMINATE:
            System.out.println("The comparison could not be carried out.");
        }

        // create a yearMonthDuration
        Duration ymDuration = df.newDurationYearMonth("P12Y10M");
        System.out.println("P12Y10M is of type: " + ymDuration.getXMLSchemaType());

        // create a dayTimeDuration (really this time)
        Duration dtDuration = df.newDurationDayTime("P10DT10H12M0S");
        System.out.println("P10DT10H12M0S is of type: " + dtDuration.getXMLSchemaType());

        // try to fool the factory!
        try {
            ymDuration = df.newDurationYearMonth("P12Y10M1D");
        } catch (IllegalArgumentException e) {
            System.out.println("'duration': P12Y10M1D is not 'yearMonthDuration'!!!");
        }

        XMLGregorianCalendar xgc = df.newXMLGregorianCalendar();
        xgc.setYear(1975);
        xgc.setMonth(DatatypeConstants.AUGUST);
        xgc.setDay(11);
        xgc.setHour(6);
        xgc.setMinute(44);
        xgc.setSecond(0);
        xgc.setMillisecond(0);
        xgc.setTimezone(5);
        xgc.add(myPhone);
        System.out.println("The approximate end of the number of milliseconds in my phone number was " + xgc);

        // adding a duration to XMLGregorianCalendar
        xgc.add(myLife);
        System.out.println("Adding the duration myLife to the above calendar:" + xgc);

        // create a new XMLGregorianCalendar using the string format of xgc.
        XMLGregorianCalendar xgcCopy = df.newXMLGregorianCalendar(xgc.toXMLFormat());

        // should be equal-if not what happened!!
        if (xgcCopy.compare(xgc) != DatatypeConstants.EQUAL) {
            System.out.println("oooops!");
        } else {
            System.out.println("Very good: " + xgc + " is equal to " + xgcCopy);
        }
    } catch (DatatypeConfigurationException dce) {
        System.err.println("error: Datatype error occurred - " + dce.getMessage());
        dce.printStackTrace(System.err);
    }
}

From source file:Main.java

public static XMLGregorianCalendar parse(long time, int timezone) {
    GregorianCalendar cal = new GregorianCalendar();

    cal.setTimeInMillis(time);/*from  ww  w .j a v a2 s.  c  o m*/
    XMLGregorianCalendar xCal = null;
    try {
        xCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        xCal.setTimezone(timezone);
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    return xCal;
}

From source file:Main.java

public static XMLGregorianCalendar parse(String time, int timezone) {
    XMLGregorianCalendar date = null;
    try {/*from w w w  .  ja  v a  2 s . c om*/
        if (time.indexOf(":") < 0) {
            time = time + "T00:00:00";
        }
        date = DatatypeFactory.newInstance().newXMLGregorianCalendar(time);
        date.setTimezone(timezone);
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    return date;
}

From source file:edu.harvard.i2b2.query.data.QueryConceptTreePanelData.java

public ConstrainByDate writeTimeConstraint() {
    ConstrainByDate timeConstrain = new ConstrainByDate();
    DTOFactory dtoFactory = new DTOFactory();

    TimeZone tz = Calendar.getInstance().getTimeZone();
    GregorianCalendar cal = new GregorianCalendar(tz);
    //cal.get(Calendar.ZONE_OFFSET);
    int zt_offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 60000;
    log.info("Timezone: " + tz.getID() + " : " + zt_offset);

    if (startTime() != -1) {
        ConstrainDateType constraindateType = new ConstrainDateType();
        XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(startYear(), startMonth() + 1,
                startDay());/*from ww w. ja  va2  s. co  m*/
        xmlC.setTimezone(zt_offset);//0);//-5*60);
        xmlC.setHour(0);
        xmlC.setMinute(0);
        xmlC.setSecond(0);
        constraindateType.setValue(xmlC);
        timeConstrain.setDateFrom(constraindateType);
    }

    if (endTime() != -1) {
        ConstrainDateType constraindateType = new ConstrainDateType();
        XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(endYear(), endMonth() + 1, endDay());
        xmlC.setTimezone(zt_offset);//0);//-5*60);
        xmlC.setHour(0);
        xmlC.setMinute(0);
        xmlC.setSecond(0);
        constraindateType.setValue(xmlC);
        timeConstrain.setDateTo(constraindateType);
    }
    return timeConstrain;
}

From source file:ejava.projects.edmv.xml.EDmvParserTest.java

public void testMonthParse() throws Exception {
    log.info("*** testCalendar ***");
    DatatypeFactory dataFactory = DatatypeFactory.newInstance();
    log.info("DataTypeFactory=" + dataFactory);
    XMLGregorianCalendar cal = dataFactory.newXMLGregorianCalendar();
    log.info("XMLGregorianCalendar=" + cal.getClass());

    cal.setMonth(GregorianCalendar.MARCH);
    String xml = cal.toXMLFormat();
    log.debug("cal=" + xml);
    dataFactory.newXMLGregorianCalendar(xml);

    cal.setTimezone(0);

    String format = "--01";
    try {/*from  w w  w. j  a va2 s.  c o m*/
        XMLGregorianCalendar xCal = dataFactory.newXMLGregorianCalendar(format);
        log.info("successfully parsed:" + format + ", xCal=" + xCal.toXMLFormat());
        format = "--01--";
        xCal = dataFactory.newXMLGregorianCalendar(format);
        log.info("successfully parsed:" + format + ", xCal=" + xCal.toXMLFormat());
    } catch (Exception ex) {
        log.error("failed to parse:" + format);
        fail("failed to parse:" + format);
    }
}

From source file:ejava.projects.edmv.xml.EDmvBindingTest.java

public void testCalendar() throws Exception {
    log.info("*** testCalendar ***");
    DatatypeFactory dataFactory = DatatypeFactory.newInstance();
    log.info("DataTypeFactory=" + dataFactory);
    XMLGregorianCalendar cal = dataFactory.newXMLGregorianCalendar();
    log.info("XMLGregorianCalendar=" + cal.getClass());
    cal.setMonth(GregorianCalendar.MARCH);
    String xml = cal.toXMLFormat();
    log.debug("cal=" + xml);
    dataFactory.newXMLGregorianCalendar(xml);

    cal.setTimezone(0);

    Calendar jCal = Calendar.getInstance();
    jCal.clear();/*from ww w.  j  a v  a2s .co  m*/
    jCal.set(Calendar.MONTH, Calendar.MARCH);
    DateFormat df = DateFormat.getDateInstance();
    String dfString = df.format(jCal.getTime());
    log.debug("calendar=" + dfString);

    String format = "--01";
    try {
        XMLGregorianCalendar xCal = dataFactory.newXMLGregorianCalendar(format);
        log.info("successfully parsed:" + format + ", xCal=" + xCal.toXMLFormat());
        format = "--01--";
        xCal = dataFactory.newXMLGregorianCalendar(format);
        log.info("successfully parsed:" + format + ", xCal=" + xCal.toXMLFormat());
    } catch (Exception ex) {
        log.error("failed to parse:" + format);
        fail("failed to parse:" + format);
    }
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

/**
 * copy participant info//from  w  ww .ja  v a 2s .  c  om
 */
private ParticipantType copyParticipant(ObjectFactory factory, Participant part) {
    final ParticipantType retVal = factory.createParticipantType();

    if (part.getId() != null)
        retVal.setId(part.getId());

    retVal.setName(part.getName());

    final LocalDate bday = part.getBirthDate();
    if (bday != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final XMLGregorianCalendar cal = df
                    .newXMLGregorianCalendar(GregorianCalendar.from(bday.atStartOfDay(ZoneId.systemDefault())));
            cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
            retVal.setBirthday(cal);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

    final Period age = part.getAge(null);
    if (age != null) {
        try {
            final DatatypeFactory df = DatatypeFactory.newInstance();
            final Duration ageDuration = df.newDuration(true, age.getYears(), age.getMonths(), age.getDays(), 0,
                    0, 0);
            retVal.setAge(ageDuration);
        } catch (DatatypeConfigurationException e) {
            LOGGER.log(Level.WARNING, e.toString(), e);
        }
    }

    retVal.setEducation(part.getEducation());
    retVal.setGroup(part.getGroup());

    final String lang = part.getLanguage();
    final String langs[] = (lang != null ? lang.split(",") : new String[0]);
    for (String l : langs) {
        retVal.getLanguage().add(StringUtils.strip(l));
    }

    if (part.getSex() == Sex.MALE)
        retVal.setSex(SexType.MALE);
    else if (part.getSex() == Sex.FEMALE)
        retVal.setSex(SexType.FEMALE);

    ParticipantRole prole = part.getRole();
    if (prole == null)
        prole = ParticipantRole.TARGET_CHILD;
    retVal.setRole(prole.toString());

    // create ID based on role if possible
    if (retVal.getId() == null && prole != null) {
        if (prole == ParticipantRole.TARGET_CHILD) {
            retVal.setId("CHI");
        } else if (prole == ParticipantRole.MOTHER) {
            retVal.setId("MOT");
        } else if (prole == ParticipantRole.FATHER) {
            retVal.setId("FAT");
        } else if (prole == ParticipantRole.INTERVIEWER) {
            retVal.setId("INT");
        } else {
            retVal.setId("p" + (++pIdx));
        }
    }

    retVal.setSES(part.getSES());

    return retVal;
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

/**
 * Create a new jaxb version of the session
 * //from   www.  j av  a  2s. co m
 * @param session
 * @return an version of the session use-able by jaxb 
 */
private JAXBElement<SessionType> toSessionType(Session session) throws IOException {
    final ObjectFactory factory = new ObjectFactory();
    final SessionType retVal = factory.createSessionType();

    // header data
    retVal.setVersion("PB1.2");
    retVal.setId(session.getName());
    retVal.setCorpus(session.getCorpus());

    final HeaderType headerData = factory.createHeaderType();
    if (session.getMediaLocation() != null && session.getMediaLocation().length() > 0) {
        headerData.setMedia(session.getMediaLocation());
    }
    final LocalDate date = (session.getDate() == null ? LocalDate.now() : session.getDate());
    try {
        final DatatypeFactory df = DatatypeFactory.newInstance();
        final XMLGregorianCalendar cal = df
                .newXMLGregorianCalendar(GregorianCalendar.from(date.atStartOfDay(ZoneId.systemDefault())));
        cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
        headerData.setDate(cal);
    } catch (DatatypeConfigurationException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    final String lang = session.getLanguage();
    if (lang != null && lang.length() > 0) {
        final String langs[] = lang.split("\\p{Space}");
        for (String l : langs) {
            headerData.getLanguage().add(l);
        }
    }
    retVal.setHeader(headerData);

    final TranscriptType transcript = factory.createTranscriptType();
    // commets
    for (int i = 0; i < session.getMetadata().getNumberOfComments(); i++) {
        final Comment c = session.getMetadata().getComment(i);
        final CommentType ct = copyComment(factory, c);
        transcript.getUOrComment().add(ct);
    }

    // participants
    final ParticipantsType parts = factory.createParticipantsType();
    for (int i = 0; i < session.getParticipantCount(); i++) {
        final Participant part = session.getParticipant(i);
        final ParticipantType pt = copyParticipant(factory, part);
        parts.getParticipant().add(pt);
    }
    retVal.setParticipants(parts);

    // transcribers
    final TranscribersType tt = factory.createTranscribersType();
    for (int i = 0; i < session.getTranscriberCount(); i++) {
        final Transcriber tr = session.getTranscriber(i);
        final TranscriberType trt = copyTranscriber(factory, tr);
        tt.getTranscriber().add(trt);
    }
    retVal.setTranscribers(tt);

    // tier info/ordering
    final UserTiersType utt = factory.createUserTiersType();
    for (int i = 0; i < session.getUserTierCount(); i++) {
        final TierDescription td = session.getUserTier(i);
        final UserTierType tierType = copyTierDescription(factory, td);
        utt.getUserTier().add(tierType);
    }
    retVal.setUserTiers(utt);

    final TierOrderType tot = factory.createTierOrderType();
    for (TierViewItem tvi : session.getTierView()) {
        final TvType tvt = copyTierViewItem(factory, tvi);
        tot.getTier().add(tvt);
    }
    retVal.setTierOrder(tot);

    // session data
    for (int i = 0; i < session.getRecordCount(); i++) {
        final Record record = session.getRecord(i);

        // insert comments first
        for (int j = 0; j < record.getNumberOfComments(); j++) {
            final Comment com = record.getComment(j);
            final CommentType ct = copyComment(factory, com);
            transcript.getUOrComment().add(ct);
        }

        // copy record data
        final RecordType rt = copyRecord(factory, retVal, record);

        rt.setId(record.getUuid().toString());

        if (record.isExcludeFromSearches())
            rt.setExcludeFromSearches(record.isExcludeFromSearches());

        // setup participant
        if (record.getSpeaker() != null) {
            for (ParticipantType pt : parts.getParticipant()) {
                if (pt.getId().equals(record.getSpeaker().getId())) {
                    rt.setSpeaker(pt);
                    break;
                }
            }
        }

        transcript.getUOrComment().add(rt);
    }
    retVal.setTranscript(transcript);

    return factory.createSession(retVal);
}

From source file:ebay.dts.client.BulkDataExchangeActions.java

private static XMLGregorianCalendar parseDateTime(String cal) throws DatatypeConfigurationException {

    DatatypeFactory factory1 = DatatypeFactory.newInstance();
    XMLGregorianCalendar calendar1 = factory1.newXMLGregorianCalendar();
    String[] dateItems;//w w  w . j  a va  2 s .  c  o m
    try {
        // df.parse(cal);
        if (cal.indexOf("_") == -1) {
            dateItems = cal.split("-");
            calendar1.setYear(Integer.parseInt(dateItems[0]));
            calendar1.setMonth(Integer.parseInt(dateItems[1]));
            calendar1.setDay(Integer.parseInt(dateItems[2]));
            // calendar1.setTime(00, 00, 00,000);
            calendar1.setTime(00, 00, 00);
        } else {
            String[] parts = cal.split("_");
            dateItems = parts[0].split("-");
            String[] timeItems = parts[1].split(":");
            calendar1.setYear(Integer.parseInt(dateItems[0]));
            calendar1.setMonth(Integer.parseInt(dateItems[1]));
            calendar1.setDay(Integer.parseInt(dateItems[2]));
            if (timeItems.length != 0) {
                switch (timeItems.length) {
                case 1: {
                    calendar1.setTime(Integer.parseInt(timeItems[0]), 00, 00, 000);
                    break;
                }
                case 2: {
                    calendar1.setTime(Integer.parseInt(timeItems[0]), Integer.parseInt(timeItems[1]), 00, 000);
                    break;
                }
                case 3: {
                    calendar1.setTime(Integer.parseInt(timeItems[0]), Integer.parseInt(timeItems[1]),
                            Integer.parseInt(timeItems[2]), 000);
                    break;
                }
                case 4: {
                    calendar1.setTime(Integer.parseInt(timeItems[0]), Integer.parseInt(timeItems[1]),
                            Integer.parseInt(timeItems[2]), Integer.parseInt(timeItems[3]));
                    break;
                }
                }

            }
        }

        // get here and we know the format is correct
    } catch (java.lang.NumberFormatException e) {
        logger.error("NumberFormatException caught when parse the DateTime string: " + cal);
        return null;
    }

    calendar1.setTimezone(0);
    logger.debug(calendar1.toXMLFormat());
    return calendar1;
}

From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java

private void jForwardButtonActionPerformed(java.awt.event.ActionEvent evt) {
    System.out.println("Loading previous queries for: " + System.getProperty("user"));

    cellStatus = "";
    String searchStr = jSearchStringTextField.getText();
    int category = jCategoryComboBox.getSelectedIndex();
    int strategy = jContainComboBox.getSelectedIndex();

    curCreationDate = previousQueries.get(previousQueries.size() - 1).creationTime();
    ////////////////////////////////////////////////
    SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");//.getDateInstance();
    Date date = null;//from w  w  w. j  ava  2  s .c om
    try {
        date = df.parse(this.jStartTimeTextField.getText());
    } catch (Exception e) {
        e.printStackTrace();
    }
    DTOFactory dtoFactory = new DTOFactory();

    TimeZone tz = Calendar.getInstance().getTimeZone();
    GregorianCalendar cal = new GregorianCalendar(tz);
    cal.setTime(date);
    //cal.get(Calendar.ZONE_OFFSET);
    int zt_offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 60000;
    //log.info("Timezone: "+tz.getID()+" : "+zt_offset);

    //if (startTime() != -1) {
    ConstrainDateType constraindateType = new ConstrainDateType();
    XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(cal.get(GregorianCalendar.YEAR),
            cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH));
    xmlC.setTimezone(zt_offset);//0);//-5*60);
    xmlC.setHour(cal.get(GregorianCalendar.HOUR_OF_DAY));
    xmlC.setMinute(cal.get(GregorianCalendar.MINUTE));
    xmlC.setSecond(cal.get(GregorianCalendar.SECOND));
    constraindateType.setValue(xmlC);
    //timeConstrain.setDateFrom(constraindateType);
    //}
    ////////////////////////////////////////////////
    String xmlStr = writePagingQueryXML("", category, strategy, false, xmlC);//curCreationDate);
    // System.out.println(xmlStr);

    String responseStr = null;
    if (System.getProperty("webServiceMethod").equals("SOAP")) {
        responseStr = QueryListNamesClient.sendQueryRequestSOAP(xmlStr);
    } else {
        responseStr = QueryListNamesClient.sendFindQueryRequestREST(xmlStr);
    }

    if (responseStr.equalsIgnoreCase("CellDown")) {
        cellStatus = new String("CellDown");
        return; //"CellDown";
    }

    try {
        JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();
        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseStr);
        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
        BodyType bt = messageType.getMessageBody();
        MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper().getObjectByClass(
                bt.getAny(), edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.MasterResponseType.class);
        for (Condition status : masterResponseType.getStatus().getCondition()) {
            if (status.getType().equals("ERROR"))
                cellStatus = new String("CellDown");
        }
        previousQueries = new ArrayList<QueryMasterData>();
        for (QueryMasterType queryMasterType : masterResponseType.getQueryMaster()) {
            QueryMasterData tmpData;
            tmpData = new QueryMasterData();
            XMLGregorianCalendar cldr = queryMasterType.getCreateDate();
            tmpData.name(
                    queryMasterType.getName() + " [" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay())
                            + "-" + addZero(cldr.getYear()) + " ]" + " [" + queryMasterType.getUserId() + "]");
            tmpData.creationTime(cldr);//.clone());
            tmpData.creationTimeStr(
                    addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear())
                            + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond());
            tmpData.tooltip("A query run by " + queryMasterType.getUserId());// System.
            // getProperty
            // ("user"));
            tmpData.visualAttribute("CA");
            tmpData.xmlContent(null);
            tmpData.id(queryMasterType.getQueryMasterId());
            tmpData.userId(queryMasterType.getUserId()); // System.getProperty
            // ("user"));
            previousQueries.add(tmpData);
        }

        if (previousQueries.size() == 0) {
            final JPanel parent = this;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(parent, "No results were found.", "Not Found",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            });
            return;
        }

        if (cellStatus.equalsIgnoreCase("")) {
            reset(200, false, false);
        } else if (cellStatus.equalsIgnoreCase("CellDown")) {
            final JPanel parent = this;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(parent,
                            "Trouble with connection to the remote server, "
                                    + "this is often a network error, please try again",
                            "Network Error", JOptionPane.INFORMATION_MESSAGE);
                }
            });
        }
        return;
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
}