Example usage for javax.xml.bind JAXBElement getValue

List of usage examples for javax.xml.bind JAXBElement getValue

Introduction

In this page you can find the example usage for javax.xml.bind JAXBElement getValue.

Prototype

public T getValue() 

Source Link

Document

Return the content model and attribute values for this element.

See #isNil() for a description of a property constraint when this value is null

Usage

From source file:com.catify.processengine.core.nodes.NodeFactoryImpl.java

/**
 * Extracts the information of the embedded start nodes that are in a given process (level)
 * and returns the actor references to that nodes. This info is needed by the sub process.
 *
 * @param clientId the client id/*from   w  w w. ja va 2  s.c om*/
 * @param processJaxb the processJaxb
 * @param subProcessesJaxb the sub processes jaxb
 * @param flowNodeJaxb the flow nodeJaxb
 * @param sequenceFlowsJaxb the sequence flowsJaxb
 * @return a list of strings of the other start node actor references
 */
protected List<ActorRef> getEmbeddedNodeActorReferences(String clientId, TProcess processJaxb,
        List<TSubProcess> subProcessesJaxb, TFlowNode flowNodeJaxb, List<TSequenceFlow> sequenceFlowsJaxb) {

    if (flowNodeJaxb instanceof TSubProcess) {
        TSubProcess subProcessJaxb = (TSubProcess) flowNodeJaxb;

        // the searched embedded flow nodes are embedded in teh given subprocess (so we need to add it to the list of (embedding) subprocesses)
        ArrayList<TSubProcess> embeddingSubProcessesJaxb = new ArrayList<TSubProcess>(subProcessesJaxb);
        embeddingSubProcessesJaxb.add(subProcessJaxb);

        // collect actorRef for each flow node in the subProcess
        List<ActorRef> embeddedFlowNodes = new ArrayList<ActorRef>();

        for (JAXBElement<? extends TFlowElement> flowElementJaxb : subProcessJaxb.getFlowElement()) {
            if (flowElementJaxb.getValue() instanceof TFlowNode) {
                TFlowNode embeddedFlowNodeJaxb = (TFlowNode) flowElementJaxb.getValue();
                embeddedFlowNodes.add(
                        new ActorReferenceService().getActorReference(IdService.getUniqueFlowNodeId(clientId,
                                processJaxb, embeddingSubProcessesJaxb, embeddedFlowNodeJaxb)));
            }
        }

        return embeddedFlowNodes;
    } else {
        return null;
    }
}

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This method will update the passed in vApp network by adding an additional
 * NetworkConfigSection that uses the command line options.networkName. It makes a PUT call
 * to the edit link of the NetworkConfigSection section of the vApp passed in. The
 * passed in VdcType is used to look up the parent network which is required for the update
 * process of the vApp NetworkConfigSection.
 * //from   w  w  w. ja  v  a  2s  . c o m
 * NOTE: This step, updating the vApp network section, must be done BEFORE any of the vApp's
 * children Vm's network sections are updated.
 * 
 * @param vApp the vApp instance to update network configuration for
 * @param vdc the VDC this vApp is deployed to
 * @return a TaskType instance if successful, otherwise an exception is thrown
 */
private TaskType updateVAppNetwork(VAppType vApp, VdcType vdc) {
    List<JAXBElement<? extends SectionType>> sections = vApp.getSection();
    for (JAXBElement<? extends SectionType> section : sections) {
        if (section.getName().toString().contains("NetworkConfigSection")) {
            NetworkConfigSectionType ncst = (NetworkConfigSectionType) section.getValue();
            // Find the EDIT link to make a PUT call to to update the network config info
            List<LinkType> links = ncst.getLink();
            String editHref = null;
            for (LinkType link : links) {
                if (link.getRel().equalsIgnoreCase("edit")) {
                    editHref = link.getHref();
                    break;
                }
            }

            if (null != editHref) {
                VAppNetworkConfigurationType vappNet = new VAppNetworkConfigurationType();

                // Use the network name passed on the command line, the same name that will
                // be applied to each vApp Vm child network configuration so they match
                vappNet.setNetworkName(options.networkName);

                // Newly constructed network configuration
                NetworkConfigurationType networkConfiguration = new NetworkConfigurationType();
                ReferenceType networkReference = new ReferenceType();

                // Get the parent network that the VDC refers to
                networkReference.setHref(getParentNetworkHrefFromVdc(vdc));
                networkConfiguration.setParentNetwork(networkReference);

                // hard coded.. 'bridged', 'natRouted' or 'isolated'
                networkConfiguration.setFenceMode("bridged");
                vappNet.setConfiguration(networkConfiguration);

                // Add the newly configured network to the existing vApp configuration
                ncst.getNetworkConfig().add(vappNet);

                // Make the PUT call to update the vApp network configuration
                HttpPut updateVAppNetwork = vcd.put(editHref, options);
                OutputStream os = null;
                ObjectFactory objectFactory = new ObjectFactory();
                JAXBElement<NetworkConfigSectionType> networkConfigSectionType = objectFactory
                        .createNetworkConfigSection(ncst);

                JAXBContext jaxbContexts = null;
                try {
                    jaxbContexts = JAXBContext.newInstance(NetworkConfigSectionType.class);
                } catch (JAXBException ex) {
                    throw new RuntimeException("Problem creating JAXB Context: ", ex);
                }

                try {
                    javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
                    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    os = new ByteArrayOutputStream();
                    // Marshal the object via JAXB to XML
                    marshaller.marshal(networkConfigSectionType, os);
                } catch (JAXBException e) {
                    throw new RuntimeException("Problem marshalling VirtualHardwareSection", e);
                }

                // Set the Content-Type header for NetworkConfigSection
                ContentType contentType = ContentType
                        .create("application/vnd.vmware.vcloud.networkConfigSection+xml", "ISO-8859-1");
                StringEntity update = new StringEntity(os.toString(), contentType);
                updateVAppNetwork.setEntity(update);

                // Invoke the HttoPut to update the VirtualHardwareSection of the Vm
                HttpResponse response = HttpUtils.httpInvoke(updateVAppNetwork);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                    TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class);
                    return taskType;
                }
            }
        }
    }

    throw new RuntimeException("Problem trying to update vApp " + vApp.getName()
            + " network config section with " + options.networkName + " as the network name");
}

From source file:com.catify.processengine.core.nodes.NodeFactoryImpl.java

/**
 * Extracts the information of the embedded start nodes that are in a given process (level)
 * and returns the actor references to that nodes. This info is needed by the sub process.
 *
 * @param clientId the client id// w  ww .j a v  a  2 s . c o  m
 * @param processJaxb the processJaxb
 * @param subProcessesJaxb the sub processes jaxb
 * @param flowNodeJaxb the flow nodeJaxb (which must be a TSubProcess)
 * @param sequenceFlowsJaxb the sequence flowsJaxb
 * @return a list of strings of the other start node actor references
 */
protected List<ActorRef> getEmbeddedStartNodeActorReferences(String clientId, TProcess processJaxb,
        List<TSubProcess> subProcessesJaxb, TFlowNode flowNodeJaxb, List<TSequenceFlow> sequenceFlowsJaxb) {

    List<ActorRef> embeddedStartNodes = new ArrayList<ActorRef>();

    // the current sub process is the parent process of the embedded nodes, 
    // so we need to add it to the list of parent sub processes in this methods scope
    ArrayList<TSubProcess> subProcesses = new ArrayList<TSubProcess>(subProcessesJaxb);
    subProcesses.add((TSubProcess) flowNodeJaxb);

    // extract StartEvents from SubProcess
    for (JAXBElement<? extends TFlowElement> flowElementJaxb : ((TSubProcess) flowNodeJaxb).getFlowElement()) {
        if (flowElementJaxb.getValue() instanceof TStartEvent) {
            TStartEvent startEventJaxb = (TStartEvent) flowElementJaxb.getValue();
            embeddedStartNodes.add(new ActorReferenceService().getActorReference(
                    IdService.getUniqueFlowNodeId(clientId, processJaxb, subProcesses, startEventJaxb)));
        }
    }

    return embeddedStartNodes;
}

From source file:com.emc.cto.ridagent.rid.RIDSender.java

@RequestMapping(method = RequestMethod.POST, value = "/listWatchList")
public ModelAndView viewWatchList(HttpServletRequest request, HttpServletResponse response, Model model,
        @ModelAttribute("params") SendQueryParams params, BindingResult result)
        throws XProcException, IOException, URISyntaxException, TransformerException, JAXBException {
    try {//from  w  w  w  . j  a  v  a2 s  .  c om

        if (logger.isDebugEnabled()) {
            logger.debug("In viewWatchList");
            logger.debug("Id = " + params.getId());
        }

        /* Get a report based on the id */
        PipelineInputCache pi = new PipelineInputCache();
        pi.addParameter("xqueryParameters", new QName("id"), params.getId());

        PipelineOutput output = m_getWatchList.executeOn(pi);
        IncidentData eventdata = new IncidentData();
        List<com.emc.documentum.xml.xproc.io.Source> sources = output.getSources(output.getPrimaryOutputPort());

        if (sources != null && !sources.isEmpty()) {
            // pipeline should only return a single value - we return the first as the output
            org.w3c.dom.Node node = sources.get(0).getNode();
            JAXBContext jc = JAXBContext.newInstance("com.emc.cto.ridagent.rid.jaxb");
            Unmarshaller u = jc.createUnmarshaller();
            JAXBElement element = (JAXBElement) u.unmarshal(node);
            RIDType d = (RIDType) element.getValue();
            RIDPolicyType policy = d.getRIDPolicy();
            if (policy.getReportSchema() != null) {
                ReportSchemaType rst = policy.getReportSchema();
                if (rst.getXMLDocument() != null) {
                    ExtensionType et = rst.getXMLDocument();
                    IODEFDocument document = (IODEFDocument) et.getContent().get(0);
                    Incident incident = document.getIncident().get(0);
                    if (incident.getDescription().size() != 0) {
                        MLStringType des = incident.getDescription().get(0);
                        eventdata.setDescription(des.getValue());
                    }
                    if (incident.getReportTime() != null)
                        eventdata.setReporttime(incident.getReportTime().toString());
                    if (incident.getStartTime() != null)
                        eventdata.setStarttime(incident.getStartTime().toString());
                    if (incident.getEndTime() != null)
                        eventdata.setStoptime(incident.getEndTime().toString());
                    if (incident.getDetectTime() != null)
                        eventdata.setDetecttime(incident.getDetectTime().toString());
                    for (int eventCount = 0; eventCount < incident.getEventData().size(); eventCount++) {
                        EventData one = incident.getEventData().get(eventCount);
                        Event nodeobj = new Event();
                        eventdata.getNode().add(nodeobj);
                        if (one.getMethod().size() != 0) {
                            Method methodobj = one.getMethod().get(0);
                            Reference ref = (Reference) methodobj.getReferenceOrDescription().get(0);
                            nodeobj.setRefName(ref.getReferenceName().getValue());
                            nodeobj.setRefURL(ref.getURL().get(0));

                        }
                        boolean domainPresent = false;
                        for (int flowindex = 0; flowindex < one.getFlow().size(); flowindex++) {
                            Flow flowobject = one.getFlow().get(flowindex);
                            if (flowobject.getSystem().size() > 0) {
                                com.emc.cto.ridagent.rid.jaxb.System sysobject = flowobject.getSystem().get(0);
                                com.emc.cto.ridagent.rid.jaxb.Node nodes = sysobject.getNode().get(0);
                                for (int addressindex = 0; addressindex < nodes
                                        .getNodeNameOrDomainDataOrAddress().size(); addressindex++) {
                                    Object obj = nodes.getNodeNameOrDomainDataOrAddress().get(addressindex);
                                    if (obj instanceof DomainData) {
                                        domainPresent = true;
                                        break;
                                    }
                                }

                            }

                            if (domainPresent) { //domaindata in flow element
                                Flow flowobj = one.getFlow().get(flowindex);
                                for (int systemindex = 0; systemindex < flowobj.getSystem()
                                        .size(); systemindex++) {
                                    com.emc.cto.ridagent.rid.jaxb.System sysobj = flowobj.getSystem()
                                            .get(systemindex);
                                    PhishingData ip = new PhishingData();
                                    nodeobj.getPhishing().add(ip);
                                    ip.setSystemcategory(sysobj.getCategory());
                                    com.emc.cto.ridagent.rid.jaxb.Node nodes = sysobj.getNode().get(0); //get the first node
                                    for (int addressindex = 0; addressindex < nodes
                                            .getNodeNameOrDomainDataOrAddress().size(); addressindex++) {
                                        Object obj = nodes.getNodeNameOrDomainDataOrAddress().get(addressindex);
                                        if (obj instanceof Address) {
                                            SystemData address = new SystemData();
                                            ip.getSystem().add(address);
                                            Address addressobj = (Address) obj;
                                            address.setType(addressobj.getCategory());
                                            address.setValue(addressobj.getValue());
                                        } else if (obj instanceof MLStringType) {
                                            SystemData address = new SystemData();
                                            ip.getSystem().add(address);
                                            MLStringType nodename = (MLStringType) obj;
                                            address.setType("Name");
                                            address.setValue(nodename.getValue());

                                        } else if (obj instanceof DomainData) {
                                            EmailInfo emailobj = new EmailInfo();
                                            ip.getEmailinfo().add(emailobj);
                                            DomainData domainobj = (DomainData) obj;
                                            emailobj.setDomain(domainobj.getName().getValue());
                                            emailobj.setDomaindate(
                                                    domainobj.getDateDomainWasChecked().toString());
                                            for (int dnsindex = 0; dnsindex < domainobj.getRelatedDNS()
                                                    .size(); dnsindex++) {
                                                RelatedDNSEntryType dnsobj = domainobj.getRelatedDNS()
                                                        .get(dnsindex);
                                                DNSRecord dnsrecordobj = new DNSRecord();
                                                emailobj.getDns().add(dnsrecordobj);
                                                dnsrecordobj.setType(dnsobj.getRecordType());
                                                dnsrecordobj.setValue(dnsobj.getValue());

                                            }
                                        }

                                    }
                                    for (int serviceindex = 0; serviceindex < sysobj.getService()
                                            .size(); serviceindex++) {
                                        Service serviceobj = sysobj.getService().get(serviceindex);
                                        if (serviceobj.getEmailInfo() != null) {
                                            EmailInfo emailinfoobj = ip.getEmailinfo().get(serviceindex);
                                            emailinfoobj.setEmailid(
                                                    serviceobj.getEmailInfo().getEmail().getValue());
                                            emailinfoobj.setSubject(
                                                    serviceobj.getEmailInfo().getEmailSubject().getValue());
                                            emailinfoobj.setMailerid(
                                                    serviceobj.getEmailInfo().getXMailer().getValue());

                                        } else {
                                            SystemData address = ip.getSystem().get(serviceindex);
                                            address.setProtocolno(address.getProtocolno());
                                            address.setPortno(address.getPortno());
                                            if (serviceobj.getApplication() != null) {
                                                SoftwareType useragent = serviceobj.getApplication();
                                                address.setUseragent(useragent.getUserAgent());
                                            }
                                        }

                                    }
                                    NodeRole noderole = nodes.getNodeRole().get(0); //get the only node role
                                    ip.setCategory(noderole.getCategory());
                                    if (noderole.getAttacktype() != null)
                                        ip.setRole(noderole.getAttacktype().name());

                                }

                            } else {
                                Flow flowobj = one.getFlow().get(flowindex);
                                for (int systemindex = 0; systemindex < flowobj.getSystem()
                                        .size(); systemindex++) {
                                    com.emc.cto.ridagent.rid.jaxb.System sysobj = flowobj.getSystem()
                                            .get(systemindex);
                                    NetworkInfo ip = new NetworkInfo();
                                    nodeobj.getAddress().add(ip);
                                    ip.setSystemcategory(sysobj.getCategory());
                                    for (int nodeindex = 0; nodeindex < sysobj.getNode().size(); nodeindex++) {
                                        com.emc.cto.ridagent.rid.jaxb.Node nodes = sysobj.getNode()
                                                .get(nodeindex);
                                        if (nodes.getNodeRole().size() != 0) {
                                            NodeRole noderole = nodes.getNodeRole().get(0); //get the only node role
                                            ip.setCategory(noderole.getCategory());
                                            if (noderole.getAttacktype() != null)
                                                ip.setRole(noderole.getAttacktype().name());
                                        }
                                        for (int addressindex = 0; addressindex < nodes
                                                .getNodeNameOrDomainDataOrAddress().size(); addressindex++) {
                                            SystemData address = new SystemData();
                                            ip.getSystem().add(address);
                                            Object obj = nodes.getNodeNameOrDomainDataOrAddress()
                                                    .get(addressindex);
                                            if (obj instanceof Address) {
                                                Address addressobj = (Address) obj;
                                                address.setType(addressobj.getCategory());
                                                address.setValue(addressobj.getValue());
                                            } else if (obj instanceof MLStringType) {
                                                MLStringType nodename = (MLStringType) obj;
                                                address.setType("Name");
                                                address.setValue(nodename.getValue());

                                            }

                                        }
                                    }
                                    for (int serviceindex = 0; serviceindex < sysobj.getService()
                                            .size(); serviceindex++) {
                                        Service serviceobj = sysobj.getService().get(serviceindex);
                                        SystemData address = ip.getSystem().get(serviceindex);
                                        address.setProtocolno(serviceobj.getIpProtocol());
                                        address.setPortno(serviceobj.getPort());
                                        if (serviceobj.getApplication() != null) {
                                            SoftwareType useragent = serviceobj.getApplication();
                                            address.setUseragent(useragent.getUserAgent());
                                        }

                                    }

                                }
                            }

                        }
                        Record recordobj = one.getRecord();
                        if (recordobj != null) {
                            for (int recorddataindex = 0; recorddataindex < recordobj.getRecordData()
                                    .size(); recorddataindex++) {
                                RecordData recorddataobj = recordobj.getRecordData().get(recorddataindex);
                                for (int hashindex = 0; hashindex < recorddataobj.getHashInformation()
                                        .size(); hashindex++) {
                                    HashSigDetails hashobj = recorddataobj.getHashInformation().get(hashindex);
                                    if (hashobj.getSignature().size() != 0) {
                                        DigitalSig signatureobj = new DigitalSig();
                                        nodeobj.getDsig().add(signatureobj);
                                        signatureobj.setType(hashobj.getType());
                                        signatureobj.setValidity(hashobj.isValid().toString());
                                        SignatureType signature = hashobj.getSignature().get(0); //get the signature
                                        SignedInfoType signedinfo = signature.getSignedInfo();
                                        signatureobj.setCan_method(
                                                signedinfo.getCanonicalizationMethod().getAlgorithm());
                                        signatureobj.setSignature_method(
                                                signedinfo.getSignatureMethod().getAlgorithm());
                                        ReferenceType reference = signedinfo.getReference().get(0);
                                        signatureobj.setHash_type(reference.getDigestMethod().getAlgorithm());
                                        signatureobj.setHash_value(reference.getDigestValue());
                                        signatureobj
                                                .setSignature_value(signature.getSignatureValue().getValue());

                                    } else {
                                        Hash hash = new Hash();
                                        nodeobj.getHash().add(hash);
                                        hash.setType(hashobj.getType());
                                        for (int fileindex = 0; fileindex < hashobj.getFileName()
                                                .size(); fileindex++) {
                                            MLStringType fileinfo = hashobj.getFileName().get(fileindex);
                                            FileData filedataobj = new FileData();
                                            hash.getFile().add(filedataobj);
                                            filedataobj.setFilename(fileinfo.getValue());
                                        }

                                        for (int anotherhashindex = 0; anotherhashindex < hashobj.getReference()
                                                .size(); anotherhashindex++) {
                                            ReferenceType referenceobj = hashobj.getReference()
                                                    .get(anotherhashindex);
                                            HashData hashvalueobj = new HashData();
                                            hash.getValue().add(hashvalueobj);
                                            DigestMethodType digestobj = referenceobj.getDigestMethod();
                                            hashvalueobj.setHash_type(digestobj.getAlgorithm());
                                            hashvalueobj.setValue(referenceobj.getDigestValue());
                                        }
                                    }

                                }
                                for (int registryindex = 0; registryindex < recorddataobj
                                        .getWindowsRegistryKeysModified().size(); registryindex++) {
                                    RegistryKeyModified rkmobj = recorddataobj.getWindowsRegistryKeysModified()
                                            .get(registryindex);
                                    for (int keyindex = 0; keyindex < rkmobj.getKey().size(); keyindex++) {
                                        Key key = rkmobj.getKey().get(keyindex);
                                        RegistryValues registryvaluesobj = new RegistryValues();
                                        nodeobj.getRegistry().add(registryvaluesobj);
                                        registryvaluesobj.setAction(key.getRegistryaction());
                                        registryvaluesobj.setKey(key.getKeyName());
                                        registryvaluesobj.setValue(key.getValue());

                                    }

                                }

                            }

                        }
                    }
                }
            }

        }

        return new ModelAndView("viewWebReport", "eventdata", eventdata);

    } finally {
        ; //TODO add finally handler
    }
}

From source file:com.evolveum.midpoint.testing.model.client.sample.TestExchangeConnector.java

private static <T> T unmarshallResource(String path) throws JAXBException, FileNotFoundException {
    JAXBContext jc = ModelClientUtil.instantiateJaxbContext();
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    InputStream is = null;/*from  www  .  j  a  va2s  . c  o m*/
    JAXBElement<T> element = null;
    try {
        is = TestExchangeConnector.class.getClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException("System resource " + path + " was not found");
        }
        element = (JAXBElement<T>) unmarshaller.unmarshal(is);
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
    if (element == null) {
        return null;
    }
    return element.getValue();
}

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This will use the passed in vm  to find the VirtualHardwareSection and modify it to attach
 * the Vm network to the vApp network the Vm is a child of. The first step is to search the
 * Vm section types for VirtualHardwareSection. If found, look in the attributes of the section
 * to find the VirtualHardwareSection Href value. The VirtualHardwareSection found in the Vm
 * has a number of extra LinkType links that can not be part of the request body when the PUT
 * call to update the network settings is made. Therefore, the Href is used to first GET the
 * VirtualHardwareSection again which responds without the links so it can be used to PUT back
 * to the same Href to update the Vm network settings. With the newly acquired 
 * VirtualHardwareSection, a search through the items is done to find the network item. This
 * is denoted by a resource type value of "10". If found the command line options.networkName
 * is set as the value of the connection, and the value POOL is assigned to the ipAddressingMode
 * attribute. With those values set, the updated VirtualHardwareSection is then sent via a PUT
 * request to change the Vm network settings.
 * /*from  w w w.j a va  2 s  .  co  m*/
 * @param vm the Vm to change network settings on
 */
private TaskType updateVMWithNetworkDetails(VmType vm) {
    // the Href to use for GET and PUT calls for the VirtualHardwareSection
    String hardwareHref = null;
    // With the VDC network details, we can now update the Vm network section to connect the Vm to the vApp network
    for (JAXBElement<? extends SectionType> st : vm.getSection()) {
        if (st.getName().toString().contains("VirtualHardwareSection")) {
            VirtualHardwareSectionType hardware = (VirtualHardwareSectionType) st.getValue();

            // Try to find the Href attribute which is used for GET and PUT
            Map<QName, String> map = hardware.getOtherAttributes();
            Set<QName> keys = map.keySet();
            for (QName key : keys) {
                if (key.toString().endsWith("href")) {
                    hardwareHref = map.get(key);
                    break;
                }
            }

            // Make sure VirtualHardwareSection href was found. This is used for the GET below
            // and PUT to later update the network settings of the Vm.
            if (null != hardwareHref) {
                // It's necessary to GET the VirtualHardwareSection again because the current
                // hardware variables from the Vm contains links that can not be sent as part
                // of the PUT body. This GET call will only get the details without the links
                // that the Vm section provides.
                HttpResponse response = HttpUtils.httpInvoke(vcd.get(hardwareHref, options));
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    hardware = HttpUtils.unmarshal(response.getEntity(), VirtualHardwareSectionType.class);

                    // Find the RASDType that has a ResourceType of 10, which indicates the
                    // VMs network info
                    for (RASDType rasType : hardware.getItem()) {
                        if (rasType.getResourceType().getValue().equals("10")) {
                            CimBoolean c = new CimBoolean();
                            c.setValue(true);

                            rasType.setAutomaticAllocation(c);
                            // Get the first CimString
                            CimString cs = rasType.getConnection().get(0);

                            // Set the network name
                            cs.setValue(options.networkName);

                            // Look in the list of attributes for the ip addressing mode
                            map = cs.getOtherAttributes();
                            keys = map.keySet();
                            for (QName key : keys) {
                                if (key.toString().endsWith("ipAddressingMode")) {
                                    // Set it to POOL
                                    map.put(key, "POOL");
                                    break;
                                }
                            }

                            break;
                        }
                    }
                }

                // Now do a PUT with update data
                com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory objectFactory = new com.vmware.vcloud.api.rest.schema.ovf.ObjectFactory();
                JAXBElement<VirtualHardwareSectionType> hardwareSection = objectFactory
                        .createVirtualHardwareSection(hardware);

                JAXBContext jaxbContexts = null;
                try {
                    jaxbContexts = JAXBContext.newInstance(VirtualHardwareSectionType.class);
                } catch (JAXBException ex) {
                    throw new RuntimeException("Problem creating JAXB Context: ", ex);
                }

                // Create HttpPut request to update the VirtualHardwareSection
                HttpPut updateVmNetwork = vcd.put(hardwareHref, options);
                OutputStream os = null;

                try {
                    javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
                    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    os = new ByteArrayOutputStream();
                    // Marshal the object via JAXB to XML
                    marshaller.marshal(hardwareSection, os);
                } catch (JAXBException e) {
                    throw new RuntimeException("Problem marshalling VirtualHardwareSection", e);
                }

                // Set the Content-Type header for VirtualHardwareSection
                ContentType contentType = ContentType
                        .create("application/vnd.vmware.vcloud.virtualHardwareSection+xml", "ISO-8859-1");
                StringEntity update = new StringEntity(os.toString(), contentType);
                updateVmNetwork.setEntity(update);

                // Invoke the HttoPut to update the VirtualHardwareSection of the Vm
                response = HttpUtils.httpInvoke(updateVmNetwork);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                    // Update was good, return the TaskType
                    TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class);
                    return taskType;
                }

                break;
            }
        }
    }

    throw new RuntimeException("Could not update Vm VirtualHardwareSection");
}

From source file:be.fedict.eid.dss.client.DigitalSignatureServiceClient.java

@SuppressWarnings("unchecked")
private StorageInfo findStorageInfo(SignResponse signeResponse) {

    AnyType optionalOutputs = signeResponse.getOptionalOutputs();
    if (null == optionalOutputs) {
        return null;
    }/*from   www.j a  va  2s.  c  o m*/
    List<Object> optionalOutputContent = optionalOutputs.getAny();
    for (Object optionalOutput : optionalOutputContent) {

        if (optionalOutput instanceof Element) {

            Element optionalOutputElement = (Element) optionalOutput;
            if (DSSConstants.ARTIFACT_NAMESPACE.equals(optionalOutputElement.getNamespaceURI())
                    && "StorageInfo".equals(optionalOutputElement.getLocalName())) {
                JAXBElement<StorageInfo> storageInfoElement;
                try {
                    storageInfoElement = (JAXBElement<StorageInfo>) this.artifactUnmarshaller
                            .unmarshal(optionalOutputElement);
                } catch (JAXBException e) {
                    throw new RuntimeException("JAXB error parsing storage info: " + e.getMessage(), e);
                }
                return storageInfoElement.getValue();
            }
        }
    }

    return null;
}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.ResourceManager.java

/**
 * Read the resources from the XML descriptor
 * @return//from ww  w . jav a2  s . c om
 */
private List<Service> loadResourceTemplates() {
    try {
        JAXBContext jaxb = JAXBContext.newInstance(ServiceDescriptor.class, Services.class,
                ResourceMapping.class, ResourceDeclaration.class);
        Unmarshaller unm = jaxb.createUnmarshaller();
        JAXBElement<Services> element = (JAXBElement<Services>) unm.unmarshal(
                new StreamSource(getClass().getResourceAsStream("resourceTemplates.xml")), Services.class);
        return element.getValue().getService();
    } catch (JAXBException e) {
        logger.error("Failed to load resource templates: " + e.getMessage(), e);
        return Collections.emptyList();
    }
}

From source file:de.ingrid.interfaces.csw.domain.filter.impl.LuceneFilterParser.java

/**
 * Build a piece of Lucene query with the specified Logical filter.
 *
 * @param logicOpsEl//from w  w  w.  j a  v a2  s .c o m
 * @return SpatialQuery
 * @throws CSWFilterException
 */
private SpatialQuery processLogicalOperator(JAXBElement<? extends LogicOpsType> logicOpsEl)
        throws CSWFilterException {
    List<SpatialQuery> subQueries = new ArrayList<SpatialQuery>();
    StringBuilder queryBuilder = new StringBuilder();
    List<Filter> filters = new ArrayList<Filter>();

    String operator = logicOpsEl.getName().getLocalPart();
    LogicOpsType logicOps = logicOpsEl.getValue();
    if (logicOps instanceof BinaryLogicOpType) {
        BinaryLogicOpType binary = (BinaryLogicOpType) logicOps;
        queryBuilder.append('(');

        // process comparison operators: PropertyIsLike, IsNull, IsBetween,
        // ...
        for (JAXBElement<? extends ComparisonOpsType> el : binary.getComparisonOps()) {
            queryBuilder.append(this.processComparisonOperator(el));
            queryBuilder.append(" ").append(operator.toUpperCase()).append(" ");
        }

        // process logical operators like AND, OR, ...
        for (JAXBElement<? extends LogicOpsType> el : binary.getLogicOps()) {
            boolean writeOperator = true;

            SpatialQuery sq = this.processLogicalOperator(el);
            String subQuery = sq.getQuery();
            Filter subFilter = sq.getSpatialFilter();

            // if the sub spatial query contains both term search and
            // spatial search we create a subQuery
            if ((subFilter != null && !subQuery.equals(defaultField)) || sq.getSubQueries().size() != 0
                    || (sq.getLogicalOperator() == SerialChainFilter.NOT && sq.getSpatialFilter() == null)) {
                subQueries.add(sq);
                writeOperator = false;
            } else {
                if (subQuery.equals("")) {
                    writeOperator = false;
                } else {
                    queryBuilder.append(subQuery);
                }
                if (subFilter != null) {
                    filters.add(subFilter);
                }
            }

            if (writeOperator) {
                queryBuilder.append(" ").append(operator.toUpperCase()).append(" ");
            } else {
                writeOperator = true;
            }
        }

        // process spatial constraint : BBOX, Beyond, Overlaps, ...
        for (JAXBElement<? extends SpatialOpsType> el : binary.getSpatialOps()) {
            // for the spatial filter we don't need to write into the Lucene
            // query
            filters.add(this.processSpatialOperator(el));
        }

        // remove the last Operator and add a ') '
        int pos = queryBuilder.length() - (operator.length() + 2);
        if (pos > 0) {
            queryBuilder.delete(queryBuilder.length() - (operator.length() + 2), queryBuilder.length());
        }
        queryBuilder.append(')');
    } else if (logicOps instanceof UnaryLogicOpType) {
        UnaryLogicOpType unary = (UnaryLogicOpType) logicOps;

        // process comparison operator: PropertyIsLike, IsNull, IsBetween,
        // ...
        if (unary.getComparisonOps() != null) {
            queryBuilder.append(this.processComparisonOperator(unary.getComparisonOps()));
        }
        // process spatial constraint : BBOX, Beyond, Overlaps, ...
        else if (unary.getSpatialOps() != null) {
            filters.add(this.processSpatialOperator(unary.getSpatialOps()));
        }
        // process logical Operators like AND, OR, ...
        else if (unary.getLogicOps() != null) {
            SpatialQuery sq = this.processLogicalOperator(unary.getLogicOps());
            String subQuery = sq.getQuery();
            Filter subFilter = sq.getSpatialFilter();

            if ((sq.getLogicalOperator() == SerialChainFilter.OR && subFilter != null
                    && !subQuery.equals(defaultField)) || (sq.getLogicalOperator() == SerialChainFilter.NOT)) {
                subQueries.add(sq);
            } else {
                if (!subQuery.equals("")) {
                    queryBuilder.append(subQuery);
                }
                if (subFilter != null) {
                    filters.add(sq.getSpatialFilter());
                }
            }
        }
    }

    String query = queryBuilder.toString();
    if (query.equals("()")) {
        query = "";
    }

    int logicalOperand = SerialChainFilter.valueOf(operator);
    Filter spatialFilter = this.getSpatialFilterFromList(logicalOperand, filters, query);
    SpatialQuery response = new SpatialQuery(query, spatialFilter, logicalOperand);
    response.setSubQueries(subQueries);
    return response;
}

From source file:edu.harvard.i2b2.eclipse.plugins.admin.utilities.views.PatientCountView.java

public String getNoteFromPDO(String xmlstr) {
    String note = null;/*from  w  w  w .j a v  a 2 s  . com*/
    try {
        JAXBUtil jaxbUtil = PFTJAXBUtil.getJAXBUtil();
        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlstr);
        DndType dndType = (DndType) jaxbElement.getValue();

        if (dndType == null)
            log.info("dndType is null");

        patientDataType = (PatientDataType) new JAXBUnWrapHelper().getObjectByClass(dndType.getAny(),
                PatientDataType.class);

        if (patientDataType == null)
            log.info("patientDataType is null");

        note = (String) patientDataType.getObservationSet().get(0).getObservation().get(0).getObservationBlob()
                .getContent().get(0);
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("Error marshalling Explorer drag text");
    }
    return note;

}