List of usage examples for org.dom4j Element add
void add(Namespace namespace);
Namespace
to this element. From source file:cn.buk.api.service.CtripHotelServiceImpl.java
License:LGPL
/** * ??//from w w w . j a v a 2 s. c om * @param cityId ? * @return ?? */ @Override public String searchHotel(int cityId) { if (cityId <= 0) return "ER#CITYID IS " + cityId; //headerAPI? Cache cache = getCache(); String cacheKey = ConfigData.OTA_HotelSearch_Request; net.sf.ehcache.Element cacheElement = cache.get(cacheKey); if (cacheElement != null) { Element headerElement = (Element) cacheElement.getValue(); int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount")); int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1; logger.info("AccessCount=" + headerElement.attributeValue("AccessCount") + ", CurrentCount=" + headerElement.attributeValue("CurrentCount") + ", ResetTime=" + headerElement.attributeValue("ResetTime")); if (currentCount >= accessCount) { try { logger.info("Sleep for one minute."); Thread.sleep(60000); } catch (InterruptedException ex) { logger.warn(Thread.currentThread().getName() + " is interrupted."); return "ER#Thread.sleep is interrupted."; } } } HotelRequestBody request = new HotelRequestBody(); request.createHotelRequestRQ(); request.getHotelRequestRQ().getCriteria().getCriterion().getHotelRef().setHotelCityCode(cityId); String xml; try { JAXBContext jc = JAXBContext.newInstance(HotelRequestBody.class); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); DocumentResult documentResult = new DocumentResult(); m.marshal(request, documentResult); org.dom4j.Document document = documentResult.getDocument(); org.dom4j.Element requestElement = document.getRootElement(); Element ele = requestElement.element("OTA_HotelSearchRQ"); ele.addNamespace("", "http://www.opentravel.org/OTA/2003/05"); org.dom4j.Document doc1 = DocumentHelper.createDocument(); org.dom4j.Element rootElement = createRequestHeaderElement(doc1, ConfigData.OTA_HotelSearch_Request); rootElement.add(requestElement); xml = doc1.asXML(); } catch (JAXBException ex) { logger.error(ex.getMessage()); return "ER"; } if (serviceStopped) return "ER#Service stopped."; String response = execApiRequest(xml, ConfigData.OTA_HotelSearch_Url, "requestXML"); //? SAXReader reader = new SAXReader(); Document document;// ?XML try { document = reader.read(new StringReader(response)); if (serviceStopped) return "ER#Service stopped."; response = processHotelSearchResponse(document); } catch (Exception ex) { logger.error(ex.getMessage()); return "ER"; } return response; }
From source file:cn.buk.api.service.CtripHotelServiceImpl.java
License:LGPL
@Override public synchronized String searchHotelDetail(List<String> hotelCodes, boolean returnXml) { if (hotelCodes == null || hotelCodes.size() == 0) return "ER#hotelcodes is null"; //headerAPI?// w w w . ja va2 s . com net.sf.ehcache.Element cacheElement = getCache().get(ConfigData.OTA_HotelDetail_Request); if (cacheElement != null) { Element headerElement = (Element) cacheElement.getValue(); int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount")); int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1; logger.info(ConfigData.OTA_HotelDetail_Request + " AccessCount=" + headerElement.attributeValue("AccessCount") + ", CurrentCount=" + headerElement.attributeValue("CurrentCount") + ", ResetTime=" + headerElement.attributeValue("ResetTime")); if (currentCount >= accessCount) { try { logger.info("Sleep for one minute."); Thread.sleep(60000); } catch (InterruptedException ex) { logger.warn(Thread.currentThread().getName() + " is interrupted."); return "ER#SearchHotelDetail thread.sleep is interrupted."; } } } if (this.serviceStopped) return "ER#Service stopped."; HotelRequestBody request = new HotelRequestBody(); request.createHotelDetailRequest(); for (String hotelCode : hotelCodes) { if (this.serviceStopped) return "ER#Service stopped."; HotelDescriptiveInfo hotelDescriptiveInfo = new HotelDescriptiveInfo(); hotelDescriptiveInfo.setHotelCode(hotelCode); cn.buk.hotel.entity.HotelInfo hotelInfo = hotelDao.getHotelDetailInfoByHotelCode(hotelCode); if (hotelInfo != null) { //if (hotelInfo.getGuestRooms().size() == 0) { hotelDescriptiveInfo.setHotelInfoFacilityInfo(new HotelInfoFacilityInfo()); hotelDescriptiveInfo.getHotelInfoFacilityInfo().setSendGuestRooms(true); //} if (hotelInfo.getRefPoints().size() == 0) { hotelDescriptiveInfo.setHotelInfoAreaInfo(new HotelInfoAreaInfo()); hotelDescriptiveInfo.getHotelInfoAreaInfo().setSendAttractions(true); hotelDescriptiveInfo.getHotelInfoAreaInfo().setSendRecreations(true); } if (hotelInfo.getMedias().size() == 0) { hotelDescriptiveInfo.setHotelInfoMultimedia(new HotelInfoMultimedia()); hotelDescriptiveInfo.getHotelInfoMultimedia().setSendData(true); } } request.getHotelDetailRequest().getHotelDescriptiveInfos().add(hotelDescriptiveInfo); } String requestXml; try { JAXBContext jc = JAXBContext.newInstance(HotelRequestBody.class); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); DocumentResult documentResult = new DocumentResult(); m.marshal(request, documentResult); org.dom4j.Document document = documentResult.getDocument(); org.dom4j.Element requestElement = document.getRootElement(); Element ele = requestElement.element("OTA_HotelDescriptiveInfoRQ"); ele.addNamespace("", "http://www.opentravel.org/OTA/2003/05"); org.dom4j.Document doc1 = DocumentHelper.createDocument(); if (this.serviceStopped) return "ER#Service stopped."; org.dom4j.Element rootElement = createRequestHeaderElement(doc1, ConfigData.OTA_HotelDetail_Request); rootElement.add(requestElement); requestXml = doc1.asXML(); } catch (JAXBException e) { e.printStackTrace(); return "ER#OTA_exception"; } Date date0 = DateUtil.getCurDateTime(); logger.debug(ConfigData.OTA_HotelDetail_Request + ": begin"); logger.debug(requestXml); if (this.serviceStopped) return "ER#Service stopped."; String response = execApiRequest(requestXml, ConfigData.OTA_HotelDetail_Url, "requestXML"); logger.debug(response); int apiElapsedTime = DateUtil.getPastTime(date0); logger.debug(ConfigData.OTA_HotelDetail_Request + ": end, " + apiElapsedTime + "ms"); if (returnXml) return response; //? String rs; SAXReader reader = new SAXReader(); Document document;// ?XML try { document = reader.read(new StringReader(response)); Element headerElement = document.getRootElement().element("Header"); //header? getCache().put(new net.sf.ehcache.Element(ConfigData.OTA_HotelDetail_Request, headerElement)); if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) { logger.error(requestXml); logger.error(document.asXML()); return "ER#ResultCode is not Success."; } DocumentDto documentDto = new DocumentDto(); documentDto.setDocument(document); if (hotelDetailQueue.size() == MAX_HOTEL_DETAIL_QUEUE) { logger.warn("hotelDetailQueue is full, thread will be blocked here."); } hotelDetailQueue.put(documentDto); hotelDetailDaoExecutor.execute(new HotelDetailDaoThread()); rs = "OK#save to the queue."; } catch (InterruptedException ex) { return "ER#Interrupt occured."; } catch (Exception ex) { logger.error(ex.getMessage()); return "ER#searchHotelDetail"; } return rs; }
From source file:cn.buk.api.service.CtripHotelServiceImpl.java
License:LGPL
private String createXml4HotelRequestBody(HotelRequestBody request, String requestType) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(HotelRequestBody.class); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); DocumentResult documentResult = new DocumentResult(); m.marshal(request, documentResult);//from w ww.j ava 2 s . co m org.dom4j.Document document = documentResult.getDocument(); org.dom4j.Element requestElement = document.getRootElement(); org.dom4j.Document doc1 = DocumentHelper.createDocument(); org.dom4j.Element rootElement = createRequestHeaderElement(doc1, requestType); rootElement.add(requestElement); return doc1.asXML(); }
From source file:com.adspore.splat.xep0030.DiscoInfoHandler.java
License:Open Source License
public IQ handleDiscoInfoIQ(IQ packet) { /*/* w ww . ja va 2s . c o m*/ * Create a copy of the sent pack that will be used as the reply we need to add * the requested info (query) to the reply as well as the 'error' element as described * in the XEP-30 Service Discovery docs, section 3.1 / example 1,2. * * We'll stuff the 'query' element into the reply, then add identity and feature elements * to that if they exist. */ Element queryElement = packet.getChildElement().createCopy(); IQ reply = IQ.createResultIQ(packet); reply.setChildElement(queryElement); /* * Look for a DiscoInfoProvider associated with the requested entity. * We consider the host of the recipient JID of the packet as the entity. It's the * DiscoInfoProvider responsibility to provide information about the JID's name together * with any possible requested node. * * As part of the refactoring, I moved this to a MultiMap implementation because there * may be multiple DiscoInfoProviders that can speak to a particular node, as a node * may host both PubSub entries as well as other services. * * One of the things that makes this so problematic, is the confusion between the JID's * concept of 'Node' and the Entity's concept of 'Node'. When referring to PubSub, the * node is really placed in a JID's 'resource', and the JID uses the 'Node' to identify * the User's name. See example: * * nodeId@domainFoo.domainBar/resource * * When using the JID+Node approach, this goes very wrong.... * */ final Element iq = packet.getChildElement(); final String node = queryElement.attributeValue("node"); final JID targetJID = (null != node) ? JIDUtils.setNodeIDAsResource(packet.getTo(), node) : packet.getTo(); final JID senderJID = packet.getFrom(); /* * Flags controlling the addition of 'standard' features/identities applicable to the * entire result set. Added if ANY of the infoProviders say they do. */ boolean hasDiscoInfoFeature = false; boolean hasDiscoItemsFeature = false; boolean hasResultSetManagementFeature = false; /* * Lookup all possible DiscoInfoProviders that service the target. Base this on the * 'domain' field of the JID, patch up with username later if required. */ Collection<DiscoInfoProvider> infoProviders = getProviders(targetJID.toBareJID()); if (!infoProviders.isEmpty()) { /* * Begin looping through the providers, checking with each to provide them with the * opportunity to add information if they have any to add. */ Iterator<DiscoInfoProvider> itor = infoProviders.iterator(); while (itor.hasNext()) { DiscoInfoProvider possibleProvider = itor.next(); if (possibleProvider.hasInfo(targetJID, senderJID)) { // Add the info that this provider says it has... Iterator<Element> identities = possibleProvider.getIdentities(targetJID, senderJID); while (identities.hasNext()) { queryElement.add(identities.next().createCopy()); } // Add to the reply all the features provided by the DiscoInfoProvider Iterator<String> features = possibleProvider.getFeatures(targetJID, senderJID); while (features.hasNext()) { // Loop through all of the features that this provider has.... final String feature = features.next(); queryElement.addElement("feature").addAttribute("var", feature); if (feature.equals(AbstractComponent.NAMESPACE_DISCO_INFO)) { hasDiscoInfoFeature = true; } else if (feature.equals(AbstractComponent.NAMESPACE_DISCO_ITEMS)) { hasDiscoItemsFeature = true; } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) { hasResultSetManagementFeature = true; } } } if (hasDiscoItemsFeature && !hasResultSetManagementFeature) { // IQDiscoItemsHandler provides result set management // support. queryElement.addElement("feature").addAttribute("var", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT); } // Add to the reply the extended info (XDataForm) provided by the DiscoInfoProvider DataForm dataForm = possibleProvider.getExtendedInfo(targetJID, packet.getFrom()); if (dataForm != null) { queryElement.add(dataForm.getElement()); } } } else { // If we didn't find a DiscoInfoProvider then answer a not found error reply.setError(PacketError.Condition.item_not_found); } return reply; }
From source file:com.adspore.splat.xep0030.DiscoItemsHandler.java
License:Open Source License
public IQ handleDiscoItemsIQ(IQ packet) { /*/*from www . jav a2 s . c om*/ * We'll stuff the 'query' element into the reply, then add identity and feature elements * to that if they exist. */ Element queryElement = packet.getChildElement().createCopy(); IQ reply = IQ.createResultIQ(packet); reply.setChildElement(queryElement); /* * Look for a DiscoInfoProvider associated with the requested entity, there may be more than one. * We consider the host of the recipient JID of the packet as the entity. It's the * DiscoInfoProvider responsibility to provide information about the JID's name together * with any possible requested node. * * As part of the refactoring, I moved this to a MultiMap implementation because there * may be multiple DiscoInfoProviders that can speak regarding a particular node, as a node * may host multiple identities. For instance, a JID+Node may support PubSub as well * as ping and time. Every node supports info and item. * * One of the things that makes this so problematic, is the confusion between the JID's * concept of 'Node' and the Entity's concept of 'Node'. When referring to PubSub, the * node is really placed in a JID's 'resource', and the JID uses the 'Node' to identify * the User's name. See example: * * nodeId@domainFoo.domainBar/resource * * When using the JID+Node approach, this goes very wrong.... * */ final Element iq = packet.getChildElement(); // Assumption: it's a 'query' object... final String node = queryElement.attributeValue("node"); final JID targetJID = (null != node) ? JIDUtils.setNodeIDAsResource(packet.getTo(), node) : packet.getTo(); final JID senderJID = packet.getFrom(); /* * Lookup all possible DiscoInfoProviders that service the target. Base this on the * 'domain' field of the JID, patch up with username later if required. */ Collection<DiscoItemsProvider> itemProviders = getProviders(targetJID.toBareJID()); if (!itemProviders.isEmpty()) { /* * Begin looping through the providers, checking with each to provide them with the * opportunity to add information on their behalf if they have any to add. */ Iterator<DiscoItemsProvider> providerItor = itemProviders.iterator(); while (providerItor.hasNext()) { // Add the items that this provider says it has... DiscoItemsProvider provider = providerItor.next(); if (true == provider.hasItems(targetJID, senderJID)) { Iterator<DiscoItem> itemItor = provider.getItems(targetJID, senderJID); while (itemItor.hasNext()) { queryElement.add(itemItor.next().getElement().createCopy()); } } } } else { // If we didn't find a DiscoItemsProvider then answer a not found error reply.setError(PacketError.Condition.item_not_found); } return reply; }
From source file:com.adspore.splat.xep0060.CollectionNode.java
License:Open Source License
/** * Notification that a new node was created and added to this node. Trigger notifications * to node subscribers whose subscription type is {@link NodeSubscription.Type#nodes} and * have the proper depth.// w ww. j a v a 2 s. c o m * * @param child the newly created node that was added to this node. */ void childNodeAdded(Node child) { // Build packet to broadcast to subscribers Message message = new Message(); Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event"); Element item = event.addElement("items").addElement("item"); item.addAttribute("id", child.getNodeID()); if (mDeliverPayloads) { item.add(child.getMetadataForm().getElement()); } // Broadcast event notification to subscribers broadcastCollectionNodeEvent(child, message); }
From source file:com.adspore.splat.xep0060.LeafNode.java
License:Open Source License
/** * Sends an IQ result with the list of items published to the node. Item ID and payload * may be included in the result based on the node configuration. * * @param originalRequest the IQ packet sent by a subscriber (or anyone) to get the node items. * @param publishedItems the list of published items to send to the subscriber. * @param forceToIncludePayload true if the item payload should be include if one exists. When * false the decision is up to the node. *//*w ww . j ava 2s . c o m*/ void sendPublishedItems(IQ originalRequest, List<PublishedItem> publishedItems, boolean forceToIncludePayload) { IQ result = IQ.createResultIQ(originalRequest); Element pubsubElem = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub"); Element items = pubsubElem.addElement("items"); items.addAttribute("node", getNodeID()); for (PublishedItem publishedItem : publishedItems) { Element item = items.addElement("item"); if (isItemRequired()) { item.addAttribute("id", publishedItem.getID()); } if ((forceToIncludePayload || isPayloadDelivered()) && publishedItem.getPayload() != null) { item.add(publishedItem.getPayload().createCopy()); } } // Send the result mService.send(result); }
From source file:com.adspore.splat.xep0060.Node.java
License:Open Source License
/** * The node configuration has changed. If this is the first time the node is configured * after it was created (i.e. is not yet persistent) then do nothing. Otherwise, send * a notification to the node subscribers informing that the configuration has changed. *///from w w w . ja v a 2 s.c o m private void nodeConfigurationChanged() { if (!isNotifiedOfConfigChanges() || !savedToDB) { // Do nothing if node was just created and configure or if notification // of config changes is disabled return; } // Build packet to broadcast to subscribers Message message = new Message(); Element event = message.addChildElement("event", "http://jabber.org/protocol/pubsub#event"); Element config = event.addElement("configuration"); config.addAttribute("node", mNodeID); if (mDeliverPayloads) { config.add(getConfigurationChangeForm().getElement()); } // Send notification that the node configuration has changed broadcastNodeEvent(message, false); }
From source file:com.adspore.splat.xep0060.NodeAffiliate.java
License:Open Source License
/** * Sends an event notification for the published items to the affiliate. The event * notification may contain zero, one or many published items based on the items * included in the original publication. If the affiliate has many subscriptions and * many items were published then the affiliate will get a notification for each set * of items that affected the same subscriptions. * * @param notification the message to sent to the subscribers. The message will be completed * with the items to include in each notification. * @param event the event Element included in the notification message. Passed as an * optimization to avoid future look ups. * @param leafNode the leaf node where the items where published. * @param publishedItems the list of items that were published. Could be an empty list. *//*from ww w . j a va2s .c om*/ void sendPublishedNotifications(Message notification, Element event, LeafNode leafNode, List<PublishedItem> publishedItems) { if (!publishedItems.isEmpty()) { Map<List<NodeSubscription>, List<PublishedItem>> itemsBySubs = getItemsBySubscriptions(leafNode, publishedItems); // Send one notification for published items that affect the same subscriptions for (List<NodeSubscription> nodeSubscriptions : itemsBySubs.keySet()) { // Add items information Element items = event.addElement("items"); items.addAttribute("node", getNode().getNodeID()); for (PublishedItem publishedItem : itemsBySubs.get(nodeSubscriptions)) { // FIXME: This was added for compatibility with PEP supporting clients. // Alternate solution needed when XEP-0163 version > 1.0 is released. // // If the node ID looks like a JID, replace it with the published item's node ID. if (getNode().getNodeID().indexOf("@") >= 0) { items.addAttribute("node", publishedItem.getNodeID()); } // Add item information to the event notification Element item = items.addElement("item"); if (leafNode.isItemRequired()) { item.addAttribute("id", publishedItem.getID()); } if (leafNode.isPayloadDelivered()) { item.add(publishedItem.getPayload().createCopy()); } // Add leaf leafNode information if affiliated leafNode and node // where the item was published are different if (leafNode != getNode()) { item.addAttribute("node", leafNode.getNodeID()); } } // Send the event notification sendEventNotification(notification, nodeSubscriptions); // Remove the added items information event.remove(items); } } else { // Filter affiliate subscriptions and only use approved and configured ones List<NodeSubscription> affectedSubscriptions = new ArrayList<NodeSubscription>(); for (NodeSubscription subscription : getSubscriptions()) { if (subscription.canSendPublicationEvent(leafNode, null)) { affectedSubscriptions.add(subscription); } } // Add item information to the event notification Element items = event.addElement("items"); items.addAttribute("node", leafNode.getNodeID()); // Send the event notification sendEventNotification(notification, affectedSubscriptions); // Remove the added items information event.remove(items); } }
From source file:com.adspore.splat.xep0060.NodeSubscription.java
License:Open Source License
/** * Sends an event notification for the last published item to the subscriber. If * the subscription has not yet been authorized or is pending to be configured then * no notification is going to be sent.<p> * * Depending on the subscription configuration the event notification may or may not have * a payload, may not be sent if a keyword (i.e. filter) was defined and it was not matched. * * @param publishedItem the last item that was published to the node. *//*from w w w . j a v a2 s.com*/ void sendLastPublishedItem(PublishedItem publishedItem) { // Check if the published item can be sent to the subscriber if (!canSendPublicationEvent(publishedItem.getNode(), publishedItem)) { return; } // Send event notification to the subscriber Message notification = new Message(); Element event = notification.getElement().addElement("event", "http://jabber.org/protocol/pubsub#event"); Element items = event.addElement("items"); items.addAttribute("node", node.getNodeID()); Element item = items.addElement("item"); if (((LeafNode) node).isItemRequired()) { item.addAttribute("id", publishedItem.getID()); } if (node.isPayloadDelivered() && publishedItem.getPayload() != null) { item.add(publishedItem.getPayload().createCopy()); } // Add a message body (if required) if (isIncludingBody()) { notification.setBody(LocaleUtils.getLocalizedString("pubsub.notification.message.body")); } // Include date when published item was created notification.getElement().addElement("delay", "urn:xmpp:delay").addAttribute("stamp", XMPPDateTimeFormat.format(publishedItem.getCreationDate())); // Send the event notification to the subscriber node.getService().sendNotification(node, notification, jid); }