Java Code Examples for org.jdom.Element#getAttribute()

The following examples show how to use org.jdom.Element#getAttribute() . 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: EDocLiteDatabasePostProcessor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private List setExtractFields(Document documentContent) {
    Element rootElement = getRootElement(documentContent);
    List<Element> fields = new ArrayList<Element>();
    Collection<Element> fieldElements = XmlHelper.findElements(rootElement, "field");
    Iterator<Element> elementIter = fieldElements.iterator();
    while (elementIter.hasNext()) {
        Element field = elementIter.next();
        Element version = field.getParentElement();
        if (version.getAttribute("current").getValue().equals("true")) {
            if (field.getAttribute("name") != null) {
                fields.add(field);
            }
        }
    }
    return fields;
}
 
Example 2
Source File: PersistentFileSetManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element state) {
  final VirtualFileManager vfManager = VirtualFileManager.getInstance();
  for (Object child : state.getChildren(FILE_ELEMENT)) {
    if (child instanceof Element) {
      final Element fileElement = (Element)child;
      final Attribute filePathAttr = fileElement.getAttribute(PATH_ATTR);
      if (filePathAttr != null) {
        final String filePath = filePathAttr.getValue();
        VirtualFile vf = vfManager.findFileByUrl(filePath);
        if (vf != null) {
          myFiles.add(vf);
        }
      }
    }
  }
}
 
Example 3
Source File: ParameterNameHintsSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private String attributeValue(Element element, String attr) {
  Attribute attribute = element.getAttribute(attr);
  if (attribute == null) {
    return null;
  }
  return attribute.getValue();
}
 
Example 4
Source File: FYIByNetworkId.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public SimpleResult process(RouteContext context, RouteHelper helper)
		throws Exception {

       LOG.debug("processing FYIByNetworkId simple node");
       String documentId = context.getDocument().getDocumentId();
       Element rootElement = getRootElement(new StandardDocumentContent(context.getDocument().getDocContent()));
	Collection<Element> fieldElements = XmlHelper.findElements(rootElement, "field");
       Iterator<Element> elementIter = fieldElements.iterator();
       while (elementIter.hasNext()) {
       	Element field = (Element) elementIter.next();
       	Element version = field.getParentElement();
       	if (version.getAttribute("current").getValue().equals("true")) {
       		LOG.debug("Looking for networkId field:  " + field.getAttributeValue("name"));
              	if (field.getAttribute("name")!= null && field.getAttributeValue("name").equals("networkId")) {
           		LOG.debug("Should send an FYI to netID:  " + field.getChildText("value"));
              		if (field.getChildText("value") != null) {
              			Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(field.getChildText("value"));

              			//WorkflowDocument wfDoc = new WorkflowDocument(new NetworkIdVO(field.getChildText("value")), documentId);
              			if (!context.isSimulation()) {
                  			KEWServiceLocator.getWorkflowDocumentService().adHocRouteDocumentToPrincipal(user.getPrincipalId(), context.getDocument(), KewApiConstants.ACTION_REQUEST_FYI_REQ, null, null, "Notification Request", user.getPrincipalId(), "Notification Request", true, null);
              		}
              			//wfDoc.adHocRouteDocumentToPrincipal(KewApiConstants.ACTION_REQUEST_FYI_REQ, "Notification Request", new NetworkIdVO(field.getChildText("value")), "Notification Request", true);
               		LOG.debug("Sent FYI using the adHocRouteDocumentToPrincipal function to NetworkID:  " + user.getPrincipalName());
                              	break;
              	}
       	}
       }
       }
	return super.process(context, helper);
}
 
Example 5
Source File: SlackNotificationSettingsTest.java    From tcSlackBuildNotifier with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test_ReadXml() throws JDOMException, IOException {
	SAXBuilder builder = new SAXBuilder();
	//builder.setValidation(true);
	builder.setIgnoringElementContentWhitespace(true);
	
		Document doc = builder.build("src/test/resources/testdoc1.xml");
		Element root = doc.getRootElement();
		System.out.println(root.toString());
		if(root.getChild("slackNotifications") != null){
			Element child = root.getChild("slackNotifications");
			if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))){
				List<Element> namedChildren = child.getChildren("slackNotification");
				for(Iterator<Element> i = namedChildren.iterator(); i.hasNext();)
	            {
					Element e = i.next();
					System.out.println(e.toString() + e.getAttributeValue("url"));
					//assertTrue(e.getAttributeValue("url").equals("http://something"));
					if(e.getChild("parameters") != null){
						Element eParams = e.getChild("parameters");
						List<Element> paramsList = eParams.getChildren("param");
						for(Iterator<Element> j = paramsList.iterator(); j.hasNext();)
						{
							Element eParam = j.next();
							System.out.println(eParam.toString() + eParam.getAttributeValue("name"));
							System.out.println(eParam.toString() + eParam.getAttributeValue("value"));
						}
					}
	            }
			}
		}

}
 
Example 6
Source File: DefaultArrangementSettingsSerializer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private List<ArrangementSectionRule> deserializeSectionRules(@Nonnull Element rulesElement,
                                                             @javax.annotation.Nullable Set<StdArrangementRuleAliasToken> tokens) {
  final List<ArrangementSectionRule> sectionRules = new ArrayList<ArrangementSectionRule>();
  for (Object o : rulesElement.getChildren(SECTION_ELEMENT_NAME)) {
    final Element sectionElement = (Element)o;
    final List<StdArrangementMatchRule> rules = deserializeRules(sectionElement, tokens);
    final Attribute start = sectionElement.getAttribute(SECTION_START_ATTRIBUTE);
    final String startComment = start != null ? start.getValue().trim() : null;
    final Attribute end = sectionElement.getAttribute(SECTION_END_ATTRIBUTE);
    final String endComment = end != null ? end.getValue().trim() : null;
    sectionRules.add(ArrangementSectionRule.create(startComment, endComment, rules));
  }
  return sectionRules;
}
 
Example 7
Source File: Polygon2DFactory.java    From beast-mcmc with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static AbstractPolygon2D createPolygon2D(Element element) {
    //Attribute attrib = element.getAttribute("fillValue");
    Attribute samplingAttrib = element.getAttribute("samplingProbability");
    if (samplingAttrib != null) {
        double fillValue = Double.parseDouble(samplingAttrib.getValue());
        return new Polygon2DSampling(element, fillValue);
    }
    else {
        return new Polygon2D(element);
    }
}
 
Example 8
Source File: WeiXinReqUtil.java    From jeewx-api with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化映射请求
 * @param configName
 * @throws JDOMException
 * @throws IOException
 */
public static void initReqConfig(String configName) throws JDOMException, IOException{
	InputStream is = WeiXinReqService.class.getClassLoader().getResourceAsStream(configName);  
	SAXBuilder xmlBuilder = new SAXBuilder();
	Document doc = xmlBuilder.build(is);
	Element objRoot = doc.getRootElement();
	List<Element> lstMapping = objRoot.getChildren("req");
	WeixinReqConfig objConfig = null;
	for(Element mapping :lstMapping){
		String key = mapping.getAttribute("key").getValue();
		String method = mapping.getAttribute("method").getValue();
		String url = mapping.getAttribute("url").getValue();
		String mappingHandler ="org.jeewx.api.core.handler.impl.WeixinReqDefaultHandler";
		String datatype =WeiXinConstant.PARAM_DATA_TYPE;
		if(mapping.getAttribute("mappingHandler") != null){
			mappingHandler = mapping.getAttribute("mappingHandler").getValue();
		}
		if(mapping.getAttribute("datatype") != null){
			datatype = mapping.getAttribute("datatype").getValue();
		}
		objConfig = new WeixinReqConfig();
		objConfig.setKey(key);
		objConfig.setMappingHandler(mappingHandler);
		objConfig.setMethod(method);
		objConfig.setUrl(url);
		objConfig.setDatatype(datatype);
		WeiXinReqUtil.registerMapping(key, objConfig);
	}
}
 
Example 9
Source File: CsvTableEditorState.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
public static CsvTableEditorState create(@NotNull Element element, @NotNull Project project, @NotNull VirtualFile file) {
    CsvTableEditorState state = new CsvTableEditorState();

    Attribute attribute = element.getAttribute("showInfoPanel");
    state.setShowInfoPanel(
            attribute == null ? CsvEditorSettings.getInstance().showTableEditorInfoPanel() : Boolean.parseBoolean(attribute.getValue())
    );

    attribute = element.getAttribute("fixedHeaders");
    state.setFixedHeaders(
            attribute == null ? false : Boolean.parseBoolean(attribute.getValue())
    );

    attribute = element.getAttribute("autoColumnWidthOnOpen");
    if (attribute != null) {
        state.setAutoColumnWidthOnOpen(Boolean.parseBoolean(attribute.getValue()));
    }

    state.setRowLines(
            StringUtilRt.parseInt(element.getAttributeValue("rowLines"), CsvEditorSettings.getInstance().getTableEditorRowHeight())
    );

    List<Element> columnWidthElements = element.getChildren("column");
    int[] columnWidths = new int[columnWidthElements.size()];
    int defaultColumnWidth = CsvEditorSettings.getInstance().getTableDefaultColumnWidth();
    for (int i = 0; i < columnWidthElements.size(); ++i) {
        Element columnElement = columnWidthElements.get(i);
        int index = StringUtilRt.parseInt(columnElement.getAttributeValue("index"), i);
        columnWidths[index] = StringUtilRt.parseInt(columnElement.getAttributeValue("width"), defaultColumnWidth);
    }
    state.setColumnWidths(columnWidths);

    return state;
}
 
Example 10
Source File: ContextConfigurator.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Element getPropertyElement(String id, String propertyName) {
	Element element = xml.getChild("bean", "id", id);
	if (element == null)
		return null;
	List properties = element.getChildren("property", element.getNamespace());
	for (Iterator iter = properties.iterator(); iter.hasNext();) {
		Element property = (Element) iter.next();
		Attribute nameAttribute = property.getAttribute("name");
		if (nameAttribute != null && propertyName.equals(nameAttribute.getValue())) {
			return property;
		}
	}
	return null;
}
 
Example 11
Source File: ProjectLevelVcsManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void loadState(Element state) {
  mySerialization.readExternalUtil(state, myOptionsAndConfirmations);
  final Attribute attribute = state.getAttribute(SETTINGS_EDITED_MANUALLY);
  if (attribute != null) {
    try {
      myHaveLegacyVcsConfiguration = attribute.getBooleanValue();
    }
    catch (DataConversionException ignored) {
    }
  }
}
 
Example 12
Source File: EDocLiteDatabasePostProcessor.java    From rice with Educational Community License v2.0 4 votes vote down vote up
private void extractEDLData(String documentId, String[] nodeNames, Document documentContent) {
    try {
        org.kuali.rice.kew.api.document.Document document = KewApiServiceLocator.getWorkflowDocumentService().getDocument(documentId);
        DocumentType documentType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeById(
                document.getDocumentTypeId());
        DumpDTO dump = getExtractService().getDumpByDocumentId(documentId);
        if (dump == null) {
            dump = new DumpDTO();
        }
        dump.setDocId(documentId);
        dump.setDocCreationDate(new Timestamp(document.getDateCreated().getMillis()));
        dump.setDocCurrentNodeName(StringUtils.join(nodeNames, ","));
        dump.setDocDescription(documentType.getDescription());
        if (document.getDateLastModified() != null) {
            dump.setDocModificationDate(new Timestamp(document.getDateLastModified().getMillis()));
        }
        dump.setDocInitiatorId(document.getInitiatorPrincipalId());
        dump.setDocRouteStatusCode(document.getStatus().getCode());
        dump.setDocTypeName(documentType.getName());

        List<FieldDTO> fields = dump.getFields();
        fields.clear();

        List fieldElements = setExtractFields(documentContent);
        for (Iterator iter = fieldElements.iterator(); iter.hasNext();) {
            FieldDTO field = new FieldDTO();
            field.setDocId(dump.getDocId());
            Element element = (Element) iter.next();
            Attribute attribute = element.getAttribute("name");
            field.setFieldName(attribute.getValue());
            field.setFieldValue(element.getChildText("value"));
            fields.add(field);
        }
        dump.setFields(fields);
        getExtractService().saveDump(dump);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: AbstractParser.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public boolean
isProtected(Element the_resource) {
  return the_resource.getAttribute(PROT_NAME, AUTH_NS)!=null;
}
 
Example 14
Source File: CryptoKeyFactory.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Loads the crypto key XML file if it is not currently loaded OR if it has
 * changed since it was last loaded.
 */
private static void loadIfNeeded() {
	ResourceFile cryptoDirectory = getCryptoDirectory();

	ResourceFile[] files = cryptoDirectory.listFiles();
	for (ResourceFile file : files) {
		if (!file.getName().endsWith(".xml")) {
			continue;
		}
		if (fileDatesMap.containsKey(file.getName())) {
			if (fileDatesMap.get(file.getName()) == file.lastModified()) {
				continue;
			}
		}
		fileDatesMap.put(file.getName(), file.lastModified());
		try {
			InputStream is = file.getInputStream();
			try {
				SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
				Document doc = sax.build(is);
				Element root = doc.getRootElement();
				String firmwareName = root.getAttributeValue("NAME");
				if (!cryptoMap.containsKey(firmwareName)) {
					cryptoMap.put(firmwareName, new HashMap<String, CryptoKey>());
				}
				List<Element> firmwareFileList =
					CollectionUtils.asList(root.getChildren(), Element.class);
				Iterator<Element> firmwareFileIter = firmwareFileList.iterator();
				while (firmwareFileIter.hasNext()) {
					Element firmwareFileElement = firmwareFileIter.next();
					String path = firmwareFileElement.getAttributeValue("PATH");
					if (firmwareFileElement.getAttribute("not_encrypted") != null) {
						cryptoMap.get(firmwareName).put(path, CryptoKey.NOT_ENCRYPTED_KEY);
					}
					else {
						Element keyElement = firmwareFileElement.getChild("KEY");
						String keyString = keyElement.getText().trim();
						if ((keyString.length() % 2) != 0) {
							throw new CryptoException("Invalid key length in [" + firmwareName +
								".xml] for [" + path + "]");
						}
						byte[] key = NumericUtilities.convertStringToBytes(keyString);
						Element ivElement = firmwareFileElement.getChild("IV");
						String ivString = ivElement.getText().trim();
						if ((ivString.length() % 2) != 0) {
							throw new CryptoException("Invalid iv length in [" + firmwareName +
								".xml] for [" + path + "]");
						}
						byte[] iv = NumericUtilities.convertStringToBytes(ivString);
						CryptoKey cryptoKey = new CryptoKey(key, iv);
						cryptoMap.get(firmwareName).put(path, cryptoKey);
					}
				}
			}
			finally {
				is.close();
			}
		}
		catch (Exception e) {
			Msg.showWarn(CryptoKeyFactory.class, null, "Error Parsing Crypto Keys File",
				"Unable to process crypto keys files.", e);
		}
	}
}
 
Example 15
Source File: DAODatabaseConfiguration.java    From Llunatic with GNU General Public License v3.0 4 votes vote down vote up
private void processImport(Element databaseElement, DBMSDB database, String fileScenario) throws DAOException {
    Element importXmlElement = databaseElement.getChild("import");
    if (importXmlElement != null) {
        Attribute createTableAttribute = importXmlElement.getAttribute("createTables");
        if (createTableAttribute != null) {
            database.getInitDBConfiguration().setCreateTablesFromFiles(Boolean.parseBoolean(createTableAttribute.getValue()));
        }
        for (Object inputFileObj : importXmlElement.getChildren("input")) {
            Element inputFileElement = (Element) inputFileObj;
            String fileName = inputFileElement.getText();
            String tableName = inputFileElement.getAttribute("table").getValue();
            String type = inputFileElement.getAttribute("type").getValue();
            fileName = filePathTransformator.expand(fileScenario, fileName);
            IImportFile fileToImport;
            if (type.equalsIgnoreCase(SpeedyConstants.XML)) {
                fileToImport = new XMLFile(fileName);
            } else if (type.equalsIgnoreCase(SpeedyConstants.CSV)) {
                CSVFile csvFile = new CSVFile(fileName);
                if (inputFileElement.getAttribute("separator") != null) {
                    String separator = inputFileElement.getAttribute("separator").getValue();
                    csvFile.setSeparator(separator.charAt(0));
                }
                if (inputFileElement.getAttribute("quoteCharacter") != null) {
                    String quoteCharacter = inputFileElement.getAttribute("quoteCharacter").getValue();
                    csvFile.setQuoteCharacter(quoteCharacter.charAt(0));
                }
                if (inputFileElement.getAttribute("hasHeader") != null) {
                    boolean hasHeader = Boolean.parseBoolean(inputFileElement.getAttribute("hasHeader").getValue());
                    csvFile.setHasHeader(hasHeader);
                }
                if (inputFileElement.getAttribute("recordsToImport") != null) {
                    String recordsToImportString = inputFileElement.getAttribute("recordsToImport").getValue();
                    try {
                        Integer recordsToImport = Integer.parseInt(recordsToImportString);
                        csvFile.setRecordsToImport(recordsToImport);
                    } catch (NumberFormatException nfe) {
                        throw new DAOException("Attribute recordsToImport needs a valid integer");
                    }
                }
                fileToImport = csvFile;
            } else {
                throw new DAOException("Type " + type + " is not supported");
            }
            database.getInitDBConfiguration().addFileToImportForTable(tableName, fileToImport);
        }
    }
}
 
Example 16
Source File: SlackNotificationMainConfig.java    From tcSlackBuildNotifier with MIT License 4 votes vote down vote up
void readConfigurationFromXmlElement(Element slackNotificationsElement) {
     if(slackNotificationsElement != null){
         content.setEnabled(true);
         if(slackNotificationsElement.getAttribute(ENABLED) != null)
         {
             setEnabled(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(ENABLED)));
         }
         if(slackNotificationsElement.getAttribute(DEFAULT_CHANNEL) != null)
         {
             setDefaultChannel(slackNotificationsElement.getAttributeValue(DEFAULT_CHANNEL));
         }
         if(slackNotificationsElement.getAttribute(TEAM_NAME) != null)
         {
             setTeamName(slackNotificationsElement.getAttributeValue(TEAM_NAME));
         }
         if(slackNotificationsElement.getAttribute(TOKEN) != null)
         {
             setToken(slackNotificationsElement.getAttributeValue(TOKEN));
         }
         if(slackNotificationsElement.getAttribute(ICON_URL) != null)
         {
             content.setIconUrl(slackNotificationsElement.getAttributeValue(ICON_URL));
         }
         if(slackNotificationsElement.getAttribute(BOT_NAME) != null)
         {
             content.setBotName(slackNotificationsElement.getAttributeValue(BOT_NAME));
         }
         if(slackNotificationsElement.getAttribute(SHOW_BUILD_AGENT) != null)
         {
             content.setShowBuildAgent(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_BUILD_AGENT)));
         }
         if(slackNotificationsElement.getAttribute(SHOW_ELAPSED_BUILD_TIME) != null)
         {
             content.setShowElapsedBuildTime(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_ELAPSED_BUILD_TIME)));
         }
         if(slackNotificationsElement.getAttribute(SHOW_COMMITS) != null)
         {
             content.setShowCommits(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_COMMITS)));
         }
         if(slackNotificationsElement.getAttribute(SHOW_COMMITTERS) != null)
         {
             content.setShowCommitters(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_COMMITTERS)));
         }
         if(slackNotificationsElement.getAttribute(SHOW_TRIGGERED_BY) != null)
         {
             content.setShowTriggeredBy(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_TRIGGERED_BY)));
         }
         if(slackNotificationsElement.getAttribute(MAX_COMMITS_TO_DISPLAY) != null)
         {
             content.setMaxCommitsToDisplay(Integer.parseInt(slackNotificationsElement.getAttributeValue(MAX_COMMITS_TO_DISPLAY)));
         }
         if(slackNotificationsElement.getAttribute(SHOW_FAILURE_REASON) != null)
         {
             content.setShowFailureReason(Boolean.parseBoolean(slackNotificationsElement.getAttributeValue(SHOW_FAILURE_REASON)));
         }
if(slackNotificationsElement.getAttribute(FILTER_BRANCH_NAME) != null)
{
	setFilterBranchName(slackNotificationsElement.getAttributeValue(FILTER_BRANCH_NAME));
}

         Element proxyElement = slackNotificationsElement.getChild(PROXY);
         if(proxyElement != null)
         {
             if (proxyElement.getAttribute("proxyShortNames") != null){
                 setProxyShortNames(Boolean.parseBoolean(proxyElement.getAttributeValue("proxyShortNames")));
             }

             if (proxyElement.getAttribute("host") != null){
                 setProxyHost(proxyElement.getAttributeValue("host"));
             }

             if (proxyElement.getAttribute("port") != null){
                 setProxyPort(Integer.parseInt(proxyElement.getAttributeValue("port")));
             }

             if (proxyElement.getAttribute(USERNAME) != null){
                 setProxyUsername(proxyElement.getAttributeValue(USERNAME));
             }

             if (proxyElement.getAttribute(PASSWORD) != null){
                 setProxyPassword(proxyElement.getAttributeValue(PASSWORD));
             }
         }
         else {
             setProxyHost(null);
             setProxyPort(null);
             setProxyUsername(null);
             setProxyPassword(null);
         }
     }
 }
 
Example 17
Source File: AbstractParser.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public boolean
isProtected(Element the_resource) {
  return the_resource.getAttribute(PROT_NAME, AUTH_NS)!=null;
}
 
Example 18
Source File: RunConfigurationSerializer.java    From intellij with Apache License 2.0 3 votes vote down vote up
/**
 * Turn a template run config into a normal run config by doing the following:
 *
 * <ul>
 *   <li>Sets the "default" attribute to "false" on a configuration element if the "default"
 *       attribute is present. This effectively turns a template configuration into a normal
 *       configuration because "default=true" is what indicates a template configuration.
 *   <li>Sets the "name" attribute to #TEMPLATE_RUN_CONFIG_NAME_PREFIX + factoryName attribute.
 *       This makes it clear to the user what the run-config is, because or else it will just show
 *       as "Untitled".
 * </ul>
 *
 * @see com.intellij.execution.impl.RunnerAndConfigurationSettingsImplKt#TEMPLATE_FLAG_ATTRIBUTE
 * @param element The element to be modified.
 */
@VisibleForTesting
static void normalizeTemplateRunConfig(Element element) {
  if (element.getAttribute("default") != null
      && element.getAttributeValue("default").equals("true")) {
    element.setAttribute("default", "false");
    element.setAttribute(
        "name", TEMPLATE_RUN_CONFIG_NAME_PREFIX + element.getAttributeValue("factoryName"));
  }
}
 
Example 19
Source File: CreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Add an attribute with the given value to the given element, but only if the
 * element does not already have the attribute, and the value is not equal to
 * the given default value.
 * 
 * @param paramElt
 *          the element
 * @param value
 *          the attribute value (which will be converted to a string)
 * @param defaultValue
 *          if value.equals(defaultValue) we do not add the attribute.
 * @param attrName
 *          the name of the attribute to add.
 */
private void addAttribute(Element paramElt, Object value,
    Object defaultValue, String attrName) {
  if(!defaultValue.equals(value) && paramElt.getAttribute(attrName) == null) {
    paramElt.setAttribute(attrName, value.toString());
  }
}
 
Example 20
Source File: ContentThreadConfigDOM.java    From entando-components with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Se l'elemento contentThreadConfig ha un attributo sitecode, che specifica
 * il codice del sito abilitato all'invio, lo setta all'interno dell'oggetto
 * {@link NewsletterConfig}
 *
 * @param root
 * l'elemento contentThreadConfig
 * @param contentThreadConfig
 * l'oggetto contenitore della configurazione
 */
private void setSitecode(Element root, ContentThreadConfig contentThreadConfig) {
	Attribute sitecodeAttr = root.getAttribute(SITECODE);
	if (null != sitecodeAttr && sitecodeAttr.getValue().trim().length() > 0) {
		String sitecode = sitecodeAttr.getValue();
		contentThreadConfig.setSitecode(sitecode);
	}
}