List of usage examples for org.dom4j Element getStringValue
String getStringValue();
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
License:Apache License
/** * Returns the collection profile IDs that are in the document without data. * //ww w.j a v a2 s . c o m * @param doc * the docuemnt to seasrch * @return a list of IDs */ private List<Integer> getPreservationActionPlanIds(Document doc) { // Get data elements that have data and a number as content XPath xpath = doc.createXPath("//plato:preservationActionPlan[number(.) = number(.)]"); Map<String, String> namespaceMap = new HashMap<String, String>(); namespaceMap.put("plato", PlanXMLConstants.PLATO_NS); xpath.setNamespaceURIs(namespaceMap); @SuppressWarnings("unchecked") List<Element> elements = xpath.selectNodes(doc); List<Integer> objectIds = new ArrayList<Integer>(elements.size()); for (Element element : elements) { objectIds.add(Integer.parseInt(element.getStringValue())); } return objectIds; }
From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java
License:Open Source License
/** * initialize principals./*from w ww. ja v a 2 s . c om*/ * * @param root dom4j element * @return */ private Map<RolePrincipal, String> initPrincipals(Element root) { Element principalsElement = root.element(XmlAuthenticationManager.PRINCIPALS); List<Element> principalsList = principalsElement.elements(XmlAuthenticationManager.PRINCIPAL); principals = new HashMap<String, Principal>(); principalsSet = new HashSet<Principal>(); Iterator<Element> itPrincipalsList = principalsList.iterator(); Map<RolePrincipal, String> principalsAndOrganizationRefs = new HashMap<RolePrincipal, String>(); while (itPrincipalsList.hasNext()) { Element principalElement = itPrincipalsList.next(); String principalClass = principalElement.element(XmlAuthenticationManager.CLASS).getStringValue(); if (!RolePrincipal.class.getName().equals(principalClass)) { throw new IllegalArgumentException("class=+" + principalClass + "is unsupported ; only class=" + RolePrincipal.class.getName() + " is supported"); } Element applicationNameElement = principalElement.element(XmlAuthenticationManager.APPLICATION_NAME); Element organizationRefElement = principalElement.element(XmlAuthenticationManager.ORGANIZATION_REF); String organizationRefId = organizationRefElement.getStringValue(); RolePrincipal principal = new RolePrincipal( principalElement.element(XmlAuthenticationManager.NAME).getStringValue(), applicationNameElement.getStringValue()); principalsAndOrganizationRefs.put(principal, organizationRefId); principals.put(principal.getName(), principal); principalsSet.add(principal); if (principal.getApplicationName().equals(applicationName)) { localPrincipalsSet.add(principal); localPrincipals.put(principal.getName(), principal); } } if (localPrincipalsSet.isEmpty()) { throw new IllegalStateException( "no principals are granted to the current application=" + getApplicationName()); } return principalsAndOrganizationRefs; }
From source file:net.skillupjapan.openfire.plugin.SUJMessageHandlerPlugin.java
License:Open Source License
public void interceptPacket(Packet packet, Session session, boolean read, boolean processed) throws PacketRejectedException { if ((packet instanceof Message)) { Log.warn("Got message: " + packet.toString()); }//from w ww. j a v a 2 s .c o m /** * Ignore forwarded messages */ if ((packet instanceof Message) && (((Message) packet).getElement().attributeValue("forwarded") != null)) { if (Log.isDebugEnabled()) { Log.warn("Ignoring forwarded message: " + packet.toString()); } return; } /** * Adds date to all conversation packets, in the same fashion * as an offline packet, as described below. * * Returned message: * <message from='romeo@montague.net/orchard' to='juliet@capulet.com' type='chat'> * <body> * O blessed, blessed night! I am afeard. * Being in night, all this is but a dream, * Too flattering-sweet to be substantial. * </body> * <delay xmlns='urn:xmpp:delay' from='capulet.com' stamp='2002-09-10T23:08:25Z'/> * </message> */ if (isValidAddDataPacket(packet, read, processed)) { Packet original = packet; // Add date to message packets Packet dated_packet = sujMessageHandler.addDate(packet); original = dated_packet; if (Log.isDebugEnabled()) { Log.debug("SUJ Message Handler: modified packet:" + original.toString()); } } /** * An IQ packet can send a query for the count of messages for the given rooms * * Example query: * <iq type='get' id='xdfw-1'> * <query xmlns='xmpp:join:msgq'> * <room room_jid='rm_015551123@conference.mediline-jabber01' since='CCYY-MM-DDThh:mm:ss[.sss]TZD' /> * <room room_jid='rm_515156520@conference.mediline-jabber01' since='2014-04-11T09:10:59.303+0000' /> * <room room_jid='pc_845169551@conference.mediline-jabber01' since='1970-01-01T00:00:00Z' /> * ... * </query> * </iq> * * Replied query: * <iq type='result' id='xdfw-1'> * <query xmlns='xmpp:join:msgq'> * <room room_jid='rm_015551123@conference.mediline-jabber01'> * <msg_count>3</msg_count> * </room> * <room room_jid='rm_515156520@conference.mediline-jabber01'> * <msg_count>0</msg_count> * </room> * ... * </query> * </iq> */ if (isValidMsgQueryPacket(packet, read, processed)) { Element child = ((IQ) packet).getChildElement(); if (child != null) { String uri = ((Element) child).getNamespaceURI().toString(); String qualifiedname = ((Element) child).getQualifiedName().toString(); if (uri.equals("xmpp:join:msgq") && qualifiedname.equals("query")) { Log.warn("MSGQ packet: " + packet.toString()); JID from = new JID(((IQ) packet).getElement().attribute("from").getValue()); //Get the fields we are interested in (all the "room" requests) List children = ((IQ) packet).getChildElement().elements("room"); if (!children.isEmpty()) { Iterator fieldElems = children.iterator(); int rescount = 0; // Create reply IQ reply = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy(); reply.setChildElement("query", "xmpp:join:msgq"); Element cur; String qroom; String qdate; while (fieldElems.hasNext()) { cur = (Element) fieldElems.next(); qroom = cur.attribute("room_jid").getValue(); qdate = cur.attribute("since").getValue(); rescount = sujMessageHandler.getArchivedMessageCount(qroom, qdate, from.toBareJID()); // Choo choo, makes the train ((IQ) reply).getChildElement().addElement("room").addAttribute("room_jid", qroom) .addElement("msg_count").addText(Integer.toString(rescount)); if (Log.isDebugEnabled()) { Log.warn("I got the query token! Search for messages in " + qroom + " older than " + qdate + ": " + rescount + " messages "); } } if (Log.isDebugEnabled()) { Log.warn("Sending IQ reply: " + reply.toString()); } // Send packet try { iqRouter.route(reply); } catch (Exception rf) { Log.error("Routing failed for IQ packet: " + reply.toString()); } } else { Log.warn("Empty MsgQueryPacket!"); } } } } /** * Hijack the registration request and parse information related to the JOIN service * This information is sent in the body of the register query. * * Example registration packet: * <iq type="set" id="purple343f3f96" from="mediline-jabber01/68b64d0a"> * <query xmlns="xmpp:iq:register"> * <x xmlns="xmpp:x:data" type="submit"> * <field var="FORM_TYPE"> * <value>xmpp:iq:register</value> * </field> * ... * </x> * </query> * </iq> */ if (isValidRegisterPacket(packet, read, processed)) { String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString(); String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString(); if (uri.equals("xmpp:iq:register") && qualifiedname.equals("query")) { String innerUri = ((IQ) packet).getChildElement().element("x").getNamespaceURI().toString(); String innerQualifiedname = ((IQ) packet).getChildElement().element("x").getQualifiedName() .toString(); String innerType = ((IQ) packet).getChildElement().element("x").attribute("type").getValue() .toString(); if (Log.isDebugEnabled()) { Log.warn("Possible register packet... "); } if (innerUri.equals("xmpp:x:data") && innerQualifiedname.equals("x") && innerType.equals("submit")) { if (Log.isDebugEnabled()) { Log.warn("We got a registration submission!!"); Log.warn("packet:" + packet.toString()); } //Get the field we are interested in, in this example we use the "email" attribute as the token Iterator fieldElems = ((IQ) packet).getChildElement().element("x").elementIterator(); Element cur; while (fieldElems.hasNext()) { cur = (Element) fieldElems.next(); if (("email").equals(cur.attribute("var").getValue())) { Log.warn("I got the token! It's " + cur.getStringValue()); } } try { if (Log.isDebugEnabled()) { Log.warn("Sleeping ..."); } //Thread.sleep(1000); sujMessageHandler.googleReq(); if (Log.isDebugEnabled()) { Log.warn("Slept"); } } catch (Exception ie) { if (Log.isDebugEnabled()) { Log.warn("Problem sleeping: " + ie.toString()); } } } } } /** * Hijack the MUC requests and check if notifications should be sent when: * - user is online but there's ongoing activity on a MUC the user belongs to (live notifications/IQ messages) * - user if offline and there are unread messages (push notifications) * * Example MUC activity packet: * <message content="text" to="gc_930f3e070d7@conference.mediline" type="groupchat" from="test2@mediline/7e3"> * <body>Message</body> * <delay xmlns="urn:xmpp:delay" from="test2@mediline/7e3" stamp="2010-02-12T13:36:22.715Z"/> * </message> */ if (isValidOutOfMUCPacket(packet, read, processed)) { //Log.warn("We got a MUC packet!" + packet.toString()); // This needs to be improved!!! // Right now, I'm only remaking the map if new chat messages from an unknown (new) room appear // A listener for new MUC rooms should be handling this MUCRoom room = rooms.get(new JID(packet.getElement().attribute("to").getValue())); if (room == null) { makeHashByJID(); room = rooms.get(new JID(packet.getElement().attribute("to").getValue())); } if (room != null) { if (room.getMembers() != null) { if (!room.getMembers().isEmpty()) { Iterator room_users = room.getMembers().iterator(); JID user; while (room_users.hasNext()) { user = (JID) room_users.next(); MUCRole role = room.getOccupantByFullJID(user); // User not in chatroom if (role == null) { if (Log.isDebugEnabled()) { Log.warn("User " + user.toString() + " not in chatroom!"); } try { // If user is online still send the message (soft-forward) if (presenceManager.isAvailable(userManager.getUser(user.getNode()))) { if (Log.isDebugEnabled()) { Log.warn("Forwarding message to user " + user.toString()); } Message forwardMsg = (Message) packet.createCopy(); forwardMsg.setFrom(new JID(packet.getElement().attribute("to").getValue())); forwardMsg.setTo(user); forwardMsg.getElement().addAttribute("forwarded", "1"); messageRouter.route(forwardMsg); } else { // If push notifications are enabled if (offlineMucHandlerEnabled) { // Send push notification to user, call you favouritest APN // ... Good luck! :D if (Log.isDebugEnabled()) { Log.warn("Sending push notification to user " + user.toString()); } } } } catch (Exception e) { Log.warn("User " + user.getNode() + " not found: " + e); } } } } } } } /** * Handles the second device check requests. This request is received * without the client being authenticated with the server. * * Received message: * <iq type="get" id="purple3436"> * <query xmlns="xmpp:join:2nd_device"> * <id>username</id> * <password>drowssap</password> * </query> * </iq> * * A successful reply is: * <iq type="result" id="purple343f3f96"> * <query xmlns="xmpp:join:2nd_device"> * <jid>test2@mediline</jid> * </query> * </iq> * * A failed password reply is: * <iq type="error" id="purple343f3f96"> * <error type="cancel"> * <not-allowed xmlns="xmpp:join:2nd_device"/> * </error> * </iq> * * An empty JID and secondID matchs reply is: * <iq type="error" id="purple343f3f96"> * <error type="cancel"> * <not-acceptable xmlns="xmpp:join:2nd_device"/> * </error> * </iq> */ if (isValidCheck2ndDevicePacket(packet, read, processed)) { String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString(); String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString(); String jid = null; if (uri.equals("xmpp:join:2nd_device") && qualifiedname.equals("query")) { //Get the id and password fields String id = ((IQ) packet).getChildElement().element("id").getStringValue(); String password = ((IQ) packet).getChildElement().element("password").getStringValue(); Log.warn("Just got a 2nd device check IQ with username " + id + " and password " + password); Log.warn("Reply: " + packet.toString()); try { jid = sujMessageHandler.getSecondDeviceJID(id, password); } catch (Exception ie) { if (Log.isDebugEnabled()) { Log.warn("Problem on request: " + ie.toString()); } } // Build reply IQ replyPacket = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy(); //replyPacket.setTo((JID)null); if (jid == null) { ((IQ) replyPacket).setType(IQ.Type.error); ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel") .addElement("not-acceptable").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas"); } else if (jid == "invalid username or password") { ((IQ) replyPacket).setType(IQ.Type.error); ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel") .addElement("not-allowed").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas"); } else { ((IQ) replyPacket).setChildElement("query", "xmpp:join:2nd_device"); ((IQ) replyPacket).getChildElement().addElement("jid").addText(jid); } Log.warn("Reply: " + replyPacket.toString()); // Send packet try { //iqRouter.route(replyPacket); session.process(replyPacket); } catch (Exception rf) { Log.error("Routing failed for IQ getting 2nd device packet"); } } } /** * Handles the second device setup requests. * * Received message: * <iq type="set" id="purple3436"> * <query xmlns="xmpp:join:2nd_device"> * <id>username</id> * <password>drowssap</password> * <jid>aa@bbb.com<jid> * </query> * </iq> * * On ok, send: * <iq type="result" id="purple343f3f96"> * <query xmlns="xmpp:join:2nd_device"/> * </iq> * * On error, the reply is: * <iq type="error" id="purple343f3f96"> * <error type="cancel"> * <not-acceptable xmlns="xmpp:join:2nd_device"/> * </error> * </iq> */ if (isValidCreate2ndDevicePacket(packet, read, processed)) { Log.warn("Inside 2nd device SET"); Log.warn("WHO? " + packet.toString()); String uri = ((IQ) packet).getChildElement().getNamespaceURI().toString(); String qualifiedname = ((IQ) packet).getChildElement().getQualifiedName().toString(); if (uri.equals("xmpp:join:2nd_device") && qualifiedname.equals("query") && session.getStatus() == 3) { //Get the id and password fields String id = ((IQ) packet).getChildElement().element("id").getStringValue(); String password = ((IQ) packet).getChildElement().element("password").getStringValue(); String jid = ((IQ) packet).getElement().attribute("from").getValue(); int queryRes = 0; Log.warn("Just got a 2nd device registration IQ with username " + id + " password " + password + " and jid " + jid); try { queryRes = sujMessageHandler.setSecondDeviceJID(id, password, jid); // Build reply IQ replyPacket = ((IQ) packet).createResultIQ(((IQ) packet)).createCopy(); if (queryRes == 0) { ((IQ) replyPacket).setType(IQ.Type.error); ((IQ) replyPacket).getElement().addElement("error").addAttribute("type", "cancel") .addElement("conflict").addNamespace("", "urn:ietf:params:xml:ns:xmpp-stanzas"); } else { ((IQ) replyPacket).setChildElement("query", "xmpp:join:2nd_device"); } Log.warn("Reply: " + replyPacket.toString()); if (replyPacket != null) { iqRouter.route(replyPacket); } else { Log.error("Routing failed for IQ setting 2nd device packet: "); } } catch (Exception ie) { if (Log.isDebugEnabled()) { Log.warn("Problem on request: " + ie.toString()); } } } } }
From source file:net.windward.Acquire.Units.GameMap.java
License:BEER-WARE LICENSE
public static GameMap fromXml(Element elemMap, ArrayList<HotelChain> hotels) { GameMap map = new GameMap(Integer.parseInt(elemMap.attribute("width").getValue()), Integer.parseInt(elemMap.attribute("height").getValue())); int x = 0;/*from w ww.ja v a2 s . com*/ for (Object elem : elemMap.elements("column")) { Element elemColOn = (Element) elem; StringTokenizer tokRows = new StringTokenizer(elemColOn.getStringValue(), ";"); int y = 0; while (tokRows.hasMoreElements()) { String strTile = tokRows.nextToken(); StringTokenizer tokParts = new StringTokenizer(strTile, ":"); int type = Integer.parseInt(tokParts.nextToken()); if (!tokParts.hasMoreElements()) map.tiles[x][y] = new MapTile(type); else { String hotelName = tokParts.nextToken(); HotelChain hotel = null; for (HotelChain h : hotels) if (h.getName().equals(hotelName)) { hotel = h; break; } map.tiles[x][y] = new MapTile(type, hotel); } y++; } x++; } return map; }
From source file:net.windward.Acquire.Units.Player.java
License:BEER-WARE LICENSE
/** * Reads all of the data passed in the XML except the Stock property. */// www. j av a2 s. c o m public static ArrayList<Player> fromXml(Element elemPlayers) { ArrayList<Player> players = new ArrayList<Player>(); for (Object elem : elemPlayers.elements("player")) { Element elemPlyrOn = (Element) elem; Player plyr = new Player(); plyr.cash = Integer.parseInt(elemPlyrOn.attribute("cash").getValue()); plyr.guid = elemPlyrOn.attribute("guid").getValue(); plyr.name = elemPlyrOn.attribute("name").getValue(); plyr.score = Integer.parseInt(elemPlyrOn.attribute("score").getValue()); Element elemTiles = elemPlyrOn.element("tiles"); if (elemTiles != null) { StringTokenizer tokTiles = new StringTokenizer(elemTiles.getStringValue(), ";"); while (tokTiles.hasMoreElements()) { String tileOn = tokTiles.nextToken(); StringTokenizer tokTileOn = new StringTokenizer(tileOn, ":"); int x = Integer.parseInt(tokTileOn.nextToken()); int y = Integer.parseInt(tokTileOn.nextToken()); PlayerTile tile = new PlayerTile(x, y); plyr.tiles.add(tile); } } Element elemPowers = elemPlyrOn.element("powers"); if (elemPowers != null) { StringTokenizer tokPowers = new StringTokenizer(elemPowers.getStringValue(), ";"); while (tokPowers.hasMoreElements()) { String pwrOn = tokPowers.nextToken(); SpecialPowers power = new SpecialPowers(Integer.parseInt(pwrOn)); plyr.powers.add(power); } } // we can't do stock yet - need the chains for their names Element elemScores = elemPlyrOn.element("scoreboard"); if (elemScores != null) { StringTokenizer tokScores = new StringTokenizer(elemScores.getStringValue(), ";"); while (tokScores.hasMoreElements()) plyr.scoreboard.add(Integer.parseInt(tokScores.nextToken())); } players.add(plyr); } return players; }
From source file:net.windward.Acquire.Units.Player.java
License:BEER-WARE LICENSE
private void ReadStockFromXml(Element elemAllPlayers, ArrayList<HotelChain> hotels) { Element elemPlayer = null;//from w w w .j a va2 s . c o m for (Object elem : elemAllPlayers.elements("player")) if (((Element) elem).attribute("guid").getValue().equals(guid)) { elemPlayer = (Element) elem; break; } Element elemStock = elemPlayer.element("stock"); if (elemStock == null) return; StringTokenizer tokStock = new StringTokenizer(elemStock.getStringValue(), ";"); while (tokStock.hasMoreElements()) { String stockOn = tokStock.nextToken().trim(); if (stockOn.length() == 0) continue; StringTokenizer tokParts = new StringTokenizer(stockOn, ":"); String chainName = tokParts.nextToken().trim(); int numShares = Integer.parseInt(tokParts.nextToken()); HotelChain chain = null; for (HotelChain h : hotels) if (h.getName().equals(chainName)) { chain = h; break; } HotelStock hotelStock = new HotelStock(chain, numShares); stock.add(hotelStock); } }
From source file:org.alfresco.web.config.header.HeaderElementReader.java
License:Open Source License
/** * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) *//* w ww. j a v a2 s . co m*/ public ConfigElement parse(Element headerElement) { HeaderConfigElement result = null; if (headerElement == null) { return null; } String name = headerElement.getName(); if (!name.equals(ELEMENT_HEADER)) { throw new ConfigException(this.getClass().getName() + " can only parse " + ELEMENT_HEADER + " elements, the element passed was '" + name + "'"); } result = new HeaderConfigElement(); // Find all the legacy-mode-enabled elements (there should only be one) and perform an AND on all the // elements to determine whether or not we're in legacy mode boolean configuredLegacyMode = true; @SuppressWarnings("unchecked") List<Element> legacyModeElements = headerElement.elements(HeaderItemsElementReader.ELEMENT_LEGACY); for (Element legacyModeElement : legacyModeElements) { configuredLegacyMode = configuredLegacyMode && Boolean.parseBoolean(legacyModeElement.getStringValue()); } // We're in legacy mode if ALL the legacy configuration elements were set to true and there was at least one. result.setLegacyMode(configuredLegacyMode && legacyModeElements.size() > 0); // Set the maximum number of recent items that can be displayed... Element maxRecentSitesEl = headerElement.element(HeaderItemsElementReader.ELEMENT_MAX_RECENT_SITES); if (maxRecentSitesEl != null) { Integer maxRecentSites = null; try { maxRecentSites = Integer.parseInt(maxRecentSitesEl.getStringValue()); } finally { // No action required for NumberFormatException } result.setMaxRecentSites(maxRecentSites); } // Set the maximum number of site pages to display... Element maxDisplayedSitePagesEl = headerElement .element(HeaderItemsElementReader.ELEMENT_MAX_DISPLAYED_SITE_PAGES); if (maxDisplayedSitePagesEl != null) { Integer maxDisplayedSitePages = null; try { maxDisplayedSitePages = Integer.parseInt(maxDisplayedSitePagesEl.getStringValue()); } finally { // No action required for NumberFormatException } result.setMaxDisplayedSitePages(maxDisplayedSitePages); } // Go through each of the <app-items> tags under <header> for (Object obj : headerElement.selectNodes("./app-items")) { Element appItemsElement = (Element) obj; HeaderItemsElementReader appsReader = new HeaderItemsElementReader(); HeaderItemsConfigElement appsCE = (HeaderItemsConfigElement) appsReader.parse(appItemsElement); result.setAppItems(appsCE); } // Go through each of the <user-items> tags under <header> for (Object obj : headerElement.selectNodes("./user-items")) { Element userItemsElement = (Element) obj; HeaderItemsElementReader userReader = new HeaderItemsElementReader(); HeaderItemsConfigElement userCE = (HeaderItemsConfigElement) userReader.parse(userItemsElement); result.setUserItems(userCE); } // Go through each of the <dependencies> tags under <header> for (Object obj : headerElement.selectNodes("./dependencies")) { Element depsElement = (Element) obj; DependenciesElementReader depsReader = new DependenciesElementReader(); DependenciesConfigElement depsCE = (DependenciesConfigElement) depsReader.parse(depsElement); result.setDependencies(depsCE); } return result; }
From source file:org.androidpn.server.console.controller.NotificationController.java
License:Open Source License
/** * connect with pubsub plugin (PuSHPress) and receive feeds and push * @param request// w w w.j av a2s . c om * @param response * @return * @throws Exception * @author xzg */ public ModelAndView pubsub(HttpServletRequest request, HttpServletResponse response) throws Exception { String apiKey = Config.getString("apiKey", ""); System.out.println("NotificationController.pubsub#" + request.getCharacterEncoding()); // UTF-8 String rStr = ServletRequestUtils.getStringParameter(request, "hub.challenge"); if (rStr != null) { System.out.println(rStr); response.setContentType("text/plain"); ServletOutputStream out = response.getOutputStream(); out.print(rStr); out.flush(); } else { // try to print the request string. BufferedReader br = request.getReader(); String s = br.readLine(); StringBuilder sb = new StringBuilder(); while (s != null) { sb.append(s); System.out.println(s); s = br.readLine(); } //create a listener for handling our callbacks /*FeedParserListener listener = new DefaultFeedParserListener() { public void onChannel( FeedParserState state, String title, String link, String description ) throws FeedParserException { System.out.println( "Found a new channel: " + title ); } public void onItem( FeedParserState state, String title, String link, String description, String permalink ) throws FeedParserException { System.out.println( "Found a new published article: " + title+ permalink ); notificationManager.sendMyNotifications("", title, description, link, "video_cievideo"); } }; FeedParser parser = FeedParserFactory.newFeedParser(); parser.parse(listener, request.getInputStream(), ""); */ Document document = org.dom4j.DocumentHelper.parseText(sb.toString()); Element re = document.getRootElement(); List es = re.elements("entry"); for (int i = 0; i < es.size(); i++) { Element currentItem = (Element) es.get(i); Element title = (Element) currentItem.elements("title").get(0); Element link = (Element) currentItem.elements("link").get(0); Element updated = (Element) currentItem.elements("updated").get(0); Element content = (Element) currentItem.elements("content").get(0); Element category = (Element) currentItem.elements("category").get(0); System.out.println(title.getStringValue()); System.out.println(content.getStringValue()); System.out.println(link.attributeValue("href")); System.out.println(category.attributeValue("term")); if (category == null || category.attributeValue("term") == null) return null; if (category.attributeValue("term").equals("")) return null; notificationManager.sendMyNotifications("", title.getStringValue(), "", link.attributeValue("href"), category.attributeValue("term")); } } return null; }
From source file:org.apache.maven.archetype.common.DefaultPomManager.java
License:Apache License
public void addModule(File pom, String artifactId) throws IOException, XmlPullParserException, DocumentException, InvalidPackaging { boolean found = false; StringWriter writer = new StringWriter(); Reader fileReader = null;/*from w w w .j a v a2s .c om*/ try { fileReader = ReaderFactory.newXmlReader(pom); SAXReader reader = new SAXReader(); Document document = reader.read(fileReader); Element project = document.getRootElement(); String packaging = null; Element packagingElement = project.element("packaging"); if (packagingElement != null) { packaging = packagingElement.getStringValue(); } if (!"pom".equals(packaging)) { throw new InvalidPackaging( "Unable to add module to the current project as it is not of packaging type 'pom'"); } Element modules = project.element("modules"); if (modules == null) { modules = project.addText(" ").addElement("modules"); modules.setText("\n "); project.addText("\n"); } // TODO: change to while loop for (@SuppressWarnings("unchecked") Iterator<Element> i = modules.elementIterator("module"); i.hasNext() && !found;) { Element module = i.next(); if (module.getText().equals(artifactId)) { found = true; } } if (!found) { Node lastTextNode = null; for (@SuppressWarnings("unchecked") Iterator<Node> i = modules.nodeIterator(); i.hasNext();) { Node node = i.next(); if (node.getNodeType() == Node.ELEMENT_NODE) { lastTextNode = null; } else if (node.getNodeType() == Node.TEXT_NODE) { lastTextNode = node; } } if (lastTextNode != null) { modules.remove(lastTextNode); } modules.addText("\n "); modules.addElement("module").setText(artifactId); modules.addText("\n "); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.write(document); FileUtils.fileWrite(pom.getAbsolutePath(), writer.toString()); } // end if } finally { IOUtil.close(fileReader); } }
From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java
License:Apache License
static boolean addModuleToParentPom(String artifactId, Reader fileReader, Writer fileWriter) throws DocumentException, IOException, ArchetypeTemplateProcessingException { SAXReader reader = new SAXReader(); Document document = reader.read(fileReader); Element project = document.getRootElement(); String packaging = null;// ww w . java 2 s .c om Element packagingElement = project.element("packaging"); if (packagingElement != null) { packaging = packagingElement.getStringValue(); } if (!"pom".equals(packaging)) { throw new ArchetypeTemplateProcessingException( "Unable to add module to the current project as it is not of packaging type 'pom'"); } Element modules = project.element("modules"); if (modules == null) { modules = project.addText(" ").addElement("modules"); modules.setText("\n "); project.addText("\n"); } boolean found = false; for (Iterator<?> i = modules.elementIterator("module"); i.hasNext() && !found;) { Element module = (Element) i.next(); if (module.getText().equals(artifactId)) { found = true; } } if (!found) { Node lastTextNode = null; for (Iterator<?> i = modules.nodeIterator(); i.hasNext();) { Node node = (Node) i.next(); if (node.getNodeType() == Node.ELEMENT_NODE) { lastTextNode = null; } else if (node.getNodeType() == Node.TEXT_NODE) { lastTextNode = node; } } if (lastTextNode != null) { modules.remove(lastTextNode); } modules.addText("\n "); modules.addElement("module").setText(artifactId); modules.addText("\n "); XMLWriter writer = new XMLWriter(fileWriter); writer.write(document); } return !found; }