Java Code Examples for org.dom4j.Element#add()

The following examples show how to use org.dom4j.Element#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserCreated.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
protected void addStageInformation(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.form);
    form.setTitle("Dispatching a user created event.");
    form.addInstruction("Fill out this form to dispatch a user created event.");

    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");

    field = form.addField();
    field.setType(FormField.Type.text_single);
    field.setLabel("The username of the user that was created");
    field.setVariable("username");
    field.setRequired(true);

    // Add the form to the command
    command.add(form.getElement());
}
 
Example 2
Source File: BpmnXMLUtil.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * 处理流程容器节点
 * 
 * @param parentElement
 *            父节点
 * @param flowElements
 *            流程节点
 */
public static void createFlowElement(Element parentElement, List<FlowElement> flowElements) {
	if (null != flowElements) {
		FlowElement flowElement = null;
		BaseElementXMLConverter converter = null;
		Element childElem = null;
		for (Iterator<FlowElement> iterator = flowElements.iterator(); iterator.hasNext();) {
			flowElement = iterator.next();
			converter = BpmnXMLConverter.getConverter(flowElement.getClass());
			if (null != converter) {
				childElem = converter.cretateXMLElement();
				if (null != childElem) {
					converter.convertModelToXML(childElem, flowElement);
					parentElement.add(childElem);
				}
			}
		}
	}
}
 
Example 3
Source File: GetUsersPresence.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
protected void addStageInformation(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.form);
    form.setTitle("Requesting Presence of Active Users");
    form.addInstruction("Fill out this form to request the active users presence of this service.");

    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");

    field = form.addField();
    field.setType(FormField.Type.list_single);
    field.setLabel("Maximum number of items to return");
    field.setVariable("max_items");
    field.addOption("25", "25");
    field.addOption("50", "50");
    field.addOption("75", "75");
    field.addOption("100", "100");
    field.addOption("150", "150");
    field.addOption("200", "200");
    field.addOption("None", "none");

    // Add the form to the command
    command.add(form.getElement());
}
 
Example 4
Source File: SequenceFlowXMLConverter.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
@Override
public void convertModelToXML(Element element, BaseElement baseElement) {
	SequenceFlow sequenceFlow = (SequenceFlow) baseElement;
	element.addAttribute(BpmnXMLConstants.ATTRIBUTE_SOURCEREF, sequenceFlow.getSourceRefId());
	element.addAttribute(BpmnXMLConstants.ATTRIBUTE_TARGETREF, sequenceFlow.getTargetRefId());
	if (null != sequenceFlow.getFlowCondition()) {
		String condition = sequenceFlow.getFlowCondition();
		Element childElem = element.addElement(BpmnXMLConstants.BPMN2_PREFIX + ':'
		        + BpmnXMLConstants.ELEMENT_CONDITIONEXPRESSION);
		childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.BPMN2_PREFIX
		        + ':' + BpmnXMLConstants.TYPE_FORMALEXPRESSION);
		childElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_ID, UniqueIDUtil.getInstance().generateElementID(BpmnXMLConstants.TYPE_FORMALEXPRESSION));
		childElem.addAttribute(BpmnXMLConstants.FOXBPM_PREFIX + ':' + BpmnXMLConstants.ATTRIBUTE_NAME, BpmnXMLUtil.interceptStr(condition));
		childElem.add(new DOMCDATA(condition));
	}
	super.convertModelToXML(element, baseElement);
}
 
Example 5
Source File: ChangeUserPassword.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
protected void addStageInformation(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.form);
    form.setTitle("Changing a User Password");
    form.addInstruction("Fill out this form to change a user\u2019s password.");

    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");

    field = form.addField();
    field.setType(FormField.Type.jid_single);
    field.setLabel("The Jabber ID for this account");
    field.setVariable("accountjid");
    field.setRequired(true);

    field = form.addField();
    field.setType(FormField.Type.text_private);
    field.setLabel("The password for this account");
    field.setVariable("password");
    field.setRequired(true);

    // Add the form to the command
    command.add(form.getElement());
}
 
Example 6
Source File: Node.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
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", nodeID);

    if (deliverPayloads) {
        config.add(getConfigurationChangeForm().getElement());
    }
    // Send notification that the node configuration has changed
    broadcastNodeEvent(message, false);

    // And also to the subscribers of parent nodes with proper subscription depth
    final CollectionNode parent = getParent();
    if (parent != null){
        parent.childNodeModified(this, message);
    }
}
 
Example 7
Source File: LeafNode.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
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", nodeID);
    
    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
    getService().send(result);
}
 
Example 8
Source File: ProcessExport.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
private static void createStarterElement(Element parentElement, List<PotentialStarter> potentialStarters) {
	if (null != potentialStarters) {
		PotentialStarter potentialStarter = null;
		Element potentialStarterEle = null;
		Element childElem = null;
		String id = null;
		for (Iterator<PotentialStarter> iterator = potentialStarters.iterator(); iterator.hasNext();) {
			potentialStarter = iterator.next();
			potentialStarterEle = parentElement.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
			        + BpmnXMLConstants.ELEMENT_POTENTIAL_STARTER);
			potentialStarterEle.addAttribute(BpmnXMLConstants.ATTRIBUTE_RESOURCETYPE, potentialStarter.getResourceType());
			potentialStarterEle.addAttribute(BpmnXMLConstants.ATTRIBUTE_DESCRIPTION, potentialStarter.getDocumentation());
			
			childElem = potentialStarterEle.addElement(BpmnXMLConstants.FOXBPM_PREFIX + ':'
			        + BpmnXMLConstants.ELEMENT_EXPRESSION);
			childElem.addAttribute(BpmnXMLConstants.XSI_PREFIX + ':' + BpmnXMLConstants.TYPE, BpmnXMLConstants.FOXBPM_PREFIX
			        + ':' + BpmnXMLConstants.TYPE_EXPRESSION);
			id = UniqueIDUtil.getInstance().generateElementID(null);
			childElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_ID, BpmnXMLConstants.ELEMENT_EXPRESSION + '_' + id);
			childElem.addAttribute(BpmnXMLConstants.ATTRIBUTE_NAME, id);
			childElem.add(new DOMCDATA(potentialStarter.getExpression()));
		}
	}
	
}
 
Example 9
Source File: GetNumberActiveUsers.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.result);

    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");

    field = form.addField();
    field.setLabel(getLabel());
    field.setVariable("activeusersnum");
    // Make sure that we are only counting based on bareJIDs and not fullJIDs
    Collection<ClientSession> sessions = SessionManager.getInstance().getSessions();
    Set<String> users = new HashSet<>(sessions.size());
    for (ClientSession session : sessions) {
        if (session.getPresence().isAvailable()) {
            users.add(session.getAddress().toBareJID());
        }
    }
    field.addValue(users.size());

    command.add(form.getElement());
}
 
Example 10
Source File: ConversionUtil.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
public static List<Document> generateMondrianDocsFromSSASSchema( final InputStream input )
  throws DocumentException, IOException, AggDesignerException {

  Document ssasDocument = parseAssl( input );

  // issue: if we have multi-line text, there is a problem with identing names / etc
  // solution: clean up the dom before traversal
  List allElements = ssasDocument.selectNodes( "//*" );
  for ( int i = 0; i < allElements.size(); i++ ) {
    Element element = (Element) allElements.get( i );
    element.setText( element.getText().replaceAll( "[\\s]+", " " ).trim() );
  }

  List ssasDatabases = ssasDocument.selectNodes( "//assl:Database" );
  List<Document> mondrianDocs = new ArrayList<Document>( ssasDatabases.size() );
  for ( int i = 0; i < ssasDatabases.size(); i++ ) {
    Document mondrianDoc = DocumentFactory.getInstance().createDocument();
    Element mondrianSchema = DocumentFactory.getInstance().createElement( "Schema" );
    mondrianDoc.add( mondrianSchema );
    Element ssasDatabase = (Element) ssasDatabases.get( i );
    mondrianSchema.add( DocumentFactory.getInstance()
      .createAttribute( mondrianSchema, "name", getXPathNodeText( ssasDatabase, "assl:Name" ) ) );
    populateCubes( mondrianSchema, ssasDatabase );

    mondrianDocs.add( mondrianDoc );
  }

  return mondrianDocs;
}
 
Example 11
Source File: ProcessExport.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
private static void createLaneSetElement(Element processEle, Process process) {
	List<LaneSet> laneSets = process.getLaneSets();
	if (laneSets != null) {
		for (LaneSet lanset : laneSets) {
			LaneSetXmlConverter laneSetXmlConverter = new LaneSetXmlConverter();
			Element elementLaneSet = laneSetXmlConverter.cretateXMLElement();
			laneSetXmlConverter.convertModelToXML(elementLaneSet, lanset);
			processEle.add(elementLaneSet);
		}
	}
}
 
Example 12
Source File: XmppPubSubControllerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private XmppSubscribe buildXmppSubscribe() {
    IQ iq = new IQ(IQ.Type.set);
    iq.setTo(toJid);
    iq.setFrom(fromJid);
    Element element = new DefaultElement(pubSub, Namespace.get(XmppPubSubConstants.PUBSUB_NAMESPACE));
    Element childElement = new DefaultElement(subscribe);
    childElement.addAttribute(node, nodeAttribute);
    element.add(childElement);
    iq.setChildElement(element);
    XmppSubscribe xmppSubscribe = new XmppSubscribe(iq);
    return xmppSubscribe;
}
 
Example 13
Source File: DefaultXmlCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the xml string from YDT.
 *
 * @param ydtBuilder YDT builder
 * @return the xml string from YDT
 */
private String buildXmlForYdt(YdtBuilder ydtBuilder) {

    YdtExtendedBuilder extBuilder = (YdtExtendedBuilder) ydtBuilder;
    YdtExtendedContext rootNode = extBuilder.getRootNode();

    if (rootNode == null) {
        throw new YchException(E_YDT_ROOT_NODE);
    }

    // Creating the root element for xml.
    Element rootElement =
            DocumentHelper.createDocument().addElement(rootNode.getName());

    // Adding the name space if exist for root name.
    if (rootNode.getNamespace() != null) {
        rootElement.add(Namespace.get(rootNode.getNamespace()));
    }

    if ("config".equals(rootElement.getName())) {
        rootElement.add(new Namespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0"));
    }

    // Adding the attribute if exist
    Map<String, String> tagAttrMap = extBuilder.getRootTagAttributeMap();
    if (tagAttrMap != null && !tagAttrMap.isEmpty()) {
        for (Map.Entry<String, String> attr : tagAttrMap.entrySet()) {
            rootElement.addAttribute(attr.getKey(), attr.getValue());
        }
    }

    XmlCodecYdtListener listener = new XmlCodecYdtListener(XML, rootNode);
    listener.getElementStack().push(rootElement);

    // Walk through YDT and build the xml.
    YdtExtendedWalker extWalker = new DefaultYdtWalker();
    extWalker.walk(listener, rootNode);

    return rootElement.asXML();
}
 
Example 14
Source File: ClsDupJarPairRisk.java    From Decca with MIT License 5 votes vote down vote up
public Element getConflictElement() {
	int riskLevel = getRiskLevel();	
	Element conflictEle = new DefaultElement("conflict");
	conflictEle.addAttribute("jar-1", jarPair.getJar1().toString());
	conflictEle.addAttribute("jar-2", jarPair.getJar2().toString());
	conflictEle.addAttribute("riskLevel", "" + riskLevel);
	conflictEle.add(jarPair.getJar1().getClsConflictEle(1));
	conflictEle.add(jarPair.getJar2().getClsConflictEle(2));
	Element risksEle = conflictEle.addElement("RiskMethods");
	risksEle.addAttribute("tip", "methods would be referenced but not be loaded");
	if (riskLevel == -1) {
		return null;
	}
	int cnt = 0;
	for (String rchedMthd : getPrintMthds()) {
		if (cnt == 10) {
			break;
		}
		if (!jarPair.getJar1().containsMthd(rchedMthd) || !jarPair.getJar2().containsMthd(rchedMthd)) {
			Element riskEle = risksEle.addElement("RiskMthd");
			riskEle.addText(rchedMthd.replace('<', ' ').replace('>', ' '));
			cnt++;
		}
	}

	return conflictEle;
}
 
Example 15
Source File: IQPrivateHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ replyPacket = IQ.createResultIQ(packet);

    Element child = packet.getChildElement();
    Element dataElement = child.elementIterator().next();

    if ( !XMPPServer.getInstance().isLocal( packet.getFrom()) || !UserManager.getInstance().isRegisteredUser( packet.getFrom()) ) {
        replyPacket.setChildElement(packet.getChildElement().createCopy());
        replyPacket.setError(PacketError.Condition.service_unavailable);
        replyPacket.getError().setText( "Service available only to locally registered users." );
        return replyPacket;
    }

    if (dataElement != null) {
        if (IQ.Type.get.equals(packet.getType())) {
            Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
            dataStored.setParent(null);

            child.remove(dataElement);
            child.setParent(null);
            replyPacket.setChildElement(child);
            child.add(dataStored);
        }
        else {
            if (privateStorage.isEnabled()) {
                privateStorage.add(packet.getFrom().getNode(), dataElement);
            } else {
                replyPacket.setChildElement(packet.getChildElement().createCopy());
                replyPacket.setError(PacketError.Condition.service_unavailable);
            }
        }
    }
    else {
        replyPacket.setChildElement("query", "jabber:iq:private");
    }
    return replyPacket;
}
 
Example 16
Source File: PrivateStorage.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Stores private data. If the name and namespace of the element matches another
 * stored private data XML document, then replace it with the new one.
 *
 * @param data the data to store (XML element)
 * @param username the username of the account where private data is being stored
 */
public void add(String username, Element data) {
    if (!enabled)
    {
        return;
    }

    final JID owner = XMPPServer.getInstance().createJID( username, null );
    final PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
    PEPService pepService = serviceMgr.getPEPService( owner );
    if ( pepService == null )
    {
        pepService = serviceMgr.create( owner );
    }

    Node node = pepService.getNode( data.getNamespaceURI() );
    if ( node == null )
    {
        PubSubEngine.CreateNodeResponse response = PubSubEngine.createNodeHelper( pepService, owner, pepService.getDefaultNodeConfiguration( true ).getConfigurationForm().getElement(), data.getNamespaceURI(), PRIVATE_DATA_PUBLISHING_OPTIONS );
        node = response.newNode;

        if ( node == null )
        {
            Log.error( "Unable to create new PEP node, to be used to store private data. Error condition: {}", response.creationStatus.toXMPP() );
            return;
        }
    }

    if (!(node instanceof LeafNode))
    {
        Log.error( "Unable to store private data into a PEP node. The node that is available is not a leaf node." );
        return;
    }

    data.detach();
    final Element item = DocumentHelper.createElement( "item" );
    item.addAttribute( "id", "current" );
    item.add( data );

    ((LeafNode) node).publishItems( owner, Collections.singletonList( item ) );
}
 
Example 17
Source File: PacketCopier.java    From Openfire with Apache License 2.0 4 votes vote down vote up
private void processPackets() {
    List<InterceptedPacket> packets = new ArrayList<>(packetQueue.size());
    packetQueue.drainTo(packets);
    for (InterceptedPacket interceptedPacket : packets) {
        for (Map.Entry<String, Subscription> entry : subscribers.entrySet()) {
            boolean notify = false;
            String componentJID = entry.getKey();
            Subscription subscription = entry.getValue();

            if (subscription.isIncoming() == interceptedPacket.isIncoming() &&
                    subscription.isProcessed() == interceptedPacket.isProcessed()) {
                Class packetClass = interceptedPacket.getPacketClass();
                if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                    notify = true;
                }
                else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                    notify = true;
                }
                else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                    notify = true;
                }
            }

            if (notify) {
                try {
                    Message message = new Message();
                    message.setFrom(serverName);
                    message.setTo(componentJID);
                    Element childElement = message.addChildElement("copy",
                            "http://jabber.org/protocol/packet#event");
                    childElement.addAttribute("incoming", subscription.isIncoming() ? "true" : "false");
                    childElement.addAttribute("processed", subscription.isProcessed() ? "true" : "false");
                    childElement.addAttribute("date", XMPPDateTimeFormat.format(interceptedPacket.getCreationDate()));
                    childElement.add(interceptedPacket.getElement().createCopy());
                    // Send message notification to subscribed component
                    routingTable.routePacket(message.getTo(), message, true);
                }
                catch (Exception e) {
                    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                }
            }
        }
    }
}
 
Example 18
Source File: ConversionUtil.java    From pentaho-aggdesigner with GNU General Public License v2.0 4 votes vote down vote up
private static void populateHierarchies(
  Element mondrianDimension,
  Element ssasCubeDimension,
  Element ssasDatabaseDimension,
  Element ssasDimensionKeyAttribute,
  Table factTable,
  List<Table> allTables,
  String factForeignKey
) throws AggDesignerException {

  // first do parent child hierarchies
  // for each attribute in cube dimension, see if it's database dimension attribute is USAGE PARENT
  // SSAS 2005 only supports one parent child hierarchy per dimension
  List cubeAttributes = ssasCubeDimension.selectNodes( "assl:Attributes/assl:Attribute" );
  for ( int i = 0; i < cubeAttributes.size(); i++ ) {
    Element cubeAttribute = (Element) cubeAttributes.get( i );
    // retrieve database attribute
    String attribID = getXPathNodeText( cubeAttribute, "assl:AttributeID" );
    Element databaseAttribute = (Element) ssasDatabaseDimension
      .selectSingleNode( "assl:Attributes/assl:Attribute[assl:ID='" + attribID + "']" );

    Element usageElement = (Element) databaseAttribute.selectSingleNode( "assl:Usage" );
    if ( usageElement != null && "Parent".equals( usageElement.getTextTrim() ) ) {
      populateParentChildHierarchy( mondrianDimension, databaseAttribute, ssasDimensionKeyAttribute,
        ssasDatabaseDimension, factTable, factForeignKey, allTables, attribID );
    }
  }

  // handle the traditional hierarchies

  List hierarchies = ssasCubeDimension.selectNodes( "assl:Hierarchies/assl:Hierarchy" );
  for ( int k = 0; k < hierarchies.size(); k++ ) {
    Element hierarchy = (Element) hierarchies.get( k );
    String databaseHierarchyID = getXPathNodeText( hierarchy, "assl:HierarchyID" );
    Element databaseHierarchy = (Element) ssasDatabaseDimension
      .selectSingleNode( "assl:Hierarchies/assl:Hierarchy[assl:ID='" + databaseHierarchyID + "']" );

    if ( databaseHierarchy == null ) {
      throw new AggDesignerException( "Failed to locate hierarchy " + databaseHierarchyID );
    }

    Element mondrianHierarchy = DocumentFactory.getInstance().createElement( "Hierarchy" );

    mondrianHierarchy.addAttribute( "name", getXPathNodeText( databaseHierarchy, "assl:Name" ) );
    String tableID =
      getXPathNodeText( ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:TableID" );
    Table primaryKeyTable = findTable( allTables, tableID );
    String primaryKey =
      getXPathNodeText( ssasDimensionKeyAttribute, "assl:KeyColumns/assl:KeyColumn/assl:Source/assl:ColumnID" );
    Column primaryKeyColumn = primaryKeyTable.findColumn( primaryKey );

    mondrianHierarchy.addAttribute( "primaryKey", primaryKeyColumn.dbName );

    Element allMemberName = (Element) databaseHierarchy.selectSingleNode( "assl:AllMemberName" );
    if ( allMemberName != null && allMemberName.getTextTrim().length() != 0 ) {
      mondrianHierarchy.addAttribute( "allMemberName", allMemberName.getTextTrim() );
      mondrianHierarchy.addAttribute( "hasAll", "true" );
    } else {
      mondrianHierarchy.addAttribute( "hasAll", "false" );
    }
    // determine if this hierarchy is a snow flake
    // we can tell this by looking at the levels

    // preprocess levels to determine snowflake-ness
    List ssasLevels = databaseHierarchy.selectNodes( "assl:Levels/assl:Level" );

    List<String> tables = new ArrayList<String>();
    for ( int l = 0; l < ssasLevels.size(); l++ ) {
      Element level = (Element) ssasLevels.get( l );
      String sourceAttribID = getXPathNodeText( level, "assl:SourceAttributeID" );
      Element sourceAttribute = (Element) ssasDatabaseDimension
        .selectSingleNode( "assl:Attributes/assl:Attribute[assl:ID='" + sourceAttribID + "']" );
      String levelTableID = getXPathNodeText( sourceAttribute, "assl:NameColumn/assl:Source/assl:TableID" );
      if ( !tables.contains( levelTableID ) ) {
        // insert the table in the correct order
        tables.add( 0, levelTableID );
      }
    }

    // skip if degenerate dimension
    if ( tables.size() != 1 || !tables.get( 0 ).equals( factTable.logicalName ) ) {
      populateHierarchyRelation( mondrianHierarchy, tables, ssasDatabaseDimension, factTable, allTables,
        databaseHierarchyID, factForeignKey );
    } else {
      mondrianHierarchy.add( DocumentFactory.getInstance().createComment( "Degenerate Hierarchy" ) );
    }

    // render levels
    populateHierarchyLevels( mondrianHierarchy, ssasLevels, ssasDatabaseDimension, allTables, tables.size() > 1 );

    mondrianDimension.add( mondrianHierarchy );
  }

  // finally, do attribute hierarchies
  populateAttributeHierarchies( mondrianDimension, cubeAttributes, ssasDatabaseDimension, ssasDimensionKeyAttribute,
    factTable, factForeignKey, allTables );

}
 
Example 19
Source File: GetServerStats.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(SessionData data, Element command) {
    DataForm form = new DataForm(DataForm.Type.result);

    FormField field = form.addField();
    field.setType(FormField.Type.hidden);
    field.setVariable("FORM_TYPE");
    field.addValue("http://jabber.org/protocol/admin");

    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.server_name"));
    field.setVariable("name");
    field.addValue(AdminConsole.getAppName());

    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.version"));
    field.setVariable("version");
    field.addValue(AdminConsole.getVersionString());

    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.domain_name"));
    field.setVariable("domain");
    field.addValue(XMPPServer.getInstance().getServerInfo().getXMPPDomain());

    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.jvm"));
    field.setVariable("os");
    String vmName = System.getProperty("java.vm.name");
    if (vmName == null) {
        vmName = "";
    }
    else {
        vmName = " -- " + vmName;
    }
    field.addValue(System.getProperty("java.version") + " " +System.getProperty("java.vendor") +vmName);

    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.uptime"));
    field.setVariable("uptime");
    field.addValue(XMPPDateTimeFormat.format(XMPPServer.getInstance().getServerInfo().getLastStarted()));

    DecimalFormat mbFormat = new DecimalFormat("#0.00");
    DecimalFormat percentFormat = new DecimalFormat("#0.0");
    Runtime runtime = Runtime.getRuntime();
    double freeMemory = (double)runtime.freeMemory()/(1024*1024);
    double maxMemory = (double)runtime.maxMemory()/(1024*1024);
    double totalMemory = (double)runtime.totalMemory()/(1024*1024);
    double usedMemory = totalMemory - freeMemory;
    double percentFree = ((maxMemory - usedMemory)/maxMemory)*100.0;
    double percentUsed = 100 - percentFree;
    field = form.addField();
    field.setLabel(LocaleUtils.getLocalizedString("index.memory"));
    field.setVariable("memory");
    field.addValue(mbFormat.format(usedMemory) + " MB of " + mbFormat.format(maxMemory) + " MB (" +
            percentFormat.format(percentUsed) + "%) used");

    // Make sure that we are only counting based on bareJIDs and not fullJIDs
    Collection<ClientSession> sessions = SessionManager.getInstance().getSessions();
    Set<String> users = new HashSet<>(sessions.size());
    int availableSessions = 0;
    for (ClientSession session : sessions) {
        if (session.getPresence().isAvailable()) {
            users.add(session.getAddress().toBareJID());
            availableSessions++;
        }
    }
    field = form.addField();
    field.setLabel("Available Users");
    field.setVariable("activeusersnum");
    field.addValue(users.size());

    field = form.addField();
    field.setLabel("Available Users Sessions");
    field.setVariable("sessionsnum");
    field.addValue(availableSessions);

    command.add(form.getElement());
}
 
Example 20
Source File: MUCRoomHistory.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new message and adds it to the history. The new message will be created based on
 * the provided information. This information will likely come from the database when loading
 * the room history from the database.
 *
 * @param senderJID the sender's JID of the message to add to the history.
 * @param nickname the sender's nickname of the message to add to the history.
 * @param sentDate the date when the message was sent to the room.
 * @param subject the subject included in the message.
 * @param body the body of the message.
 * @param stanza the stanza to add
 */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject,
        String body, String stanza)
{
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>)element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>)child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>)child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    }
    else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }

    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    }
    else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}