Example usage for javax.xml.datatype DatatypeFactory newXMLGregorianCalendar

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

Introduction

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

Prototype

public abstract XMLGregorianCalendar newXMLGregorianCalendar(final GregorianCalendar cal);

Source Link

Document

Create an XMLGregorianCalendar from a GregorianCalendar .

Usage

From source file:org.overlord.sramp.common.derived.XsdDeriverTest.java

/**
 * Test method for {@link org.overlord.sramp.common.repository.derived.XsdDeriver#derive(org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType, java.io.InputStream)}.
 */// w w w  .  j  av a 2 s.  c  o  m
@Test
public void testDerive() throws Exception {
    DatatypeFactory dtFactory = DatatypeFactory.newInstance();

    XsdDeriver deriver = new XsdDeriver();
    XsdDocument testSrcArtifact = new XsdDocument();
    testSrcArtifact.setArtifactType(BaseArtifactEnum.XSD_DOCUMENT);
    testSrcArtifact.setUuid(UUID.randomUUID().toString());
    testSrcArtifact.setName("ws-humantask.xsd"); //$NON-NLS-1$
    testSrcArtifact.setVersion("1.0"); //$NON-NLS-1$
    testSrcArtifact.setContentEncoding("UTF-8"); //$NON-NLS-1$
    testSrcArtifact.setContentType("application/xml"); //$NON-NLS-1$
    testSrcArtifact.setContentSize(31723L);
    testSrcArtifact.setCreatedBy("anonymous"); //$NON-NLS-1$
    XMLGregorianCalendar xmlGC = dtFactory.newXMLGregorianCalendar(new GregorianCalendar());
    testSrcArtifact.setCreatedTimestamp(xmlGC);
    testSrcArtifact.setDescription("Hello world."); //$NON-NLS-1$
    testSrcArtifact.setLastModifiedBy("anonymous"); //$NON-NLS-1$
    testSrcArtifact.setLastModifiedTimestamp(xmlGC);

    InputStream testSrcContent = null;
    try {
        testSrcContent = getClass().getResourceAsStream("/sample-files/xsd/ws-humantask.xsd"); //$NON-NLS-1$
        Collection<BaseArtifactType> derivedArtifacts = deriver.derive(testSrcArtifact, testSrcContent);
        Assert.assertNotNull(derivedArtifacts);
        Assert.assertEquals(83, derivedArtifacts.size());
        int numElements = 0;
        int numAttributes = 0;
        int numSimpleTypes = 0;
        int numComplexTypes = 0;
        Set<String> elementNames = new HashSet<String>();
        Set<String> attributeNames = new HashSet<String>();
        Set<String> simpleTypeNames = new HashSet<String>();
        Set<String> complexTypeNames = new HashSet<String>();
        for (BaseArtifactType derivedArtifact : derivedArtifacts) {
            DerivedArtifactType dat = (DerivedArtifactType) derivedArtifact;
            Assert.assertEquals(testSrcArtifact.getUuid(), dat.getRelatedDocument().getValue());
            Assert.assertEquals(DocumentArtifactEnum.XSD_DOCUMENT, dat.getRelatedDocument().getArtifactType());

            if (dat instanceof ElementDeclaration) {
                numElements++;
                elementNames.add(((ElementDeclaration) dat).getNCName());
            } else if (dat instanceof AttributeDeclaration) {
                numAttributes++;
                attributeNames.add(((AttributeDeclaration) dat).getNCName());
            } else if (dat instanceof SimpleTypeDeclaration) {
                numSimpleTypes++;
                simpleTypeNames.add(((SimpleTypeDeclaration) dat).getNCName());
            } else if (dat instanceof ComplexTypeDeclaration) {
                numComplexTypes++;
                complexTypeNames.add(((ComplexTypeDeclaration) dat).getNCName());
            }
        }
        // Verify the counts
        Assert.assertEquals(17, numElements);
        Assert.assertEquals(0, numAttributes);
        Assert.assertEquals(5, numSimpleTypes);
        Assert.assertEquals(61, numComplexTypes);
        Assert.assertEquals(83, numElements + numAttributes + numSimpleTypes + numComplexTypes);

        // Verify the names
        Assert.assertEquals(EXPECTED_ELEMENT_NAMES, elementNames);
        Assert.assertEquals(EXPECTED_ATTRIBUTE_NAMES, attributeNames);
        Assert.assertEquals(EXPECTED_SIMPLE_TYPE_NAMES, simpleTypeNames);
        Assert.assertEquals(EXPECTED_COMPLEX_TYPE_NAMES, complexTypeNames);
    } finally {
        IOUtils.closeQuietly(testSrcContent);
    }
}

From source file:org.overlord.sramp.server.atom.services.AuditResourceTest.java

@Test
public void testCreate() throws Exception {
    Document pdf = addPdf();/*from ww w  .  ja v a  2  s  .c om*/

    DatatypeFactory dtFactory = DatatypeFactory.newInstance();

    // Create another audit entry
    ClientRequest request = new ClientRequest(generateURL("/s-ramp/audit/artifact/" + pdf.getUuid())); //$NON-NLS-1$
    XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar) Calendar.getInstance());
    AuditEntry auditEntry = new AuditEntry();
    auditEntry.setType("junit:test1"); //$NON-NLS-1$
    auditEntry.setWhen(now);
    auditEntry.setWho("junituser"); //$NON-NLS-1$
    AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "junit:item"); //$NON-NLS-1$
    AuditUtils.setAuditItemProperty(item, "foo", "bar"); //$NON-NLS-1$ //$NON-NLS-2$
    AuditUtils.setAuditItemProperty(item, "hello", "world"); //$NON-NLS-1$ //$NON-NLS-2$

    request.body(MediaType.APPLICATION_AUDIT_ENTRY_XML_TYPE, auditEntry);
    ClientResponse<Entry> response = request.post(Entry.class);
    Entry entry = response.getEntity();
    AuditEntry re = SrampAtomUtils.unwrap(entry, AuditEntry.class);
    Assert.assertNotNull(re);
    Assert.assertNotNull(re.getUuid());
    Assert.assertEquals("junituser", re.getWho()); //$NON-NLS-1$
    Assert.assertEquals(1, re.getAuditItem().size());
    Assert.assertEquals("junit:item", re.getAuditItem().iterator().next().getType()); //$NON-NLS-1$
    Assert.assertEquals(2, re.getAuditItem().iterator().next().getProperty().size());

    // List all the audit entries
    request = new ClientRequest(generateURL("/s-ramp/audit/artifact/" + pdf.getUuid())); //$NON-NLS-1$
    Feed auditEntryFeed = request.get(Feed.class).getEntity();
    Assert.assertNotNull(auditEntryFeed);
    List<Entry> entries = auditEntryFeed.getEntries();
    Assert.assertEquals(2, entries.size());

    // Get just the custom entry we created
    request = new ClientRequest(generateURL("/s-ramp/audit/artifact/" + pdf.getUuid() + "/" + re.getUuid())); //$NON-NLS-1$ //$NON-NLS-2$
    response = request.get(Entry.class);
    entry = response.getEntity();
    re = SrampAtomUtils.unwrap(entry, AuditEntry.class);
    Assert.assertNotNull(re);
    Assert.assertNotNull(re.getUuid());
    Assert.assertEquals("junituser", re.getWho()); //$NON-NLS-1$
    Assert.assertEquals(1, re.getAuditItem().size());
    Assert.assertEquals("junit:item", re.getAuditItem().iterator().next().getType()); //$NON-NLS-1$
    Assert.assertEquals(2, re.getAuditItem().iterator().next().getProperty().size());
}

From source file:org.overlord.sramp.test.server.atom.services.AuditResourceTest.java

@Test
public void testCreate() throws Exception {
    Document pdf = addPdf();/*from   w  ww .j  a  v  a  2s. c om*/

    DatatypeFactory dtFactory = DatatypeFactory.newInstance();

    // Create another audit entry
    ClientRequest request = clientRequest("/s-ramp/audit/artifact/" + pdf.getUuid()); //$NON-NLS-1$
    XMLGregorianCalendar now = dtFactory.newXMLGregorianCalendar((GregorianCalendar) Calendar.getInstance());
    AuditEntry auditEntry = new AuditEntry();
    auditEntry.setType("junit:test1"); //$NON-NLS-1$
    auditEntry.setWhen(now);
    auditEntry.setWho(getUsername());
    AuditItemType item = AuditUtils.getOrCreateAuditItem(auditEntry, "junit:item"); //$NON-NLS-1$
    AuditUtils.setAuditItemProperty(item, "foo", "bar"); //$NON-NLS-1$ //$NON-NLS-2$
    AuditUtils.setAuditItemProperty(item, "hello", "world"); //$NON-NLS-1$ //$NON-NLS-2$

    request.body(MediaType.APPLICATION_AUDIT_ENTRY_XML_TYPE, auditEntry);
    ClientResponse<Entry> response = request.post(Entry.class);
    Entry entry = response.getEntity();
    AuditEntry re = SrampAtomUtils.unwrap(entry, AuditEntry.class);
    Assert.assertNotNull(re);
    Assert.assertNotNull(re.getUuid());
    Assert.assertEquals(getUsername(), re.getWho());
    Assert.assertEquals(1, re.getAuditItem().size());
    Assert.assertEquals("junit:item", re.getAuditItem().iterator().next().getType()); //$NON-NLS-1$
    Assert.assertEquals(2, re.getAuditItem().iterator().next().getProperty().size());

    // List all the audit entries
    request = clientRequest("/s-ramp/audit/artifact/" + pdf.getUuid()); //$NON-NLS-1$
    Feed auditEntryFeed = request.get(Feed.class).getEntity();
    Assert.assertNotNull(auditEntryFeed);
    List<Entry> entries = auditEntryFeed.getEntries();
    Assert.assertEquals(2, entries.size());

    // Get just the custom entry we created
    request = clientRequest("/s-ramp/audit/artifact/" + pdf.getUuid() + "/" + re.getUuid()); //$NON-NLS-1$ //$NON-NLS-2$
    response = request.get(Entry.class);
    entry = response.getEntity();
    re = SrampAtomUtils.unwrap(entry, AuditEntry.class);
    Assert.assertNotNull(re);
    Assert.assertNotNull(re.getUuid());
    Assert.assertEquals(getUsername(), re.getWho());
    Assert.assertEquals(1, re.getAuditItem().size());
    Assert.assertEquals("junit:item", re.getAuditItem().iterator().next().getType()); //$NON-NLS-1$
    Assert.assertEquals(2, re.getAuditItem().iterator().next().getProperty().size());
}

From source file:org.ow2.aspirerfid.beg.capture.CaptureReport.java

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

From source file:org.ow2.aspirerfid.demos.warehouse.management.beg.CaptureReport.java

private void handleReports(ECReports reports) throws IOException, JAXBException {
    log.debug("**********************Handling incomming reports****************************");

    // get the current time and set the eventTime
    XMLGregorianCalendar now = null;
    try {//from  w  w w .j av a  2s . c o  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();
    }

    List<ECReport> theReports = reports.getReports().getReport();
    // collect all the tags
    List<EPC> epcs = new LinkedList<EPC>();
    if (theReports != null) {
        for (ECReport report : theReports) {
            // log.debug("Report Count: "+report.getGroup().size());
            log.debug("***************Report Name:" + report.getReportName() + "**************");
            if (report.getGroup() != null) {
                for (ECReportGroup group : report.getGroup()) {

                    if (WarehouseManagement.getEntryDateTextField().equals("")) {
                        WarehouseManagement.setEntryDateTextField(
                                now.getDay() + "/" + now.getMonth() + "/" + now.getYear());
                    }
                    if (WarehouseManagement.getEntryHourTextField().equals("")) {
                        WarehouseManagement.setEntryHourTextField(
                                now.getHour() + ":" + now.getMinute() + ":" + now.getSecond());
                    }

                    WarehouseManagement.setZoneIDTextField(zoneID);
                    WarehouseManagement.setWarehouseIDTextField(warehouseID);

                    log.debug("Group Count: " + group.getGroupCount().getCount());
                    log.debug("Group Name: " + group.getGroupName());
                    if (group.getGroupList() != null) {
                        deliveredItem = null;

                        // warehousemen
                        if (group.getGroupName().equals(warehousemenGroupName)) {
                            for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                                if (member.getEpc() != null) {
                                    WarehouseManagement
                                            .setUserIDTextField(member.getTag().getValue().split(":")[4]);
                                }
                            }
                        }

                        // Invoice
                        if (group.getGroupName().equals(invoiceGroupName)) {
                            for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                                if (member.getEpc() != null) {
                                    WarehouseManagement
                                            .setInvoiceIDTextField(member.getTag().getValue().split(":")[4]);
                                    WarehouseManagement.setOfferingDateTextField("22/05/08");
                                    WarehouseManagement.setOfferingHourTextField("10:53:22");
                                }
                            }
                        }
                        //                     // Small Packets
                        //                     if (group.getGroupName().equals("urn:epc:pat:gid-96:145.56.*")) {
                        //                        for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                        //                           if (member.getEpc() != null) {
                        //                              // WarehouseManagement.setInvoiceIDTextField(member.getTag().getValue().split(":")[4]);
                        //                           }
                        //                        }
                        //                     }
                        //                     // Medium Packets
                        //                     if (group.getGroupName().equals("urn:epc:pat:gid-96:145.87.*")) {
                        //                        for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                        //                           if (member.getEpc() != null) {
                        //                              // WarehouseManagement.setInvoiceIDTextField(member.getTag().getValue().split(":")[4]);
                        //                           }
                        //                        }
                        //                     }

                        for (int i = 0; i < nOFmerchandise; i++) {

                            if (group.getGroupName().equals(packetsGroupName[i])) {
                                BigInteger quantity = new BigInteger(packetsQuantity[i]);
                                BigInteger expectedQuantity = new BigInteger(packetsExpectedQuantity[i]);
                                BigInteger quantityDelivered = new BigInteger(
                                        (group.getGroupCount().getCount()) + "");
                                BigInteger quantityRemain = quantity.add(quantityDelivered.negate());

                                for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                                    if (member.getEpc() != null) {
                                        deliveredItem = new DeliveredItem();
                                        deliveredItem.setCompany(packetsCompany[i]);
                                        deliveredItem.setDeliveryDate(
                                                now.getDay() + "/" + now.getMonth() + "/" + now.getYear());
                                        deliveredItem.setDescription(packetsDescription[i]);
                                        deliveredItem.setExpectedQuantity(expectedQuantity);
                                        deliveredItem.setMeasurementID(packetsMeasurementID[i]);
                                        deliveredItem.setQuantity(quantity);
                                        deliveredItem.setQuantityDelivered(quantityDelivered);
                                        deliveredItem.setQuantityRemain(quantityRemain);
                                        deliveredItem.setItemCode(member.getTag().getValue().split(":")[4]);
                                        WarehouseManagement.updateDeliveryTableModel(deliveredItem);
                                        deliveredItem = null;
                                    }
                                }
                            }
                        }

                        // Print All
                        for (ECReportGroupListMember member : group.getGroupList().getMember()) {
                            if (member.getEpc() != null) {
                                log.debug("***Recieved Group Values***");
                                log.debug("RawDecimal Value: " + member.getRawDecimal().getValue());
                                {
                                    if (!(member.getEpc() == null))
                                        epcs.add(member.getEpc());
                                    log.debug("Epc Value: " + member.getEpc().getValue());
                                    if ((member.getEpc() == null))
                                        log.debug("Epc Value: null");
                                }
                                log.debug("RawHex Value: " + member.getRawHex().getValue());
                                log.debug("Tag Value: " + member.getTag().getValue());
                                // log.debug("Group
                                // Value:"+member.getExtension().getFieldList().toString());

                            }
                        }

                    }
                }
            }
        }
    }
    if (epcs.size() == 0) {
        log.debug("no epc received - generating no event");
        return;
    }
}

From source file:org.ow2.aspirerfid.ide.masterdata.tools.MasterDataCaptureClient.java

private XMLGregorianCalendar getCurrentTime() {
    // get the current time and set the eventTime
    XMLGregorianCalendar now = null;
    try {//w ww  .jav a2  s . c o  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.ow2.aspirerfid.programmableengine.epcisclient.MasterDataCaptureClient.java

public XMLGregorianCalendar getCurrentTime() {
    // get the current time and set the eventTime
    XMLGregorianCalendar now = null;
    try {//from ww w  .ja v a  2s . com
        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 {//  w w w  .  ja va 2s  .c o m
            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.talend.components.marketo.runtime.client.MarketoSOAPClient.java

/**
 * In getMultipleLeadsJSON you have to add includeAttributes base fields like Email. Otherwise, they return null from
 * API. WTF ?!? It's like that.../*from ww w  .j ava  2s  . co m*/
 */
@Override
public MarketoRecordResult getMultipleLeads(TMarketoInputProperties parameters, String offset) {
    LOG.debug("MarketoSOAPClient.getMultipleLeadsJSON with {}", parameters.leadSelectorSOAP.getValue());
    Schema schema = parameters.schemaInput.schema.getValue();
    Map<String, String> mappings = parameters.mappingInput.getNameMappingsForMarketo();
    int bSize = parameters.batchSize.getValue();
    //
    // Create Request
    //
    ParamsGetMultipleLeads request = new ParamsGetMultipleLeads();
    // LeadSelect
    //
    // Request Using LeadKey Selector
    //
    if (parameters.leadSelectorSOAP.getValue().equals(LeadKeySelector)) {
        LOG.info("LeadKeySelector - Key type:  {} with value : {}.",
                parameters.leadKeyTypeSOAP.getValue().toString(), parameters.leadKeyValues.getValue());
        LeadKeySelector keySelector = new LeadKeySelector();
        keySelector.setKeyType(valueOf(parameters.leadKeyTypeSOAP.getValue().toString()));
        ArrayOfString aos = new ArrayOfString();
        String[] keys = parameters.leadKeyValues.getValue().split("(,|;|\\s)");
        for (String s : keys) {
            LOG.debug("Adding leadKeyValue : {}.", s);
            aos.getStringItems().add(s);
        }
        keySelector.setKeyValues(aos);
        request.setLeadSelector(keySelector);
    } else
    //
    // Request Using LastUpdateAtSelector
    //

    if (parameters.leadSelectorSOAP.getValue().equals(LastUpdateAtSelector)) {
        LOG.debug("LastUpdateAtSelector - since {} to  {}.", parameters.oldestUpdateDate.getValue(),
                parameters.latestUpdateDate.getValue());
        LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
        try {
            DatatypeFactory factory = newInstance();
            Date oldest = MarketoUtils.parseDateString(parameters.oldestUpdateDate.getValue());
            Date latest = MarketoUtils.parseDateString(parameters.latestUpdateDate.getValue());
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(latest);
            JAXBElement<XMLGregorianCalendar> until = objectFactory
                    .createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));
            GregorianCalendar since = new GregorianCalendar();
            since.setTime(oldest);
            leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
            leadSelector.setLatestUpdatedAt(until);
            request.setLeadSelector(leadSelector);
        } catch (ParseException | DatatypeConfigurationException e) {
            LOG.error("Error for LastUpdateAtSelector : {}.", e.getMessage());
            throw new ComponentException(e);
        }
    } else
    //
    // Request Using StaticList Selector
    //
    if (parameters.leadSelectorSOAP.getValue().equals(StaticListSelector)) {
        LOG.info("StaticListSelector - List type : {} with value : {}.", parameters.listParam.getValue(),
                parameters.listParamListName.getValue());

        StaticListSelector staticListSelector = new StaticListSelector();
        if (parameters.listParam.getValue().equals(STATIC_LIST_NAME)) {
            JAXBElement<String> listName = objectFactory
                    .createStaticListSelectorStaticListName(parameters.listParamListName.getValue());
            staticListSelector.setStaticListName(listName);

        } else {
            // you can find listId by examining the URL : https://app-abq.marketo.com/#ST29912B2
            // #ST29912B2 :
            // #ST -> Static list identifier
            // 29912 -> our list FIELD_ID !
            // B2 -> tab in the UI
            JAXBElement<Integer> listId = objectFactory
                    .createStaticListSelectorStaticListId(parameters.listParamListId.getValue()); //
            staticListSelector.setStaticListId(listId);
        }
        request.setLeadSelector(staticListSelector);
    } else {
        // Duh !
        LOG.error("Unknown LeadSelector : {}.", parameters.leadSelectorSOAP.getValue());
        throw new ComponentException(new Exception(
                "Incorrect parameter value for LeadSelector : " + parameters.leadSelectorSOAP.getValue()));
    }
    // attributes
    // curiously we have to put some basic fields like Email in attributes if we have them feed...
    ArrayOfString attributes = new ArrayOfString();
    for (String s : mappings.values()) {
        attributes.getStringItems().add(s);
    }
    attributes.getStringItems().add("Company");
    request.setIncludeAttributes(attributes);
    // batchSize : another curious behavior... Don't seem to work properly with leadKeySelector...
    // nevertheless, the server automatically adjust batch size according request.
    JAXBElement<Integer> batchSize = new ObjectFactory().createParamsGetMultipleLeadsBatchSize(bSize);
    request.setBatchSize(batchSize);
    // stream position
    if (offset != null && !offset.isEmpty()) {
        request.setStreamPosition(new ObjectFactory().createParamsGetMultipleLeadsStreamPosition(offset));
    }
    //
    //
    // Request execution
    //
    SuccessGetMultipleLeads result = null;
    MarketoRecordResult mkto = new MarketoRecordResult();
    try {
        result = getPort().getMultipleLeads(request, header);
    } catch (Exception e) {
        LOG.error("Lead not found : {}.", e.getMessage());
        mkto.setSuccess(false);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, e.getMessage())));
        return mkto;
    }

    if (result == null || result.getResult().getReturnCount() == 0) {
        LOG.debug(MESSAGE_REQUEST_RETURNED_0_MATCHING_LEADS);
        mkto.setSuccess(true);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, MESSAGE_NO_LEADS_FOUND)));
        mkto.setRecordCount(0);
        mkto.setRemainCount(0);
        return mkto;
    } else {

        String streamPos = result.getResult().getNewStreamPosition();
        int recordCount = result.getResult().getReturnCount();
        int remainCount = result.getResult().getRemainingCount();

        // Process results
        List<IndexedRecord> results = convertLeadRecords(
                result.getResult().getLeadRecordList().getValue().getLeadRecords(), schema, mappings);

        return new MarketoRecordResult(true, streamPos, recordCount, remainCount, results);
    }
}

From source file:org.talend.components.marketo.runtime.client.MarketoSOAPClient.java

@Override
public MarketoRecordResult getLeadChanges(TMarketoInputProperties parameters, String offset) {
    Schema schema = parameters.schemaInput.schema.getValue();
    Map<String, String> mappings = parameters.mappingInput.getNameMappingsForMarketo();
    int bSize = parameters.batchSize.getValue() > 100 ? 100 : parameters.batchSize.getValue();
    String sOldest = parameters.oldestCreateDate.getValue();
    String sLatest = parameters.latestCreateDate.getValue();
    LOG.debug("LeadChanges - from {} to {}.", sOldest, sLatest);
    ///*from w  w  w .j  av a 2  s.c om*/
    // Create Request
    //
    ParamsGetLeadChanges request = new ParamsGetLeadChanges();
    LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
    try {
        Date oldest = MarketoUtils.parseDateString(sOldest);
        Date latest = MarketoUtils.parseDateString(sLatest);
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(latest);
        DatatypeFactory factory = newInstance();
        JAXBElement<XMLGregorianCalendar> until = objectFactory
                .createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));
        GregorianCalendar since = new GregorianCalendar();
        since.setTime(oldest);
        leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
        leadSelector.setLatestUpdatedAt(until);
        request.setLeadSelector(leadSelector);

        JAXBElement<XMLGregorianCalendar> oldestCreateAtValue = objectFactory
                .createStreamPositionOldestCreatedAt(factory.newXMLGregorianCalendar(since));

        StreamPosition sp = new StreamPosition();
        sp.setOldestCreatedAt(oldestCreateAtValue);
        if (offset != null && !offset.isEmpty()) {
            sp.setOffset(objectFactory.createStreamPositionOffset(offset));
        }
        request.setStartPosition(sp);

    } catch (ParseException | DatatypeConfigurationException e) {
        LOG.error("Error for LastUpdateAtSelector : {}.", e.getMessage());
        throw new ComponentException(e);
    }

    // attributes
    ArrayOfString attributes = new ArrayOfString();
    for (String s : mappings.values()) {
        attributes.getStringItems().add(s);
    }
    // Activity filter
    ActivityTypeFilter filter = new ActivityTypeFilter();

    if (parameters.setIncludeTypes.getValue()) {
        ArrayOfActivityType includes = new ArrayOfActivityType();
        for (String a : parameters.includeTypes.type.getValue()) {
            includes.getActivityTypes().add(fromValue(a));
        }
        filter.setIncludeTypes(includes);
    }
    if (parameters.setExcludeTypes.getValue()) {
        ArrayOfActivityType excludes = new ArrayOfActivityType();
        for (String a : parameters.excludeTypes.type.getValue()) {
            excludes.getActivityTypes().add(fromValue(a));
        }
        filter.setExcludeTypes(excludes);
    }

    JAXBElement<ActivityTypeFilter> typeFilter = objectFactory
            .createParamsGetLeadActivityActivityFilter(filter);
    request.setActivityFilter(typeFilter);
    // batch size
    JAXBElement<Integer> batchSize = objectFactory.createParamsGetMultipleLeadsBatchSize(bSize);
    request.setBatchSize(batchSize);
    //
    //
    // Request execution
    //
    SuccessGetLeadChanges result = null;

    MarketoRecordResult mkto = new MarketoRecordResult();
    try {
        result = getPort().getLeadChanges(request, header);
        mkto.setSuccess(true);
    } catch (Exception e) {
        LOG.error("getLeadChanges error: {}.", e.getMessage());
        mkto.setSuccess(false);
        mkto.setRecordCount(0);
        mkto.setRemainCount(0);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, e.getMessage())));
        return mkto;
    }

    if (result == null || result.getResult().getReturnCount() == 0) {
        LOG.debug(MESSAGE_REQUEST_RETURNED_0_MATCHING_LEADS);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, MESSAGE_NO_LEADS_FOUND)));
        return mkto;
    }

    String streamPos = result.getResult().getNewStartPosition().getOffset().getValue();
    int recordCount = result.getResult().getReturnCount();
    int remainCount = result.getResult().getRemainingCount();

    // Process results
    List<IndexedRecord> results = convertLeadChangeRecords(
            result.getResult().getLeadChangeRecordList().getValue().getLeadChangeRecords(), schema, mappings);

    mkto.setRecordCount(recordCount);
    mkto.setRemainCount(remainCount);
    mkto.setStreamPosition(streamPos);
    mkto.setRecords(results);

    return mkto;
}