Example usage for javax.xml.namespace QName QName

List of usage examples for javax.xml.namespace QName QName

Introduction

In this page you can find the example usage for javax.xml.namespace QName QName.

Prototype

public QName(String localPart) 

Source Link

Document

QName constructor specifying the local part.

If the local part is null an IllegalArgumentException is thrown.

Usage

From source file:com.abiquo.am.services.ovfformat.TemplateFromOVFEnvelope.java

/**
 * TODO re-DOC <br>/*from   w ww . ja  v a  2  s.  co  m*/
 * REQUIRE THE OVFID IS PLACED ON A REMOTE LOCATION (WARINING on generation)<BR>
 * Creates a list of VirtualInfo relative to the VirtualDisk (from the disk section) and
 * requirements (from the VirtualHardwareSection) contained on the provided OVF envelope. Used
 * to add VirtualImage on database once an OVFPackage completes its download. No duplicated Disk
 * are returned.
 * 
 * @param ovfDescription, the OVF description of the required OVF package.
 * @return an array containing all the DiskInfo properties and requirements.
 * @throws RepositoryException, if the envelope do not contain the required info to get
 *             VirtualDisk information.
 **/
public static TemplateDto createTemplateDto(final String ovfId, final EnvelopeType envelope)
        // TODO String userID, String category
        throws AMException {

    TemplateDto diskInfo = null;

    Map<String, VirtualDiskDescType> diskIdToDiskFormat = new HashMap<String, VirtualDiskDescType>();
    Map<String, FileType> fileIdToFileType = new HashMap<String, FileType>();
    Map<String, List<String>> diskIdToVSs = new HashMap<String, List<String>>();
    Map<String, TemplateDto> requiredByVSs = new HashMap<String, TemplateDto>();
    DiskSectionType diskSectionType;

    try {
        ContentType contentType = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);

        ProductSectionType product = OVFEnvelopeUtils.getSection(contentType, ProductSectionType.class);

        String description = null;
        if (product.getInfo() != null && product.getInfo().getValue() != null) {
            description = product.getInfo().getValue();
        }

        String categoryName = null;
        if (product.getOtherAttributes().containsKey(new QName("CategoryName"))) {
            categoryName = product.getOtherAttributes().get(new QName("CategoryName"));
        }

        String iconPath = getIconPath(product, fileIdToFileType, ovfId);

        diskSectionType = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);

        for (FileType fileType : envelope.getReferences().getFile()) {
            fileIdToFileType.put(fileType.getId(), fileType);
        }
        // Create a hash
        for (VirtualDiskDescType virtualDiskDescType : diskSectionType.getDisk()) {
            diskIdToDiskFormat.put(virtualDiskDescType.getDiskId(), virtualDiskDescType);
        }

        if (contentType instanceof VirtualSystemType) {

            VirtualSystemType vs = (VirtualSystemType) contentType;
            TemplateDto req = getDiskInfo(vs, diskIdToDiskFormat, diskIdToVSs);

            requiredByVSs.put(vs.getId(), req);
        } else if (contentType instanceof VirtualSystemCollectionType) {
            List<VirtualSystemType> virtualSystems = OVFEnvelopeUtils
                    .getVirtualSystems((VirtualSystemCollectionType) contentType);

            for (VirtualSystemType virtualSystemType : virtualSystems) {
                TemplateDto req = getDiskInfo(virtualSystemType, diskIdToDiskFormat, diskIdToVSs);

                requiredByVSs.put(virtualSystemType.getId(), req);
            }
        }

        for (VirtualDiskDescType diskDescType : diskIdToDiskFormat.values()) {

            String diskId = diskDescType.getDiskId();
            String fileId = diskDescType.getFileRef();

            if (!fileIdToFileType.containsKey(fileId)) {
                String msg = "File Id [" + fileId + "] not found on the ReferencesSection";
                throw new IdNotFoundException(msg);
            }

            FileType file = fileIdToFileType.get(fileId);
            final String filePath = file.getHref();
            final Long fileSize = file.getSize().longValue();

            String format = diskDescType.getFormat(); // XXX using the same format on the OVF
            // disk

            if (!diskIdToVSs.containsKey(diskId)) {
                throw new IdNotFoundException("Any virtualSystem is using diskId[" + diskId + "]"); // XXX warning ??
            }

            if (diskIdToVSs.size() != 1) {
                throw new AMException(AMError.TEMPLATE_INVALID, String
                        .format("There are more than one virtual system on the OVF Envelope [%s]", ovfId));
            }

            for (String vssName : diskIdToVSs.get(diskId)) {
                diskInfo = new TemplateDto();
                diskInfo.setName(vssName);
                diskInfo.setUrl(ovfId);

                DiskFormat diskFormat = DiskFormat.fromValue(format);
                DiskFormatType ovfDiskFormat = DiskFormatType.valueOf(diskFormat.name());

                diskInfo.setDiskFileFormat(ovfDiskFormat);
                diskInfo.setDiskFileSize(fileSize);

                // Note that getHRef() will now return the relative path
                // of the file at the downloaded repository space

                if (filePath.startsWith("http:")) {
                    diskInfo.setDiskFilePath(FilenameUtils.getName(filePath));
                } else {
                    diskInfo.setDiskFilePath(filePath);
                }

                diskInfo.setIconPath(iconPath);
                diskInfo.setDescription(description);
                diskInfo.setCategoryName(categoryName);
                // XXX diskInfo.setSO(value);

                if (!requiredByVSs.containsKey(vssName)) {
                    throw new IdNotFoundException("VirtualSystem id not found [" + vssName + "]");
                }

                TemplateDto requirement = requiredByVSs.get(vssName);

                // XXX disk format ::: diskInfo.setImageType(requirement.getImageType());

                diskInfo.setCpu(requirement.getCpu());
                diskInfo.setRam(requirement.getRam());
                diskInfo.setHd(requirement.getHd());

                diskInfo.setRamSizeUnit(requirement.getRamSizeUnit());
                diskInfo.setHdSizeUnit(requirement.getHdSizeUnit());

                diskInfo.setEthernetDriverType(requirement.getEthernetDriverType());

                // TODO diskInfo.setEnterpriseId(enterpriseId);
                // diskInfo.setUserId(userId); TODO user ID
                // diskInfo.getCategories().add(category); TODO category

            } // all vss
        } // all disks
    } catch (EmptyEnvelopeException e) {
        String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
        throw new AMException(AMError.TEMPLATE_INVALID, msg, e);
    } catch (Exception e) {
        throw new AMException(AMError.TEMPLATE_INVALID, e);
    }

    if (diskInfo == null) {
        String msg = "No VirtualSystem or VirtualSystemCollection exists for this OVF package";
        throw new AMException(AMError.TEMPLATE_INVALID, msg);
    }

    return diskInfo;
}

From source file:com.googlecode.ddom.frontend.saaj.SOAPElementTest.java

@Validated
@Test//from   w w  w. java 2s . c  o m
public void testAddAttributeFromQNameWithoutNamespace() throws Exception {
    SOAPElement element = saajUtil.createSOAPElement(null, "test", null);
    SOAPElement retValue = element.addAttribute(new QName("attr"), "value");
    assertSame(element, retValue);
    Attr attr = element.getAttributeNodeNS(null, "attr");
    assertNull(attr.getNamespaceURI());
    String localName = attr.getLocalName();
    // The RI creates a namespace unaware attribute node in this case; we believe
    // it's better to create a namespace aware node.
    if (localName != null) {
        assertEquals("attr", attr.getLocalName());
    }
    assertNull(attr.getPrefix());
    assertEquals("value", attr.getValue());
}

From source file:com.vangent.hieos.services.xds.bridge.activity.AbstractGetDocumentsSQActivity.java

/**
 * Method description//  w  w w  .j av  a  2s  . com
 *
 *
 * @param registryResponse
 * @param context
 *
 * @return
 */
protected List<String> parseObjectRefs(GetDocumentsSQResponseMessage registryResponse,
        SDRActivityContext context) throws XdsException {

    List<String> result = new ArrayList<String>();

    SubmitDocumentResponse sdrResponse = context.getSubmitDocumentResponse();
    Document document = context.getDocument();
    OMElement rootNode = registryResponse.getElement();

    RegistryResponseParser parser = new RegistryResponseParser(rootNode);

    // The registry may return success even though there was
    // a token or policy issue/problem so we can not rely on "Success"
    List<RegistryError> registryErrors = parser.parseErrors();

    if (parser.is_error() || registryErrors.isEmpty() == false) {

        // If there are any errors or warnings then
        // propagate back to caller
        StringBuilder errmsg = new StringBuilder();
        errmsg.append("The XDS.b Registry returned the following errors/warnings: \n");
        for (RegistryError error : registryErrors) {

            String msg = String.format("%s: %s%n", error.getCode(), error.getContext());

            errmsg.append(msg);
        }

        throw new XdsException(errmsg.toString());

    } else {

        try {

            // search for any nodes
            String expr = "./ns:RegistryObjectList/ns:ObjectRef";
            List<OMElement> docs = XPathHelper.selectNodes(rootNode, expr, URIConstants.RIM_URI);

            if (docs != null) {

                QName idQName = new QName("id");

                for (OMElement doc : docs) {

                    result.add(doc.getAttributeValue(idQName));
                }
            }

        } catch (XdsInternalException e) {

            // log it
            logger.error(e, e);

            // capture in response
            StringBuilder sb = new StringBuilder();

            sb.append("Unable to parse repository response, exception follows. ");
            sb.append(e.getMessage());

            sdrResponse.addResponse(document, ResponseTypeStatus.Failure, sb.toString());
        }
    }

    return result;
}

From source file:org.apache.servicemix.jms.JmsConsumerEndpointTest.java

public void testConsumerSimpleJmsTx() throws Exception {
    JmsComponent component = new JmsComponent();
    JmsConsumerEndpoint endpoint = new JmsConsumerEndpoint();
    endpoint.setService(new QName("jms"));
    endpoint.setEndpoint("endpoint");
    endpoint.setTargetService(new QName("receiver"));
    endpoint.setListenerType("simple");
    endpoint.setConnectionFactory(connectionFactory);
    endpoint.setDestinationName("destination");
    endpoint.setTransacted("jms");
    component.setEndpoints(new JmsConsumerEndpoint[] { endpoint });
    container.activateComponent(component, "servicemix-jms");

    container.start();/*from   www  .j a  v  a  2  s.c  o  m*/

    jmsTemplate.convertAndSend("destination", "<hello>world</hello>");
    receiver.getMessageList().assertMessagesReceived(1);
}

From source file:com.vangent.hieos.services.xds.bridge.support.XDSBridgeConfigXmlParser.java

/**
 * Method description//from w w w .  j av  a  2 s. co  m
 *
 *
 *
 * @return
 *
 *
 * @throws XPathHelperException
 */
private Map<String, ContentParserConfig> parseContentConfigs() throws XPathHelperException {

    Map<String, ContentParserConfig> result = new HashMap<String, ContentParserConfig>();
    QName nameQName = new QName("name");
    QName baseQName = new QName("base");
    Iterator<OMElement> iterator = this.configElem.getChildrenWithName(new QName("ContentParserConfig"));

    while (iterator.hasNext()) {
        OMElement parserConfigElem = iterator.next();

        // pull name
        String name = parserConfigElem.getAttributeValue(nameQName);
        //String name = null;

        /*
        try {
        name = ContentParserConfigName.valueOf(nameAttribute);
        logger.info(String.format("Loaded config [%s].",
                                  nameAttribute));
        } catch (IllegalArgumentException e) {
        // ignore, probably a base config
        }*/

        if (name != null) {
            logger.info(String.format("Loading config [%s].", name));
            ContentParserConfig parserConfig = parseContentConfig(name, parserConfigElem);

            // pull base value
            String baseAttribute = parserConfigElem.getAttributeValue(baseQName);
            if (StringUtils.isNotBlank(baseAttribute)) {
                String expr = String.format("//ContentParserConfig[@name='%s']", baseAttribute);
                OMElement baseElem = XPathHelper.selectSingleNode(this.configElem, expr, "");
                if (baseElem != null) {
                    logger.info(String.format("Loading base config [%s].", baseAttribute));
                    ContentParserConfig baseConfig = parseContentConfig(name, baseElem);

                    // need to merge
                    // Note (BHT): Strange how this was implemented.
                    // Copies parserConfig into baseConfig and then points parserConfig
                    // into baseConfig.  Someone trying to be "cute".
                    // Besides the fact that baseConfig has to be parsed more than
                    // once (upon multiple passes).
                    logger.info(String.format("Merged configs [%s] and [%s] to support [%s] config.",
                            baseAttribute, name, name));
                    baseConfig.merge(parserConfig);
                    parserConfig = baseConfig;
                } else {
                    logger.warn(String.format("Base %s is not found.", baseAttribute));
                }
            }
            logger.info(String.format("Cached config [%s].", name));
            result.put(name, parserConfig);
        }
    }
    return result;
}

From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java

private Map.Entry<String, Boolean> getTargetInfo(final StartElement element, final String linkName)
        throws Exception {
    final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML);
    XMLEventReader reader = XMLUtilities.getEventReader(metadata);

    final String associationName = element.getAttributeByName(new QName("Relationship")).getValue();

    final Map.Entry<Integer, XmlElement> association = XMLUtilities.getAtomElement(reader, null, "Association",
            Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Name",
                    associationName.substring(associationName.lastIndexOf(".") + 1))),
            0, 4, 4, false);// ww  w.  ja  v a2  s .  co m

    final InputStream associationContent = association.getValue().toStream();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(associationContent, bos);
    IOUtils.closeQuietly(associationContent);

    reader.close();
    reader = XMLUtilities.getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    final Map.Entry<Integer, XmlElement> associationEnd = XMLUtilities.getAtomElement(reader, null, "End",
            Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Role", linkName)),
            0, -1, -1, false);

    final String target = associationEnd.getValue().getStart().getAttributeByName(new QName("Type")).getValue();
    final boolean feed = associationEnd.getValue().getStart().getAttributeByName(new QName("Multiplicity"))
            .getValue().equals("*");

    return new SimpleEntry<String, Boolean>(target, feed);
}

From source file:edu.monash.merc.system.parser.xml.HPAWSXmlParser.java

public List<HPAEntryBean> parseHPAXml(String fileName, XMLInputFactory2 factory2) {
    xmlif2 = factory2;/*  w w w .j  av  a 2 s  .  c o m*/
    logger.info("Starting to parse " + fileName);
    List<HPAEntryBean> hpaEntryBeans = new ArrayList<HPAEntryBean>();
    XMLEventReader2 xmlEventReader = null;
    try {
        xmlEventReader = (XMLEventReader2) xmlif2.createXMLEventReader(new FileInputStream(fileName));

        QName entryQN = new QName(ELE_ENTRY);
        QName versionQN = new QName(ATTR_VERSION);
        QName urlQN = new QName(ATTR_URL);
        QName nameQN = new QName(ELE_NAME);
        QName identiferQN = new QName(ELE_IDENTIFIER);
        QName idQN = new QName(ATTR_ID);
        QName xrefQN = new QName(ELE_XREF);
        QName dbQN = new QName(ATTR_DB);
        QName tissueExpQN = new QName(ELE_TISSUE_EXPRESSION);
        QName typeQN = new QName(ATTR_TYPE);
        QName verificationQN = new QName(ELE_VERIFICATION);
        QName dataQN = new QName(ELE_DATA);
        QName tissueQN = new QName(ELE_TISSUE);
        QName statusQN = new QName(ATTR_STATUS);
        QName cellTypeQN = new QName(ELE_CELLTYPE);
        QName levelQN = new QName(ELE_LEVEL);
        QName antibodyQN = new QName(ELE_ANTIBODY);

        String version = null;
        String url = null;

        String geneName = null;
        String geneAccession = null;
        String dbNameForIdentifier = null;

        String xrefAc = null;
        String xrefDb = null;
        boolean tissueExpressionPresent = false;

        boolean antibodyPresent = false;

        String tissueStatus = null;
        String tissue = null;
        String cellType = null;
        String levelType = null;
        String level = null;

        String verificationType = null;
        String verification = null;

        HPAEntryBean hpaEntryBean = null;

        GeneBean geneBean = null;

        List<DbSourceAcEntryBean> dbSourceAcEntryBeans = new ArrayList<DbSourceAcEntryBean>();

        List<PEEvidenceBean> peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>();

        PEEvidenceBean antiIHCNormEvidenceBean = null;

        AccessionBean identifiedAcBean = null;

        while (xmlEventReader.hasNextEvent()) {
            //eventType = reader.next();
            XMLEvent event = xmlEventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement element = event.asStartElement();

                //hpa entry
                if (element.getName().equals(entryQN)) {
                    //start to create a hpaEntryBean
                    hpaEntryBean = new HPAEntryBean();
                    //create a GeneBean
                    geneBean = new GeneBean();
                    //create a list of DbSourceAcEntryBean to store all DbSource and Ac
                    dbSourceAcEntryBeans = new ArrayList<DbSourceAcEntryBean>();
                    //create a list of PEEvidenceBean to store all antibody evidencs for the current gene
                    peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>();

                    //get the version attribute
                    Attribute versionAttr = element.getAttributeByName(versionQN);
                    if (versionAttr != null) {
                        version = versionAttr.getValue();
                    }
                    //get the url attribute
                    Attribute urlAttr = element.getAttributeByName(urlQN);
                    if (urlAttr != null) {
                        url = urlAttr.getValue();
                    }
                }

                //parse the gene name in the name element
                if (element.getName().equals(nameQN)) {
                    if (xmlEventReader.peek().isCharacters()) {
                        event = xmlEventReader.nextEvent();
                        Characters geneCharacters = event.asCharacters();
                        if (geneCharacters != null) {
                            geneName = geneCharacters.getData();
                        }
                    }
                }

                //parse the ensg accession and db in the identifier element
                if (element.getName().equals(identiferQN)) {
                    Attribute idAttr = element.getAttributeByName(idQN);
                    if (idAttr != null) {
                        geneAccession = idAttr.getValue();
                    }
                    Attribute dbAttr = element.getAttributeByName(dbQN);
                    if (dbAttr != null) {
                        dbNameForIdentifier = dbAttr.getValue();
                    }
                }

                //parse all db and accession pair in xref element
                if (element.getName().equals(xrefQN)) {
                    Attribute idAttr = element.getAttributeByName(idQN);
                    if (idAttr != null) {
                        xrefAc = idAttr.getValue();
                    }
                    Attribute dbAttr = element.getAttributeByName(dbQN);
                    if (dbAttr != null) {
                        xrefDb = dbAttr.getValue();
                    }
                }

                //parse tissueExpression
                if (element.getName().equals(tissueExpQN)) {
                    //we only focus on the tissueExpression element in the path /entry/tissueExpression
                    if (!antibodyPresent) {
                        //set the tissueExpression present flag into true;
                        tissueExpressionPresent = true;
                        //create a list of PEEvidenceBean to store the PEEvidence for antibody
                        peAntiIHCNormEvidenceBeans = new ArrayList<PEEvidenceBean>();
                    }
                }

                //parse the verification element to get reliability or validation value
                if (element.getName().equals(verificationQN)) {
                    //we only focus on the verification element in the path /entry/tissueExpression/verification
                    if (!antibodyPresent && tissueExpressionPresent) {
                        Attribute verifAttr = element.getAttributeByName(typeQN);
                        if (verifAttr != null) {
                            verificationType = element.getAttributeByName(typeQN).getValue();
                        }
                        if (xmlEventReader.peek().isCharacters()) {
                            event = xmlEventReader.nextEvent();
                            verification = event.asCharacters().getData();
                        }
                    }
                }
                //start of the data element
                if (element.getName().equals(dataQN)) {
                    //we only focus on the data element in the path /entry/tissueExpression/data
                    if (!antibodyPresent && tissueExpressionPresent) {
                        antiIHCNormEvidenceBean = new PEEvidenceBean();
                        TPBDataTypeBean dataTypeBean = createTPBDataTypeBeanForPEANTIIHCNORM();
                        antiIHCNormEvidenceBean.setTpbDataTypeBean(dataTypeBean);
                    }
                }

                //start of tissue
                if (element.getName().equals(tissueQN)) {
                    //we only focus on the tissue element in the path /entry/tissueExpression/data/tissue
                    if (!antibodyPresent && tissueExpressionPresent) {
                        Attribute tissueStatusAttr = element.getAttributeByName(statusQN);
                        if (tissueStatusAttr != null) {
                            tissueStatus = tissueStatusAttr.getValue();
                        }
                        if (xmlEventReader.peek().isCharacters()) {
                            event = xmlEventReader.nextEvent();
                            tissue = event.asCharacters().getData();
                        }
                    }
                }

                //start of cellType
                if (element.getName().equals(cellTypeQN)) {
                    //we only focus on the cellType element in the path /entry/tissueExpression/data/cellType
                    if (!antibodyPresent && tissueExpressionPresent) {
                        if (xmlEventReader.peek().isCharacters()) {
                            event = xmlEventReader.nextEvent();
                            cellType = event.asCharacters().getData();
                        }
                    }
                }

                //start of level
                if (element.getName().equals(levelQN)) {
                    //we only focus on the level element in the path /entry/tissueExpression/data/level
                    if (!antibodyPresent && tissueExpressionPresent) {
                        Attribute typeAttr = element.getAttributeByName(typeQN);
                        if (typeAttr != null) {
                            levelType = typeAttr.getValue();
                        }
                        if (xmlEventReader.peek().isCharacters()) {
                            event = xmlEventReader.nextEvent();
                            level = event.asCharacters().getData();
                        }
                    }
                }
                //start of antibody element
                if (element.getName().equals(antibodyQN)) {
                    //we have to setup antibodyPresent flag as true
                    antibodyPresent = true;
                }
            }

            //End of element
            if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                //hpa entry end
                if (endElement.getName().equals(entryQN)) {
                    //set hpa version
                    hpaEntryBean.setHpaVersion(version);
                    //hpaEntryBean set gene bean
                    hpaEntryBean.setGeneBean(geneBean);
                    //create the primary dbsource bean
                    DBSourceBean primaryDbSourceBean = createPrimaryDBSourceBeanForHPA();

                    //set the primary DBSourceBean
                    hpaEntryBean.setPrimaryDbSourceBean(primaryDbSourceBean);

                    //set the identified accesion bean
                    hpaEntryBean.setIdentifiedAccessionBean(identifiedAcBean);

                    //set DbSourceAcEntryBean list
                    hpaEntryBean.setDbSourceAcEntryBeans(dbSourceAcEntryBeans);

                    //set all the PeAntiIHCBody evidences
                    if (peAntiIHCNormEvidenceBeans.size() == 0) {
                        peAntiIHCNormEvidenceBeans.add(createNonePEEvidence(url));
                    }

                    hpaEntryBean.setPeAntiIHCNormEvidencesBeans(peAntiIHCNormEvidenceBeans);

                    //add the current hpa entry bean into list
                    hpaEntryBeans.add(hpaEntryBean);
                    //reset version and url
                    version = null;
                    url = null;
                    identifiedAcBean = null;
                }

                //end of gene name, populate the gene name
                if (endElement.getName().equals(nameQN)) {
                    //set gene name
                    geneBean.setDisplayName(geneName);
                }

                //end of identifier, populating for gene accession, db and accessions if any
                if (endElement.getName().equals(identiferQN)) {
                    //set the gene accession
                    geneBean.setEnsgAccession(geneAccession);

                    identifiedAcBean = createIdentifiedAcBean(geneAccession, dbNameForIdentifier);
                    //create a DbSourceAcEntryBean based on the identifier element
                    DbSourceAcEntryBean dbSourceAcEntryBean = createDbSourceAcEntry(dbNameForIdentifier,
                            geneAccession);
                    //add this DbSourceAcEntryBean into list
                    dbSourceAcEntryBeans.add(dbSourceAcEntryBean);
                }

                //end of xref element.  populate for db and accessions if any
                if (endElement.getName().equals(xrefQN)) {
                    //create a DbSourceAcEntryBean based on the xref element
                    DbSourceAcEntryBean dbSourceAcEntryBean = createDbSourceAcEntry(xrefDb, xrefAc);
                    //add this DbSoureAcEntryBean into list
                    dbSourceAcEntryBeans.add(dbSourceAcEntryBean);
                    //set rest of db and accession values
                    xrefDb = null;
                    xrefAc = null;
                }
                //end of the tissueExpression
                if (endElement.getName().equals(tissueExpQN)) {
                    //we only focus on the tissueExpression element in the path /entry/tissueExpression
                    if (!antibodyPresent) {
                        //the tissueExpression is end. we have to reset tissueExpressionPresent,
                        //verificationType and verification values under the tissueExpression element level
                        //reset tissueExpression present flag into false
                        tissueExpressionPresent = false;
                        //reset verification type
                        verificationType = null;
                        //reset verification value
                        verification = null;
                    }
                }

                //end of data element
                if (endElement.getName().equals(dataQN)) {
                    //we only focus on the data element in the path /entry/tissueExpression/data
                    if (!antibodyPresent && tissueExpressionPresent) {
                        //we only consider the tissue status is normal one
                        if (StringUtils.endsWithIgnoreCase(tissueStatus, TISSUE_STATUS_NORMAL)) {
                            setAntiEvidence(antiIHCNormEvidenceBean, url, verification, tissue, cellType, level,
                                    levelType);
                            //add anti evidence
                            peAntiIHCNormEvidenceBeans.add(antiIHCNormEvidenceBean);
                        }
                        //the data element is end. we have to reset the tissueStatus, tissue, cellType and level values under the data element level
                        tissueStatus = null;
                        tissue = null;
                        cellType = null;
                        level = null;
                        levelType = null;
                    }
                }
                //end of antibody
                if (endElement.getName().equals(antibodyQN)) {
                    //we have to reset antibodyPresent flag as false
                    antibodyPresent = false;
                }
            }
            //End of XML document
            if (event.isEndDocument()) {
                // finished to parse the whole document;
                break;
            }
        }
    } catch (Exception ex) {
        logger.error(ex);
        throw new DMXMLParserException(ex);
    } finally {
        if (xmlEventReader != null) {
            try {
                xmlEventReader.close();
            } catch (Exception e) {
                //ignore whatever caught.
            }
        }
    }
    return hpaEntryBeans;
}

From source file:com.globalqss.ObPOSInterface.ExternalSalesImpl.java

public static void authenticate(String username, String password, String webServiceName, String method)
        throws XFireFault {
    String dbpwd = DB.getSQLValueString(null,
            "SELECT Password FROM AD_User WHERE Name=? AND Password IS NOT NULL", username); // and ad_client_id in (0,?)
    if (dbpwd == null || dbpwd.length() <= 0)
        throw new XFireFault("Invalid user/password", new QName("username"));

    String isencr = DB.getSQLValueString(null, "SELECT IsEncrypted FROM AD_Column WHERE AD_Column_ID=417");
    if ("Y".equals(isencr))
        dbpwd = SecureEngine.decrypt(dbpwd);

    String hashPassword = null;/*from   w  w  w.  j a  va2s  .com*/
    try {
        hashPassword = new String(
                Base64.encodeBase64(MessageDigest.getInstance("SHA-1").digest(dbpwd.getBytes("UTF-8"))),
                "ASCII");
    } catch (UnsupportedEncodingException e1) {
        throw new XFireFault("Error hashing db password", e1, new QName("username"));
    } catch (NoSuchAlgorithmException e1) {
        throw new XFireFault("Error hashing db password", e1, new QName("username"));
    }

    if (!hashPassword.equals(password))
        /* Invalid password */
        throw new XFireFault("Invalid user/password", new QName("password"));

    throw new XFireFault("Security not implemented yet", new QName("webServiceName"));
    // TODO: authenticate web service and method
    // TODO: Search for a service type for client and role access with the same value as the method
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp,
        MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlObjectTreeModel treeModel = null;
    XmlCursor cursor = messagePart.newCursor();
    XmlObject rootXmlObject = cursor.getObject();

    try {// w  w w  .j a  v a2 s  . co  m
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which
                // specify a content
                // element referring to the attachment)
                if (messagePart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(XOP_HREF_QNAME);
                    if (href != null && href.length() > 0) {
                        contentIds.put(messagePart.getPart().getName(), href);
                    }

                    break;
                }

                XmlObject xmlObj = cursor.getObject();
                SchemaType schemaType = xmlObj.schemaType();
                if (schemaType.isNoType()) {
                    if (treeModel == null) {
                        treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(),
                                rootXmlObject);
                    }

                    XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj);
                    if (tn != null)
                        schemaType = tn.getSchemaType();
                }

                if (AttachmentUtils.isSwaRefType(schemaType)) {
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);

                        try {
                            // is the textcontent already a URI?
                            new URI(textContent);
                            contentIds.put(textContent, textContent);
                        } catch (RuntimeException e) {
                            // not a URI.. try to create one..
                            String contentId = textContent + "@soapui.org";
                            cursor.setTextValue("cid:" + contentId);
                            contentIds.put(textContent, contentId);
                        }
                    }
                } else if (AttachmentUtils.isXopInclude(schemaType)) {
                    String contentId = cursor.getAttributeText(new QName("href"));
                    if (contentId != null && contentId.length() > 0) {
                        contentIds.put(contentId, contentId);
                        isXop = true;

                        Attachment[] attachments = container.getAttachmentsForPart(contentId);
                        if (attachments.length == 1) {
                            XmlCursor cur = cursor.newCursor();
                            if (cur.toParent()) {
                                String contentType = getXmlMimeContentType(cur);
                                if (contentType != null && contentType.length() > 0)
                                    attachments[0].setContentType(contentType);
                            }

                            cur.dispose();
                        }
                    }
                } else {
                    // extract contentId
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent)) {
                        Attachment attachment = null;
                        boolean isXopAttachment = false;

                        // is content a reference to a file?
                        if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) {
                            String filename = textContent.substring(5);
                            if (container.isMtomEnabled()) {
                                MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                String xmimeContentType = getXmlMimeContentType(cursor);

                                if (StringUtils.isNullOrEmpty(xmimeContentType))
                                    xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename);

                                part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename),
                                        xmimeContentType, schemaType)));
                                part.setContentID("<" + filename + ">");
                                mp.addBodyPart(part);

                                isXopAttachment = true;
                            } else {
                                if (new File(filename).exists()) {
                                    inlineData(cursor, schemaType, new FileInputStream(filename));
                                } else {
                                    Attachment att = getAttachmentForFilename(container, filename);
                                    if (att != null)
                                        inlineData(cursor, schemaType, att.getInputStream());
                                }
                            }
                        } else {
                            Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent);
                            if (textContent.startsWith("cid:")) {
                                textContent = textContent.substring(4);
                                attachmentsForPart = container.getAttachmentsForPart(textContent);

                                Attachment[] attachments = attachmentsForPart;
                                if (attachments.length == 1) {
                                    attachment = attachments[0];
                                } else if (attachments.length > 1) {
                                    attachment = buildMulitpartAttachment(attachments);
                                }

                                isXopAttachment = container.isMtomEnabled();
                                contentIds.put(textContent, textContent);
                            }
                            // content should be binary data; is this an XOP element
                            // which should be serialized with MTOM?
                            else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType)
                                    || SchemaUtils.isAnyType(schemaType))) {
                                if ("true".equals(System.getProperty("soapui.mtom.strict"))) {
                                    if (SchemaUtils.isAnyType(schemaType)) {
                                        textContent = null;
                                    } else {
                                        for (int c = 0; c < textContent.length(); c++) {
                                            if (Character.isWhitespace(textContent.charAt(c))) {
                                                textContent = null;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (textContent != null) {
                                    MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                    String xmimeContentType = getXmlMimeContentType(cursor);

                                    part.setDataHandler(new DataHandler(
                                            new XOPPartDataSource(textContent, xmimeContentType, schemaType)));

                                    textContent = "http://www.soapui.org/" + System.nanoTime();

                                    part.setContentID("<" + textContent + ">");
                                    mp.addBodyPart(part);

                                    isXopAttachment = true;
                                }
                            } else if (container.isInlineFilesEnabled() && attachmentsForPart != null
                                    && attachmentsForPart.length > 0) {
                                attachment = attachmentsForPart[0];
                            }
                        }

                        // add XOP include?
                        if (isXopAttachment && container.isMtomEnabled()) {
                            buildXopInclude(cursor, textContent);
                            isXop = true;
                        }
                        // inline?
                        else if (attachment != null) {
                            inlineAttachment(cursor, schemaType, attachment);
                        }
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}