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

The following examples show how to use org.dom4j.Element#addAttribute() . 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: DesktopSplitPanel.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public boolean saveSettings(Element element) {
    if (!isSettingsEnabled()) {
        return false;
    }

    if (!positionChanged) {
        return false; // most probably user didn't change the divider location
    }

    int location = impl.getUI().getDividerLocation(impl);
    Element e = element.element("position");
    if (e == null) {
        e = element.addElement("position");
    }
    e.addAttribute("value", String.valueOf(location));
    return true;
}
 
Example 2
Source File: StanzaIDUtilTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} does not overwrites
 * a stanza-id element when another is present with a different 'by' value.
 */
@Test
public void testDontOverwriteStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "by", new JID( "someoneelse" ).toString() );
    toOverwrite.addAttribute( "id", notExpected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final List<Element> elements = result.getElement().elements( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    assertEquals( 2, elements.size() );
}
 
Example 3
Source File: ChoiceQuestion.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Adds condition to resprocessing with ident
 * 
 * @param resprocessingXML
 * @param ident
 * @param mastery
 * @param points
 */
private void addRespcondition(final Element resprocessingXML, final String ident, final boolean mastery, final String points) {
    final Element respcondition = resprocessingXML.addElement("respcondition");
    respcondition.addAttribute("continue", "Yes");

    if (mastery) {
        respcondition.addAttribute("title", "Mastery");
    } else {
        respcondition.addAttribute("title", "Fail");
    }
    Element condition = respcondition.addElement("conditionvar");
    if (!mastery) {
        condition = condition.addElement("not");
    }
    final Element varequal = condition.addElement("varequal");
    varequal.addAttribute("respident", getIdent());
    varequal.addAttribute("case", "Yes");
    varequal.addText(ident);

    final Element setvar = respcondition.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Add");
    setvar.addText(points);
}
 
Example 4
Source File: DesktopGroupBox.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public boolean saveSettings(Element element) {
    if (!isSettingsEnabled()) {
        return false;
    }

    Element groupBoxElement = element.element("groupBox");
    if (groupBoxElement != null) {
        element.remove(groupBoxElement);
    }
    groupBoxElement = element.addElement("groupBox");
    groupBoxElement.addAttribute("expanded", BooleanUtils.toStringTrueFalse(isExpanded()));
    return true;
}
 
Example 5
Source File: FIBQuestion.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Build fail resprocessing: Adjust score to 0 (if single correct mode) and set hints, solutions and fail feedback when any blank is answered wrong
 * 
 * @param resprocessingXML
 * @param isSingleCorrect
 */
private void buildRespcondition_fail(final Element resprocessingXML, final boolean isSingleCorrect) {
    // build
    final Element respcondition_fail = resprocessingXML.addElement("respcondition");
    respcondition_fail.addAttribute("title", "Fail");
    respcondition_fail.addAttribute("continue", "Yes");
    final Element conditionvar = respcondition_fail.addElement("conditionvar");
    final Element or = conditionvar.addElement("or");

    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse tmpResponse = (FIBResponse) i.next();
        if (!tmpResponse.getType().equals(FIBResponse.TYPE_BLANK)) {
            continue;
        }
        final Element not = or.addElement("not");
        final Element varequal = not.addElement("varequal");
        varequal.addAttribute("respident", tmpResponse.getIdent());
        varequal.addAttribute("case", tmpResponse.getCaseSensitive());
        varequal.setText(tmpResponse.getCorrectBlank());
    } // for loop

    if (isSingleCorrect) {
        final Element setvar = respcondition_fail.addElement("setvar");
        setvar.addAttribute("varname", "SCORE");
        setvar.addAttribute("action", "Set");
        setvar.addText("0");
    }

    // Use fail feedback, hints and solutions
    QTIEditHelperEBL.addFeedbackFail(respcondition_fail);
    QTIEditHelperEBL.addFeedbackHint(respcondition_fail);
    QTIEditHelperEBL.addFeedbackSolution(respcondition_fail);

    // remove whole respcondition if empty
    if (or.element("varequal") == null) {
        resprocessingXML.remove(respcondition_fail);
    }
}
 
Example 6
Source File: ResultsBuilder.java    From olat with Apache License 2.0 5 votes vote down vote up
private static void addStaticsPath(final Element el_in, final AssessmentInstance ai) {
    Element el_staticspath = (Element) el_in.selectSingleNode(STATICS_PATH);
    if (el_staticspath == null) {
        final DocumentFactory df = DocumentFactory.getInstance();
        el_staticspath = df.createElement(STATICS_PATH);
        final Resolver resolver = ai.getResolver();
        el_staticspath.addAttribute("ident", resolver.getStaticsBaseURI());
        el_in.add(el_staticspath);
    }
}
 
Example 7
Source File: Dom4jAccessor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void set(Object target, Object value, SessionFactoryImplementor factory) 
throws HibernateException {
	Element owner = ( Element ) target;
	Attribute attribute = owner.attribute(attributeName);
	if (value==null) {
		if (attribute!=null) attribute.detach();
	}
	else {
		if (attribute==null) {
			owner.addAttribute(attributeName, "null");
			attribute = owner.attribute(attributeName);
		}
		super.propertyType.setToXMLNode(attribute, value, factory);
	}
}
 
Example 8
Source File: SelectionOrdering.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public void addToElement(final Element root) {
    final Element selection_ordering = root.addElement("selection_ordering");

    final Element selection = selection_ordering.addElement("selection");
    if (selectionNumber > 0) {
        final Element selection_number = selection.addElement("selection_number");
        selection_number.addText(String.valueOf(selectionNumber));
    }

    final Element order = selection_ordering.addElement("order");
    order.addAttribute(ORDER_TYPE, orderType);
}
 
Example 9
Source File: VCardCreated.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Get the username
    String username;
    try {
        username = get(data, "username", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Username required parameter.");
        return;
    }

    // Loads the new vCard
    Element vCard = VCardManager.getProvider().loadVCard(username);

    if (vCard == null) {
        note.addAttribute("type", "error");
        note.setText("VCard not found.");
        return;
    }

    // Fire event.
    VCardEventDispatcher.dispatchVCardCreated(username, vCard);

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example 10
Source File: CourseOfferingExport.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected void exportInstructor(Element instructorElement, ClassInstructor instructor, Session session) {
    exportInstructor(instructorElement, instructor.getInstructor(), session);
    if (instructor.getPercentShare()!=null)
    	instructorElement.addAttribute("share", instructor.getPercentShare().toString());
    instructorElement.addAttribute("lead", instructor.isLead()?"true":"false");
    if (instructor.getResponsibility() != null)
    	instructorElement.addAttribute("responsibility", instructor.getResponsibility().getReference());
}
 
Example 11
Source File: ForkNodeDef.java    From EasyML with Apache License 2.0 5 votes vote down vote up
@Override
public void append2XML(Element root) {
	Element fork = root.addElement("fork");
	fork.addAttribute("name", getName());

	for (NodeDef node : outNodes) {
		Element path = fork.addElement("path");
		path.addAttribute("start", node.getName());
	}

}
 
Example 12
Source File: TimetableSolver.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void toXml(Element element) {
	if (iTimeStamp!=null)
		element.addAttribute("timeStamp", String.valueOf(iTimeStamp.getTime()));
	if (iBefore!=null)
		iBefore.toXml(element.addElement("before"));
	if (iAfter!=null)
		iAfter.toXml(element.addElement("after"));
	if (iAssignments!=null) {
		for (RecordedAssignment ra: iAssignments) {
			ra.toXml(element.addElement("assignment"));
		}
	}
}
 
Example 13
Source File: StudentSectioningXMLSaver.java    From cpsolver with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save enrollment
 * @param assignmentEl assignment element to be populated
 * @param enrollment enrollment to be saved
 */
protected void saveEnrollment(Element assignmentEl, Enrollment enrollment) {
    if (enrollment.getReservation() != null)
        assignmentEl.addAttribute("reservation", getId("reservation", enrollment.getReservation().getId()));
    for (Section section : enrollment.getSections()) {
        Element sectionEl = assignmentEl.addElement("section").addAttribute("id",
                getId("section", section.getId()));
        if (iShowNames)
            sectionEl.setText(section.getName() + " " +
                    (section.getTime() == null ? " Arr Hrs" : " " + section.getTime().getLongName(true)) +
                    (section.getNrRooms() == 0 ? "" : " " + section.getPlacement().getRoomName(",")) +
                    (section.hasInstructors() ? " " + section.getInstructorNames(",") : ""));
    }
}
 
Example 14
Source File: NodeAffiliate.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the affiliate for the deleted items. The event
 * notification may contain one or many published items based on the items included
 * in the original publication. If the affiliate has many subscriptions and many
 * items were deleted 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 deleted from.
 * @param publishedItems the list of items that were deleted.
 */
void sendDeletionNotifications(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", leafNode.getUniqueIdentifier().getNodeId());
            for (PublishedItem publishedItem : itemsBySubs.get(nodeSubscriptions)) {
                // Add retract information to the event notification
                Element item = items.addElement("retract");
                if (leafNode.isItemRequired()) {
                    item.addAttribute("id", publishedItem.getID());
                }
            }
            // Send the event notification
            sendEventNotification(notification, nodeSubscriptions);
            // Remove the added items information
            event.remove(items);
        }
    }
}
 
Example 15
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the specified subscriber. The event notification may
 * include information about the affected subscriptions.
 *
 * @param subscriberJID the subscriber JID that will get the notification.
 * @param notification the message to send to the subscriber.
 * @param subIDs the list of affected subscription IDs or null when node does not
 *        allow multiple subscriptions.
 */
protected void sendEventNotification(JID subscriberJID, Message notification,
        Collection<String> subIDs) {
    Element headers = null;
    if (subIDs != null) {
        // Notate the event notification with the ID of the affected subscriptions
        headers = notification.addChildElement("headers", "http://jabber.org/protocol/shim");
        for (String subID : subIDs) {
            Element header = headers.addElement("header");
            header.addAttribute("name", "SubID");
            header.setText(subID);
        }
    }
    
    // Verify that the subscriber JID is currently available to receive notification
    // messages. This is required because the message router will deliver packets via 
    // the bare JID if a session for the full JID is not available. The "isActiveRoute"
    // condition below will prevent inadvertent delivery of multiple copies of each
    // event notification to the user, possibly multiple times (e.g. route.all-resources). 
    // (Refer to http://issues.igniterealtime.org/browse/OF-14 for more info.)
    //
    // This approach is informed by the following XEP-0060 implementation guidelines:
    //   12.2 "Intended Recipients for Notifications" - only deliver to subscriber JID
    //   12.4 "Not Routing Events to Offline Storage" - no offline storage for notifications
    //
    // Note however that this may be somewhat in conflict with the following:
    //   12.3 "Presence-Based Delivery of Events" - automatically detect user's presence
    //
    if (subscriberJID.getResource() == null ||
        SessionManager.getInstance().getSession(subscriberJID) != null) {
        getService().sendNotification(this, notification, subscriberJID);
    }

    if (headers != null) {
        // Remove the added child element that includes subscription IDs information
        notification.getElement().remove(headers);
    }
}
 
Example 16
Source File: UnifiedXmlDataShapeSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public DataShape createShapeFromRequest(final ObjectNode json, final T openApiDoc, final O operation) {
    final Document document = DocumentHelper.createDocument();

    final Element schemaSet = document.addElement("d:SchemaSet", SCHEMA_SET_NS);
    schemaSet.addNamespace(XmlSchemaHelper.XML_SCHEMA_PREFIX, XmlSchemaHelper.XML_SCHEMA_NS);

    final Element schema = XmlSchemaHelper.addElement(schemaSet, "schema");
    schema.addAttribute("targetNamespace", SYNDESIS_REQUEST_NS);
    schema.addAttribute("elementFormDefault", "qualified");

    final Element parametersSchema = createParametersSchema(openApiDoc, operation);

    final Map<String, SchemaPrefixAndElement> moreSchemas = new HashMap<>();

    final Element bodySchema = createRequestBodySchema(openApiDoc, operation, moreSchemas);

    if (bodySchema == null && parametersSchema == null) {
        return DATA_SHAPE_NONE;
    }

    final Element element = XmlSchemaHelper.addElement(schema, ELEMENT);
    element.addAttribute(NAME, "request");
    final Element sequence = XmlSchemaHelper.addElement(element, COMPLEX_TYPE, SEQUENCE);

    final Element additionalSchemas = schemaSet.addElement("d:AdditionalSchemas");

    if (parametersSchema != null) {
        final Element parameters = XmlSchemaHelper.addElement(sequence, ELEMENT);
        parameters.addNamespace("p", SYNDESIS_PARAMETERS_NS);
        parameters.addAttribute(REF, "p:parameters");

        additionalSchemas.add(parametersSchema.detach());
    }

    if (bodySchema != null) {
        final Element bodyElement = XmlSchemaHelper.addElement(sequence, ELEMENT);
        bodyElement.addAttribute(NAME, "body");

        final Element body = XmlSchemaHelper.addElement(bodyElement, COMPLEX_TYPE, SEQUENCE, ELEMENT);
        final String bodyTargetNamespace = bodySchema.attributeValue("targetNamespace");

        final String bodyElementName = bodySchema.element(ELEMENT).attributeValue(NAME);
        if (bodyTargetNamespace != null) {
            body.addNamespace("b", bodyTargetNamespace);
            body.addAttribute(REF, "b:" + bodyElementName);
        } else {
            body.addAttribute(REF, bodyElementName);
        }

        additionalSchemas.add(bodySchema.detach());
    }

    moreSchemas.values().forEach(e -> additionalSchemas.add(e.schema.detach()));

    final String xmlSchemaSet = XmlSchemaHelper.serialize(document);

    return new DataShape.Builder()//
        .kind(DataShapeKinds.XML_SCHEMA)//
        .name("Request")//
        .description("API request payload")//
        .specification(xmlSchemaSet)//
        .putMetadata(DataShapeMetaData.UNIFIED, "true")
        .build();
}
 
Example 17
Source File: ConversionUtil.java    From pentaho-aggdesigner with GNU General Public License v2.0 4 votes vote down vote up
/**
 * generates <Measure> mondrian tags
 */
private static void populateCubeMeasures(
  Element mondrianCube,
  Element ssasMeasureGroup,
  Table factTable,
  String cubeName
) throws AggDesignerException {

  List allMeasures = ssasMeasureGroup.selectNodes( "assl:Measures/assl:Measure" );
  for ( int j = 0; j < allMeasures.size(); j++ ) {
    Element measure = (Element) allMeasures.get( j );

    // assert Source/Source xsi:type="ColumnBinding"
    if ( measure.selectSingleNode( "assl:Source/assl:Source[@xsi:type='ColumnBinding']" ) == null
      && measure.selectSingleNode( "assl:Source/assl:Source[@xsi:type='RowBinding']" ) == null ) {
      logger.warn( "SKIPPING MEASURE, INVALID MEASURE IN CUBE " + cubeName + " : " + measure.asXML() );
      continue;
    }

    Element mondrianMeasure = DocumentFactory.getInstance().createElement( "Measure" );
    String measureName = getXPathNodeText( measure, "assl:Name" );
    mondrianMeasure.addAttribute( "name", measureName );
    logger.trace( "MEASURE: " + measureName );
    String aggType = "sum";
    Element aggFunction = (Element) measure.selectSingleNode( "assl:AggregateFunction" );
    if ( aggFunction != null ) {
      aggType = aggFunction.getTextTrim().toLowerCase();
    }
    if ( aggType.equals( "distinctcount" ) ) {
      aggType = "distinct-count";
    }
    mondrianMeasure.addAttribute( "aggregator", aggType );
    if ( measure.selectSingleNode( "assl:Source/assl:Source[@xsi:type='ColumnBinding']" ) != null ) {
      String column = getXPathNodeText( measure, "assl:Source/assl:Source/assl:ColumnID" );
      Column columnObj = factTable.findColumn( column );
      columnObj.addToMondrian( mondrianMeasure, "column", "MeasureExpression" );
    } else {
      // select the first fact column in the star
      mondrianMeasure.addAttribute( "column", factTable.columns.get( 0 ) );
    }
    mondrianCube.add( mondrianMeasure );
  }
}
 
Example 18
Source File: StudentSectioningXMLSaver.java    From cpsolver with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Save section
 * @param sectionEl section element to be populated
 * @param section section to be saved
 */
protected void saveSection(Element sectionEl, Section section) {
    sectionEl.addAttribute("id", getId("section", section.getId()));
    sectionEl.addAttribute("limit", String.valueOf(section.getLimit()));
    if (section.isCancelled())
        sectionEl.addAttribute("cancelled", "true");
    if (!section.isEnabled())
        sectionEl.addAttribute("enabled", "false");
    if (section.isOnline())
        sectionEl.addAttribute("online", "true");
    if (iShowNames && section.getNameByCourse() != null)
        for (Map.Entry<Long, String> entry: section.getNameByCourse().entrySet())
            sectionEl.addElement("cname").addAttribute("id", getId("course", entry.getKey())).setText(entry.getValue());
    if (section.getParent() != null)
        sectionEl.addAttribute("parent", getId("section", section.getParent().getId()));
    if (section.hasInstructors()) {
        for (Instructor instructor: section.getInstructors()) {
            Element instructorEl = sectionEl.addElement("instructor");
            instructorEl.addAttribute("id", getId("instructor", instructor.getId()));
            if (iShowNames && instructor.getName() != null)
                instructorEl.addAttribute("name", instructor.getName());
            if (iShowNames && instructor.getExternalId() != null)
                instructorEl.addAttribute("externalId", instructor.getExternalId());
            if (iShowNames && instructor.getEmail() != null)
                instructorEl.addAttribute("email", instructor.getExternalId());
        }
    }
    if (iShowNames)
        sectionEl.addAttribute("name", section.getName());
    if (section.getPlacement() != null) {
        TimeLocation tl = section.getPlacement().getTimeLocation();
        if (tl != null) {
            Element timeLocationEl = sectionEl.addElement("time");
            timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer
                    .toBinaryString(tl.getDayCode()))));
            timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
            timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
            if (tl.getBreakTime() != 0)
                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (iShowNames && tl.getTimePatternId() != null)
                timeLocationEl.addAttribute("pattern", getId("timePattern", tl.getTimePatternId()));
            if (iShowNames && tl.getDatePatternId() != null)
                timeLocationEl.addAttribute("datePattern", tl.getDatePatternId().toString());
            if (iShowNames && tl.getDatePatternName() != null
                    && tl.getDatePatternName().length() > 0)
                timeLocationEl.addAttribute("datePatternName", tl.getDatePatternName());
            timeLocationEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
            if (iShowNames)
                timeLocationEl.setText(tl.getLongName(true));
        }
        for (RoomLocation rl : section.getRooms()) {
            Element roomLocationEl = sectionEl.addElement("room");
            roomLocationEl.addAttribute("id", getId("room", rl.getId()));
            if (iShowNames && rl.getBuildingId() != null)
                roomLocationEl.addAttribute("building", getId("building", rl.getBuildingId()));
            if (iShowNames && rl.getName() != null)
                roomLocationEl.addAttribute("name", rl.getName());
            roomLocationEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
            if (rl.getPosX() != null && rl.getPosY() != null)
                roomLocationEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
            if (rl.getIgnoreTooFar())
                roomLocationEl.addAttribute("ignoreTooFar", "true");
        }
    }
    if (iSaveOnlineSectioningInfo) {
        if (section.getSpaceHeld() != 0.0)
            sectionEl.addAttribute("hold", sStudentWeightFormat.format(section.getSpaceHeld()));
        if (section.getSpaceExpected() != 0.0)
            sectionEl.addAttribute("expect", sStudentWeightFormat
                    .format(section.getSpaceExpected()));
    }
    if (section.getIgnoreConflictWithSectionIds() != null && !section.getIgnoreConflictWithSectionIds().isEmpty()) {
        Element ignoreEl = sectionEl.addElement("no-conflicts");
        for (Long sectionId: section.getIgnoreConflictWithSectionIds())
            ignoreEl.addElement("section").addAttribute("id", getId("section", sectionId));
    }
}
 
Example 19
Source File: EntityInspectorEditor.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * Adds field to the specified field group.
 * If the field should be custom, adds it to the specified customFields collection
 * which can be used later to create fieldGenerators
 *
 * @param metaProperty meta property of the item's property which field is creating
 * @param item         entity instance containing given property
 * @param fieldGroup   field group to which created field will be added
 * @param customFields if the field is custom it will be added to this collection
 * @param required     true if the field is required
 * @param custom       true if the field is custom
 */
protected void addField(MetaClass metaClass, MetaProperty metaProperty, Entity item,
                        FieldGroup fieldGroup, boolean required, boolean custom, boolean readOnly,
                        Collection<FieldGroup.FieldConfig> customFields) {
    if (!attrViewPermitted(metaClass, metaProperty))
        return;

    if ((metaProperty.getType() == MetaProperty.Type.COMPOSITION
            || metaProperty.getType() == MetaProperty.Type.ASSOCIATION)
            && !entityOpPermitted(metaProperty.getRange().asClass(), EntityOp.READ))
        return;

    FieldGroup.FieldConfig field = fieldGroup.createField(metaProperty.getName());
    field.setProperty(metaProperty.getName());
    field.setCaption(getPropertyCaption(metaClass, metaProperty));
    field.setCustom(custom);
    field.setRequired(required);

    if (metaProperty.getRange().isClass() && !metadata.getTools().isEmbedded(metaProperty)) {
        field.setEditable(metadata.getTools().isOwningSide(metaProperty) && !readOnly);
    } else {
        field.setEditable(!readOnly);
    }

    field.setWidth("400px");

    if (requireTextArea(metaProperty, item)) {
        Element root = DocumentHelper.createElement("textArea");
        root.addAttribute("rows", "3");
        field.setXmlDescriptor(root);
    }

    if (focusFieldId == null && !readOnly) {
        focusFieldId = field.getId();
        focusFieldGroup = fieldGroup;
    }

    if (required) {
        field.setRequiredMessage(messageTools.getDefaultRequiredMessage(metaClass, metaProperty.getName()));
    }
    fieldGroup.addField(field);
    if (custom)
        customFields.add(field);
}
 
Example 20
Source File: FilterDelegateImpl.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public boolean saveSettings(Element element) {
    boolean changed = false;
    Element e = element.element("defaultFilter");
    if (e == null)
        e = element.addElement("defaultFilter");

    UUID defaultId = null;
    Boolean applyDefault = false;

    for (FilterEntity filter : filterEntities) {
        if (BooleanUtils.isTrue(filter.getIsDefault())) {
            defaultId = filter.getId();
            applyDefault = filter.getApplyDefault();
            break;
        }
    }

    String newDef = defaultId != null ? defaultId.toString() : null;
    Attribute attr = e.attribute("id");
    String oldDef = attr != null ? attr.getValue() : null;
    if (!Objects.equals(oldDef, newDef)) {
        if (newDef == null && attr != null) {
            e.remove(attr);
        } else {
            if (attr == null)
                e.addAttribute("id", newDef);
            else
                attr.setValue(newDef);
        }
        changed = true;
    }
    Boolean newApplyDef = BooleanUtils.isTrue(applyDefault);
    Attribute applyDefaultAttr = e.attribute("applyDefault");
    Boolean oldApplyDef = applyDefaultAttr != null ? Boolean.valueOf(applyDefaultAttr.getValue()) : false;
    if (!Objects.equals(oldApplyDef, newApplyDef)) {
        if (applyDefaultAttr != null) {
            applyDefaultAttr.setValue(newApplyDef.toString());
        } else {
            e.addAttribute("applyDefault", newApplyDef.toString());
        }
        changed = true;
    }

    if (groupBoxExpandedChanged) {
        Element groupBoxExpandedEl = element.element("groupBoxExpanded");
        if (groupBoxExpandedEl == null)
            groupBoxExpandedEl = element.addElement("groupBoxExpanded");

        Boolean oldGroupBoxExpandedValue =
                groupBoxExpandedEl.getText().isEmpty() ? Boolean.TRUE : Boolean.valueOf(groupBoxExpandedEl.getText());

        Boolean newGroupBoxExpandedValue = groupBoxLayout.isExpanded();
        if (!Objects.equals(oldGroupBoxExpandedValue, newGroupBoxExpandedValue)) {
            groupBoxExpandedEl.setText(newGroupBoxExpandedValue.toString());
            changed = true;
        }
    }

    if (isMaxResultsLayoutVisible()) {
        if (maxResultValueChanged) {
            Element maxResultsEl = element.element("maxResults");
            if (maxResultsEl == null) {
                maxResultsEl = element.addElement("maxResults");
            }

            Integer newMaxResultsValue = maxResultsField.getValue();
            if (newMaxResultsValue != null) {
                maxResultsEl.setText(newMaxResultsValue.toString());
                changed = true;
            }
        }
    }

    return changed;
}