Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

In this page you can find the example usage for org.jdom2 Element getChild.

Prototype

public Element getChild(final String cname, final Namespace ns) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to the given namespace.

Usage

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a result list in response to an EDS API Search Request
 *//*  w  w  w.j  av a  2s.c o m*/
public ResultsList buildResultsList(Response response) {

    ResultsList resultsList = new ResultsList();
    String resultsListXML = "";

    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        resultsList.setApierrormessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        BufferedReader reader = response.getRead();
        if (null != reader) {
            try {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    resultsListXML += line;
                }
            } catch (IOException e) {
                ApiErrorMessage errorMessage = new ApiErrorMessage();
                errorMessage.setErrorDescription("Error processing resultList response");
                errorMessage.setDetailedErrorDescription(e.getMessage());
                resultsList.setApierrormessage(errorMessage);
            }
        }
        try {
            StringReader stringReader = new StringReader(resultsListXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);
            // root element (level 1), handle resultsList
            Element searchResponseMessageGet = doc.getRootElement();

            // level 2 elements
            if (null == searchResponseMessageGet)
                return resultsList;

            Element searchRequestGet = searchResponseMessageGet.getChild("SearchRequestGet",
                    searchResponseMessageGet.getNamespace());
            Element searchResult = searchResponseMessageGet.getChild("SearchResult",
                    searchResponseMessageGet.getNamespace());
            // level 3 elements
            if (null != searchRequestGet) {
                Element queryString = searchRequestGet.getChild("QueryString", searchRequestGet.getNamespace());
                // Get Query String
                String querystring = queryString.getContent(0).getValue();
                resultsList.setQueryString(querystring);
            }

            Element statistics = searchResult.getChild("Statistics", searchResult.getNamespace());
            Element data = searchResult.getChild("Data", searchResult.getNamespace());

            /*
             * In next steps, elements will be analyzed separately
             */

            // Get Total Hits and Total Search Time
            String totalHits = "0";
            if (null != statistics) {
                totalHits = statistics.getContent(0).getValue();
                String totalSearchTime = statistics.getContent(1).getValue();
                resultsList.setHits(totalHits);
                resultsList.setSearchTime(totalSearchTime);
            }

            if (Integer.parseInt(totalHits) > 0 && null != data) {
                // Get Results
                Element records = data.getChild("Records", data.getNamespace());
                if (null != records && null != records.getChildren()) {
                    List<Element> recordsList = records.getChildren();
                    for (int i = 0; i < recordsList.size(); i++) {
                        Element xmlRecord = (Element) recordsList.get(i);
                        if (null == xmlRecord)
                            continue;
                        Record record = new Record();
                        record = constructRecord(xmlRecord);
                        resultsList.getResultsList().add(record);
                    }
                }
            }
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            resultsList.setApierrormessage(errorMessage);
        }
    }
    return resultsList;

}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

/**
 * Constructs a retrieve response object from the EDS API response XML
 * message/*from w w w .j a  v  a2s  .c  o m*/
 */
public RetrieveResult buildRecord(Response response) {

    RetrieveResult retrieveResult = new RetrieveResult();
    BufferedReader reader = response.getRead();
    String RecordXML = "";
    if (null != response.getErrorStream() && !response.getErrorStream().isEmpty()) {
        retrieveResult.setApiErrorMessage(ProcessError(response.getErrorNumber(), response.getErrorStream()));
    } else {
        try {
            String line = "";
            while ((line = reader.readLine()) != null) {
                RecordXML += line;
            }
        } catch (IOException e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing resultList response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            retrieveResult.setApiErrorMessage(errorMessage);
        }
        try {
            StringReader stringReader = new StringReader(RecordXML);
            InputSource inputSource = new InputSource(stringReader);
            Document doc = (new SAXBuilder()).build(inputSource);

            // ---------------begin to handle record

            // root element (level 1)
            Element data = doc.getRootElement();
            // level 2 elements

            // Get Results
            Element xmlRecord = data.getChild("Record", data.getNamespace());
            Record record = null;
            if (null != xmlRecord)
                record = constructRecord(xmlRecord, true);
            retrieveResult.setRecord(record);
        } catch (Exception e) {
            ApiErrorMessage errorMessage = new ApiErrorMessage();
            errorMessage.setErrorDescription("Error processing search response");
            errorMessage.setDetailedErrorDescription(e.getMessage());
            retrieveResult.setApiErrorMessage(errorMessage);
        }
    }
    return retrieveResult;

}

From source file:com.eds.Response.XMLProcessor.java

License:Apache License

private Record constructRecord(Element xmlRecord, Boolean parse) {
    Record record = new Record();

    // Get Record Id
    String resultId = xmlRecord.getChildText("ResultId", xmlRecord.getNamespace());
    record.setResultId(resultId);/* www .j  a  v a2 s .c o  m*/

    // Get Header Info
    Element header = xmlRecord.getChild("Header", xmlRecord.getNamespace());
    if (null != header) {
        String dbId = header.getChildText("DbId", header.getNamespace());
        String dbLabel = header.getChildText("DbLabel", header.getNamespace());
        String an = header.getChildText("An", header.getNamespace());
        String pubType = header.getChildText("PubType", header.getNamespace());
        String pubTypeId = header.getChildText("PubTypeId", header.getNamespace());

        record.setDbId(dbId);
        record.setDbLabel(dbLabel);
        record.setPubTypeId(pubTypeId);
        record.setAn(an);
        record.setPubType(pubType);
    }
    // Get PLink
    String pLink = xmlRecord.getChildText("PLink", xmlRecord.getNamespace());
    record.setpLink(pLink);

    // Get ImageInfo

    Element imageInfo = xmlRecord.getChild("ImageInfo", xmlRecord.getNamespace());

    if (imageInfo != null) {
        List<Element> coverArts = imageInfo.getChildren();
        for (int b = 0; b < coverArts.size(); b++) {
            Element coverArt = (Element) coverArts.get(b);
            if (null != coverArt) {
                BookJacket bookJacket = new BookJacket();
                String size = coverArt.getChildText("Size", coverArt.getNamespace());
                String target = coverArt.getChildText("Target", coverArt.getNamespace());
                bookJacket.setSize(size);
                bookJacket.setTarget(target);
                record.getBookJacketList().add(bookJacket);
            }
        }
    }

    // Get Custom Links
    Element customLinks = xmlRecord.getChild("CustomLinks", xmlRecord.getNamespace());
    if (customLinks != null) {
        List<Element> customLinksList = customLinks.getChildren();
        for (int c = 0; c < customLinksList.size(); c++) {
            Element cl = (Element) customLinksList.get(c);
            if (null != cl) {
                String clurl = cl.getChildText("Url", cl.getNamespace());
                String name = cl.getChildText("Name", cl.getNamespace());
                String category = cl.getChildText("Category", cl.getNamespace());
                String text = cl.getChildText("Text", cl.getNamespace());
                String icon = cl.getChildText("Icon", cl.getNamespace());
                String mouseOverText = cl.getChildText("MouseOverText", cl.getNamespace());

                CustomLink customLink = new CustomLink();
                customLink.setUrl(clurl);
                customLink.setName(name);
                customLink.setCategory(category);
                customLink.setText(text);
                customLink.setIcon(icon);
                customLink.setMouseOverText(mouseOverText);
                record.getCustomLinkList().add(customLink);
            }
        }
    }

    // Get Full Text Info
    Element fullText = xmlRecord.getChild("FullText", xmlRecord.getNamespace());
    if (null != fullText) {
        Element htmlFullText = fullText.getChild("Text", fullText.getNamespace());
        if (null != htmlFullText) {
            String availability = htmlFullText.getChildText("Availability", fullText.getNamespace());
            record.setHtml(availability);
        }
    }

    // Process Items
    Element items = xmlRecord.getChild("Items", xmlRecord.getNamespace());
    if (null != items) {
        List<Element> itemList = items.getChildren();
        for (int j = 0; j < itemList.size(); j++) {
            Element itemElement = (Element) itemList.get(j);
            Item item = new Item();
            String label = itemElement.getChildText("Label", itemElement.getNamespace());
            String group = itemElement.getChildText("Group", itemElement.getNamespace());
            String itemData = itemElement.getChildText("Data", itemElement.getNamespace());

            if (parse)
                itemData = Jsoup.parse(itemData).text().toString();
            // translate data to valid HTML tags
            itemData = TransDataToHTML.transDataToHTML(itemData);
            item.setLabel(label);
            item.setGroup(group);
            item.setData(itemData);
            record.getItemList().add(item);
        }
    }
    return record;
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;/*from www .j a  v a 2  s.c  om*/
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

License:Apache License

private String parseXLF(JobBO p_job, File p_srcFile) {
    if (p_srcFile == null || !p_srcFile.exists())
        return "File not exits.";

    String srcLang, trgLang;/*from   www . j a v a2  s .c o m*/
    List<String> srcSegments = new ArrayList<String>();

    try {
        SAXBuilder builder = new SAXBuilder();
        Document read_doc = builder.build(p_srcFile);
        // Get Root Element
        Element root = read_doc.getRootElement();
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        // Get Source/Target Language
        srcLang = fileElem.getAttributeValue(XLF_SOURCE_LANGUAGE);
        trgLang = fileElem.getAttributeValue(XLF_TARGET_LANGUAGE);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> list = expr.evaluate(fileElem.getChild("body", namespace));
        for (int i = 0; i < list.size(); i++) {
            Element tuElem = (Element) list.get(i);
            Element srcElem = tuElem.getChild("source", namespace);
            // Get Source Segment 
            if (srcElem != null && srcElem.getContentSize() > 0) {
                String source = getInnerXMLString(srcElem);
                srcSegments.add(source);
            }
        }

        p_job.setSourceLanguage(srcLang);
        p_job.setTargetLanguage(trgLang);
        p_job.setSourceSegments(srcSegments);
    } catch (Exception e) {
        String msg = "Parse XLIFF file error.";
        logger.error(msg, e);
        return msg;
    }

    return null;
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

private void addProperty(Element element, CdsObject obj, String property, String propertyValue) {

    if (property.contains("@")) {
        Element parentElement = null;
        String strParentElement = property.substring(0, property.indexOf('@'));
        if (strParentElement.equals("")) {
            parentElement = element;/*from   w  ww  .j  av a 2s .com*/
        } else {
            parentElement = element.getChild(removePrefix(strParentElement), getNamespace(strParentElement));
            if (parentElement == null) {
                parentElement = new Element(removePrefix(strParentElement), getNamespace(strParentElement));
                parentElement.setText(obj.getProperty(strParentElement));
                element.addContent(parentElement);
            }
        }
        parentElement.setAttribute(property.substring(property.indexOf('@') + 1), propertyValue);
    } else {
        Element newElement = new Element(removePrefix(property), getNamespace(property));
        newElement.setText(propertyValue);
        element.addContent(newElement);
    }
}

From source file:com.kixeye.kixmpp.server.module.muc.MucRoom.java

License:Apache License

/**
 * A user requests to join the room.//  w ww.j  a va 2  s .c o  m
 *
 * @param channel
 * @param nickname
 * @param mucStanza
 */
public void join(final Channel channel, String nickname, Element mucStanza) {
    KixmppJid jid = channel.attr(BindKixmppServerModule.JID).get();

    if (settings.isOpen() && !jidRoles.containsKey(jid.withoutResource())) {
        addUser(jid, nickname, MucRole.Participant, MucAffiliation.Member);
    }

    verifyMembership(jid.withoutResource());
    checkForNicknameInUse(nickname, jid);

    User user = usersByNickname.get(nickname);

    boolean existingUser = true;
    if (user == null) {
        user = new User(nickname, jid.withoutResource());
        usersByNickname.put(nickname, user);
        MucRoomEventHandler handler = service.getServer().getMucRoomEventHandler();
        if (handler != null) {
            handler.userAdded(this, user);
        }
        existingUser = false;
    }

    Client client = user.addClient(new Client(jid, nickname, channel));

    // xep-0045 7.2.3 begin
    // self presence
    KixmppJid fromRoomJid = roomJid.withResource(nickname);
    channel.writeAndFlush(createPresence(fromRoomJid, jid, MucRole.Participant, null));

    if (settings.isPresenceEnabled() && !existingUser) {
        // Send presence from existing occupants to new occupant
        sendExistingOccupantsPresenceToNewOccupant(user, channel);

        // Send new occupant's presence to all occupants
        broadcastPresence(fromRoomJid, MucRole.Participant, null);
    }
    // xep-0045 7.2.3 end

    if (settings.getSubject() != null) {
        Element message = new Element("message");
        message.setAttribute("id", UUID.randomUUID().toString());
        message.setAttribute("from", roomJid.withResource(nickname).toString());
        message.setAttribute("to", channel.attr(BindKixmppServerModule.JID).get().toString());
        message.setAttribute("type", "groupchat");

        message.addContent(new Element("subject").setText(settings.getSubject()));

        channel.writeAndFlush(message);
    }

    if (mucStanza != null) {
        Element history = mucStanza.getChild("history", mucStanza.getNamespace());

        if (history != null) {
            MucHistoryProvider historyProvider = mucModule.getHistoryProvider();

            if (historyProvider != null) {
                Integer maxChars = null;
                Integer maxStanzas = null;
                Integer seconds = null;

                String parsableString = history.getAttributeValue("maxchars");
                if (parsableString != null) {
                    try {
                        maxChars = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("maxstanzas");
                if (parsableString != null) {
                    try {
                        maxStanzas = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("seconds");
                if (parsableString != null) {
                    try {
                        seconds = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }

                String since = history.getAttributeValue("since");

                historyProvider.getHistory(roomJid, user.getBareJid(), maxChars, maxStanzas, seconds, since)
                        .addListener(new GenericFutureListener<Future<List<MucHistory>>>() {
                            @Override
                            public void operationComplete(Future<List<MucHistory>> future) throws Exception {
                                if (future.isSuccess()) {
                                    List<MucHistory> historyItems = future.get();
                                    if (historyItems != null) {
                                        for (MucHistory historyItem : historyItems) {
                                            Element message = new Element("message")
                                                    .setAttribute("id", UUID.randomUUID().toString())
                                                    .setAttribute("from",
                                                            roomJid.withResource(historyItem.getNickname())
                                                                    .toString())
                                                    .setAttribute("to",
                                                            channel.attr(BindKixmppServerModule.JID).get()
                                                                    .toString())
                                                    .setAttribute("type", "groupchat");
                                            message.addContent(
                                                    new Element("body").setText(historyItem.getBody()));

                                            Element addresses = new Element("addresses", Namespace
                                                    .getNamespace("http://jabber.org/protocol/address"));
                                            addresses
                                                    .addContent(new Element("address", addresses.getNamespace())
                                                            .setAttribute("type", "ofrom").setAttribute("jid",
                                                                    historyItem.getFrom().toString()));
                                            message.addContent(addresses);

                                            message.addContent(new Element("delay",
                                                    Namespace.getNamespace("urn:xmpp:delay"))
                                                            .setAttribute("from", roomJid.toString())
                                                            .setAttribute("stamp", XmppDateUtils
                                                                    .format(historyItem.getTimestamp())));

                                            channel.write(message);
                                        }
                                        channel.flush();
                                    }
                                }
                            }
                        });
            }
        }
    }

    channel.closeFuture().addListener(new CloseChannelListener(client));
}

From source file:com.rometools.modules.base.io.CustomTagParser.java

License:Open Source License

@Override
public Module parse(final Element element, final Locale locale) {
    final CustomTags module = new CustomTagsImpl();
    final ArrayList<CustomTag> tags = new ArrayList<CustomTag>();
    final List<Element> elements = element.getChildren();
    final Iterator<Element> it = elements.iterator();
    while (it.hasNext()) {
        final Element child = it.next();
        if (child.getNamespace().equals(NS)) {
            final String type = child.getAttributeValue("type");
            try {
                if (type == null) {
                    continue;
                } else if (type.equals("string")) {
                    tags.add(new CustomTagImpl(child.getName(), child.getText()));
                } else if (type.equals("int")) {
                    tags.add(new CustomTagImpl(child.getName(), new Integer(child.getTextTrim())));
                } else if (type.equals("float")) {
                    tags.add(new CustomTagImpl(child.getName(), new Float(child.getTextTrim())));
                } else if (type.equals("intUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new IntUnit(child.getTextTrim())));
                } else if (type.equals("floatUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new FloatUnit(child.getTextTrim())));
                } else if (type.equals("date")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new ShortDate(GoogleBaseParser.SHORT_DT_FMT.parse(child.getTextTrim()))));
                    } catch (final ParseException e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }//from w  w  w .j  av  a  2s .  co m
                } else if (type.equals("dateTime")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                GoogleBaseParser.LONG_DT_FMT.parse(child.getTextTrim())));
                    } catch (final ParseException e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("dateTimeRange")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new DateTimeRange(
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("start", CustomTagParser.NS).getText().trim()),
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("end", CustomTagParser.NS).getText().trim()))));
                    } catch (final Exception e) {
                        LOG.warn("Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("url")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(), new URL(child.getTextTrim())));
                    } catch (final MalformedURLException e) {
                        LOG.warn("Unable to parse URL type on " + child.getName(), e);
                    }
                } else if (type.equals("boolean")) {
                    tags.add(
                            new CustomTagImpl(child.getName(), new Boolean(child.getTextTrim().toLowerCase())));
                } else if (type.equals("location")) {
                    tags.add(new CustomTagImpl(child.getName(), new CustomTagImpl.Location(child.getText())));
                } else {
                    throw new Exception("Unknown type: " + type);
                }
            } catch (final Exception e) {
                LOG.warn("Unable to parse type on " + child.getName(), e);
            }
        }
    }
    module.setValues(tags);
    return module;
}

From source file:com.rometools.modules.base.io.GoogleBaseParser.java

License:Open Source License

private void handleTag(final Element tag, final PropertyDescriptor pd, final GoogleBase module)
        throws Exception {
    Object tagValue = null;//from  w w  w .j a va  2 s.com

    if (pd.getPropertyType() == Integer.class || pd.getPropertyType().getComponentType() == Integer.class) {
        tagValue = new Integer(
                GoogleBaseParser.stripNonValidCharacters(GoogleBaseParser.INTEGER_CHARS, tag.getText()));
    } else if (pd.getPropertyType() == Float.class || pd.getPropertyType().getComponentType() == Float.class) {
        tagValue = new Float(
                GoogleBaseParser.stripNonValidCharacters(GoogleBaseParser.FLOAT_CHARS, tag.getText()));
    } else if (pd.getPropertyType() == String.class
            || pd.getPropertyType().getComponentType() == String.class) {
        tagValue = tag.getText();
    } else if (pd.getPropertyType() == URL.class || pd.getPropertyType().getComponentType() == URL.class) {
        tagValue = new URL(tag.getText().trim());
    } else if (pd.getPropertyType() == Boolean.class
            || pd.getPropertyType().getComponentType() == Boolean.class) {
        tagValue = new Boolean(tag.getText().trim());
    } else if (pd.getPropertyType() == Date.class || pd.getPropertyType().getComponentType() == Date.class) {
        final String text = tag.getText().trim();

        if (text.length() > 10) {
            tagValue = GoogleBaseParser.LONG_DT_FMT.parse(text);
        } else {
            tagValue = GoogleBaseParser.SHORT_DT_FMT.parse(text);
        }
    } else if (pd.getPropertyType() == IntUnit.class
            || pd.getPropertyType().getComponentType() == IntUnit.class) {
        tagValue = new IntUnit(tag.getText());
    } else if (pd.getPropertyType() == FloatUnit.class
            || pd.getPropertyType().getComponentType() == FloatUnit.class) {
        tagValue = new FloatUnit(tag.getText());
    } else if (pd.getPropertyType() == DateTimeRange.class
            || pd.getPropertyType().getComponentType() == DateTimeRange.class) {
        tagValue = new DateTimeRange(
                LONG_DT_FMT.parse(tag.getChild("start", GoogleBaseParser.NS).getText().trim()),
                LONG_DT_FMT.parse(tag.getChild("end", GoogleBaseParser.NS).getText().trim()));
    } else if (pd.getPropertyType() == ShippingType.class
            || pd.getPropertyType().getComponentType() == ShippingType.class) {
        final FloatUnit price = new FloatUnit(tag.getChild("price", GoogleBaseParser.NS).getText().trim());
        ShippingType.ServiceEnumeration service = ShippingType.ServiceEnumeration
                .findByValue(tag.getChild("service", GoogleBaseParser.NS).getText().trim());

        if (service == null) {
            service = ShippingType.ServiceEnumeration.STANDARD;
        }

        final String country = tag.getChild("country", GoogleBaseParser.NS).getText().trim();
        tagValue = new ShippingType(price, service, country);
    } else if (pd.getPropertyType() == PaymentTypeEnumeration.class
            || pd.getPropertyType().getComponentType() == PaymentTypeEnumeration.class) {
        tagValue = PaymentTypeEnumeration.findByValue(tag.getText().trim());
    } else if (pd.getPropertyType() == PriceTypeEnumeration.class
            || pd.getPropertyType().getComponentType() == PriceTypeEnumeration.class) {
        tagValue = PriceTypeEnumeration.findByValue(tag.getText().trim());
    } else if (pd.getPropertyType() == CurrencyEnumeration.class
            || pd.getPropertyType().getComponentType() == CurrencyEnumeration.class) {
        tagValue = CurrencyEnumeration.findByValue(tag.getText().trim());
    } else if (pd.getPropertyType() == GenderEnumeration.class
            || pd.getPropertyType().getComponentType() == GenderEnumeration.class) {
        tagValue = GenderEnumeration.findByValue(tag.getText().trim());
    } else if (pd.getPropertyType() == YearType.class
            || pd.getPropertyType().getComponentType() == YearType.class) {
        tagValue = new YearType(tag.getText().trim());
    } else if (pd.getPropertyType() == Size.class || pd.getPropertyType().getComponentType() == Size.class) {
        tagValue = new Size(tag.getText().trim());
    }

    if (!pd.getPropertyType().isArray()) {
        pd.getWriteMethod().invoke(module, new Object[] { tagValue });
    } else {
        final Object[] current = (Object[]) pd.getReadMethod().invoke(module, (Object[]) null);
        final int newSize = current == null ? 1 : current.length + 1;
        final Object setValue = Array.newInstance(pd.getPropertyType().getComponentType(), newSize);

        int i = 0;

        for (; current != null && i < current.length; i++) {
            Array.set(setValue, i, current[i]);
        }

        Array.set(setValue, i, tagValue);
        pd.getWriteMethod().invoke(module, new Object[] { setValue });
    }
}

From source file:com.rometools.modules.content.io.ContentModuleParser.java

License:Open Source License

@Override
public com.rometools.rome.feed.module.Module parse(final Element element, final Locale locale) {
    boolean foundSomething = false;
    final ContentModule cm = new ContentModuleImpl();
    final List<Element> encodeds = element.getChildren("encoded", CONTENT_NS);
    final ArrayList<String> contentStrings = new ArrayList<String>();
    final ArrayList<String> encodedStrings = new ArrayList<String>();

    if (!encodeds.isEmpty()) {
        foundSomething = true;// w  w  w  . j  a  v a 2s .c o m

        for (int i = 0; i < encodeds.size(); i++) {
            final Element encodedElement = encodeds.get(i);
            encodedStrings.add(encodedElement.getText());
            contentStrings.add(encodedElement.getText());
        }
    }

    final ArrayList<ContentItem> contentItems = new ArrayList<ContentItem>();
    final List<Element> items = element.getChildren("items", CONTENT_NS);

    for (int i = 0; i < items.size(); i++) {
        foundSomething = true;

        final List<Element> lis = items.get(i).getChild("Bag", RDF_NS).getChildren("li", RDF_NS);

        for (int j = 0; j < lis.size(); j++) {
            final ContentItem ci = new ContentItem();
            final Element li = lis.get(j);
            final Element item = li.getChild("item", CONTENT_NS);
            final Element format = item.getChild("format", CONTENT_NS);
            final Element encoding = item.getChild("encoding", CONTENT_NS);
            final Element value = item.getChild("value", RDF_NS);

            if (value != null) {
                if (value.getAttributeValue("parseType", RDF_NS) != null) {
                    ci.setContentValueParseType(value.getAttributeValue("parseType", RDF_NS));
                }

                if (ci.getContentValueParseType() != null && ci.getContentValueParseType().equals("Literal")) {
                    ci.setContentValue(getXmlInnerText(value));
                    contentStrings.add(getXmlInnerText(value));
                    ci.setContentValueNamespaces(value.getAdditionalNamespaces());
                } else {
                    ci.setContentValue(value.getText());
                    contentStrings.add(value.getText());
                }

                ci.setContentValueDOM(value.clone().getContent());
            }

            if (format != null) {
                ci.setContentFormat(format.getAttribute("resource", RDF_NS).getValue());
            }

            if (encoding != null) {
                ci.setContentEncoding(encoding.getAttribute("resource", RDF_NS).getValue());
            }

            if (item != null) {
                final Attribute about = item.getAttribute("about", RDF_NS);

                if (about != null) {
                    ci.setContentAbout(about.getValue());
                }
            }

            contentItems.add(ci);
        }
    }

    cm.setEncodeds(encodedStrings);
    cm.setContentItems(contentItems);
    cm.setContents(contentStrings);

    return foundSomething ? cm : null;
}