Java Code Examples for org.w3c.dom.Node#setTextContent()

The following examples show how to use org.w3c.dom.Node#setTextContent() . 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: IOUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Modifies element text value according to the given regex (first occurrence) iff 
 * there are following conditions accomplished:
 * 
 *  - exactly one node is found within the document
 *  - the regex is found in the text content of the element
 * 
 * Otherwise there is nothing changed.
 * 
 * @param doc
 * @param tagName
 * @param regex
 * @param replacement 
 */
public static void modifyDocElementValue(Document doc, String tagName, String regex, String replacement) {
    NodeList nodes = doc.getElementsByTagName(tagName);
    if (nodes.getLength() != 1) {
        log.warn("Not able or ambiguous to find element: " + tagName);
        return;
    }

    Node node = nodes.item(0);
    if (node == null) {
        log.warn("Not able to find element: " + tagName);
        return;
    }

    node.setTextContent(node.getTextContent().replaceFirst(regex, replacement));
}
 
Example 2
Source File: HeritrixInverseBooleanAttributeValueModifier.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Document modifyDocument(Document document, String value) {
    if (StringUtils.isBlank(value) || 
            ( !value.equalsIgnoreCase(Boolean.FALSE.toString()) &&
                !value.equalsIgnoreCase(Boolean.TRUE.toString())) ) {
        return document;
    }
    try {
        Boolean valueToSet = !Boolean.valueOf(value);
        Node parentNode = getNodeFromXpath(document);
        NamedNodeMap attr = parentNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
        nodeAttr.setTextContent(valueToSet.toString());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Update " + getAttributeValue() +" attribute of bean "+getIdBeanParent()+ " with value "+ valueToSet.toString());
        }
    } catch (XPathExpressionException ex) {
        LOGGER.warn(ex);
    }
    return document;
}
 
Example 3
Source File: ClusteredOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testXmlClusteredCache(OsgiTestUtils.Cluster cluster) throws Exception {
  File config = cluster.getWorkingArea().resolve("ehcache.xml").toFile();

  Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(TestMethods.class.getResourceAsStream("ehcache-clustered-osgi.xml"));
  XPath xpath = XPathFactory.newInstance().newXPath();
  Node clusterUriAttribute = (Node) xpath.evaluate("//config/service/cluster/connection/@url", doc, XPathConstants.NODE);
  clusterUriAttribute.setTextContent(cluster.getConnectionUri().toString() + "/cache-manager");
  Transformer xformer = TransformerFactory.newInstance().newTransformer();
  xformer.transform(new DOMSource(doc), new StreamResult(config));


  try (PersistentCacheManager cacheManager = (PersistentCacheManager) CacheManagerBuilder.newCacheManager(
    new XmlConfiguration(config.toURI().toURL(), TestMethods.class.getClassLoader())
  )) {
    cacheManager.init();

    final Cache<Long, Person> cache = cacheManager.getCache("clustered-cache", Long.class, Person.class);

    cache.put(1L, new Person("Brian"));
    assertThat(cache.get(1L).name, is("Brian"));
  }
}
 
Example 4
Source File: RemoveToolContextClasspathTask.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Remove the tool's applicationContext entry from the param-value node of the context-param entry.
    * Should find and remove all the matching entries (should it somehow have have got in there m
    * 
    * @param doc
    * @param children
    * @param childNode
    */
   @Override
   protected void updateParamValue(Document doc, Node contextParamElement) {

NodeList valueChildren = contextParamElement.getChildNodes();
for (int i = 0; i < valueChildren.getLength(); i++) {
    Node valueChild = valueChildren.item(i);
    if (valueChild instanceof Text) {
	String value = valueChild.getNodeValue();
	String newValue = StringUtils.replace(value, getApplicationContextPathWithClasspath(), "");
	if (newValue.length() < value.length()) {
	    valueChild.setTextContent(newValue);
	    System.out.println(
		    "Removed context entry " + getApplicationContextPathWithClasspath() + " from document.");
	}
    }
}
   }
 
Example 5
Source File: XMLUtil.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static Document replaceSystemPropsInXml(Document doc) {
   NodeList nodeList = doc.getElementsByTagName("*");
   for (int i = 0, len = nodeList.getLength(); i < len; i++) {
      Node node = nodeList.item(i);
      if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
         if (node.hasAttributes()) {
            NamedNodeMap attributes = node.getAttributes();
            for (int j = 0; j < attributes.getLength(); j++) {
               Node attribute = attributes.item(j);
               attribute.setTextContent(XMLUtil.replaceSystemPropsInString(attribute.getTextContent()));
            }
         }
         if (node.hasChildNodes()) {
            NodeList children = node.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
               String value = children.item(j).getNodeValue();
               if (value != null) {
                  children.item(j).setNodeValue(XMLUtil.replaceSystemPropsInString(value));
               }
            }
         }
      }
   }

   return doc;
}
 
Example 6
Source File: JenkinsConnector.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Update Jenkins job description with build failed factory link.
 *
 * @param factoryUrl build failed factory url that will be set as a url for link in jenkins job
 *     description
 * @throws IOException if any i/o error occurs.
 * @throws ServerException if any other error occurs.
 */
public void addFailedBuildFactoryLink(String factoryUrl) throws IOException, ServerException {
  Document configDocument = xmlToDocument(getCurrentJenkinsJobConfiguration());
  Node descriptionNode =
      configDocument.getDocumentElement().getElementsByTagName("description").item(0);
  String content = descriptionNode.getTextContent();
  if (!content.contains(factoryUrl)) {
    String startPoint = "<br>Dev Workspace (Failed Build): <a href=\"";
    content =
        content.contains(startPoint)
            ? content.substring(0, content.indexOf(startPoint))
            : content;
    descriptionNode.setTextContent(
        content + startPoint + factoryUrl + "\">" + factoryUrl + "</a>");
    updateJenkinsJobDescription(factoryUrl, configDocument);
  } else {
    LOG.debug(String.format(FACTORY_LINK_DISPLAYED_MESSAGE, factoryUrl, jobName));
  }
}
 
Example 7
Source File: UpdateJDACommand.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
    if (args.length == 1) {
        String version = args[0];

        try {
            File f = new File("pom.xml");
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);

            Node jdaNode = doc.getElementsByTagName("dependency").item(0);
            NodeList children = jdaNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i);
                if (node.getNodeName().equalsIgnoreCase("version"))
                    node.setTextContent(version);
            }

            DOMSource source = new DOMSource(doc);
            TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(f));
            channel.sendMessage("Updated to JDA version `" + version + "`\n" +
                    "I will now restart in 10 minutes and apply the update!").queue();
            new FlareBotTask("JDA-Update") {
                @Override
                public void run() {
                    FlareBot.instance().quit(true);
                }
            }.delay(TimeUnit.MINUTES.toMillis(10));
            // _update-jda 3.3.1_306
        } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
            FlareBot.LOGGER.error("Failed to parse the pom file!", e);
            channel.sendMessage("Parsing failed! " + e.getMessage()).queue();
        }
    }
}
 
Example 8
Source File: SimpleTypeMangler.java    From cougar with Apache License 2.0 5 votes vote down vote up
private void replaceViaXPath(Node doc, String simpleTypeName, String simpleTypePrimitive, String xPath)  throws ValidationException {
	// Need to zap through the entire document and replace anything that has a type
	// of the "name" parameter, and replace it's value with the "type" parameter.
	final XPathFactory factory = XPathFactory.newInstance();
       NodeList nodes;
       try {
   		nodes = (NodeList) factory.newXPath().evaluate(xPath, doc, XPathConstants.NODESET);
	} catch (XPathExpressionException e) {
		throw new ValidationException("Unable to parse XPath "+xPath, doc, e);
	}
       for (int i = 0; i < nodes.getLength(); i++) {
       	Node n = nodes.item(i);
       	Node attrNode = getAttributeNode(getName(), n, "type");
       	String content = attrNode.getTextContent();
       	if (content.equals(simpleTypeName)) {
       		attrNode.setTextContent(simpleTypePrimitive);

       	} else {
       		// Need to check if it's a composite type and replace there.
       		String[] composites = getComposites(content);
       		boolean contentChanged = false;
       		if (composites != null) {
       			// It is a composite type - check the underlying data types
       			for (String composite: composites) {
       	        	if (composite.equals(simpleTypeName)) {
       	        		content = content.replace(simpleTypeName, simpleTypePrimitive);
       	        		contentChanged = true;
       	        	}
       			}
       			if (contentChanged) {
       				attrNode.setTextContent(content);
       			}
       		}
       	}
       }

}
 
Example 9
Source File: FilterController.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @description:get filter xml
 * @date:2014-5-5 下午8:28:20
 * @version:v1.0
 * @param request
 * @param response
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping("/getFilterXml.do")
@ResponseBody
public String getFilterXml(HttpServletRequest request, HttpServletResponse response ,HttpSession session) throws Exception {
	
	Key key = (Key)session.getAttribute("key");
	String filterId = request.getParameter("filterId");
	Filter filter = das.queryFilter(DataAccessFactory.getInstance().createUUID(filterId));
	if (filter == null) {
		return "";
	}
	else {
		if(filter.getCreateUser().equals("[email protected]"))
  			{
  				Document filterDoc = XMLUtil.string2Document(filter.getXml(), "UTF-8");

  				Node envNode = XMLUtil.getSingleNode(filterDoc, "query/env");

  				XMLUtil.getSingleNode(envNode, "current_user").setTextContent(key.getUsername());

  				UserInfo userInfo = das.queryUserInfoByUserName(key.getUsername());
  				if (userInfo != null) {
  					Node userListNode = filterDoc.createElement("user_list");
  					userListNode.setTextContent(userInfo.getUserName());
  					envNode.appendChild(userListNode);
			}

  				filter.setXml(XMLUtil.document2String(filterDoc, "UTF-8"));
  			}
		
		return filter.getXml().replaceAll("\\\r", "").replaceAll("\\\n", "").replaceAll("\\\"", "\\\\\\\"").trim();
	}
}
 
Example 10
Source File: AzureIaasHandler.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private void replaceValueOfTagInXMLFile(String filePath, String tagName, String replacingValue)
throws ParserConfigurationException, SAXException, IOException {

	File fXmlFile = new File(filePath);
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);

	//optional, but recommended
	//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
	doc.getDocumentElement().normalize();

	NodeList nList = doc.getElementsByTagName(tagName);
	Node nNode = nList.item(0);
	nNode.setTextContent(replacingValue);

	// write the modified content into xml file
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer;
	try {
		transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filePath));
		transformer.transform(source, result);

	} catch (TransformerException e) {
		this.logger.severe( e.getMessage());
	}
}
 
Example 11
Source File: PomUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the text content of the given node to the specified value preserving all whitespace.
 *
 * @param parentNode the parent node of the node where to set the text content.
 * @param nodeName the name of the node to set the text content at.
 * @param content the text content to set.
 * @param createOnDemand if {@code true} the node with name {@code nodeName} will be created as a child of
 *          {@code parentNode} if it does not exist.
 */
public static void setNodeTextContent(Node parentNode, String nodeName, String content, boolean createOnDemand) {
  Node node = null;
  NodeList children = parentNode.getChildNodes();
  for (int i = 0; i < children.getLength(); i++) {
    Node n = children.item(i);
    if (Objects.equal(nodeName, n.getNodeName())) {
      node = n;
      break;
    }
  }

  if (node == null && createOnDemand) {
    node = parentNode.getOwnerDocument().createElement(nodeName);
    if (children.getLength() > 0) {
      Node lastChild = children.item(children.getLength() - 1);
      Text lineBreak = parentNode.getOwnerDocument().createTextNode("\n");
      parentNode.insertBefore(lineBreak, lastChild);
      parentNode.insertBefore(node, lastChild);
    } else {
      parentNode.appendChild(node);
    }
  }

  if (node != null) {
    node.setTextContent(content);
  }
}
 
Example 12
Source File: Meta_Builder.java    From SensorWebClient with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 
 * @param user. The owner of the rule
 * @param rule
 * @param medium. The selected communication ways. (e.g SMS, E-Mail, ...)
 * @param sensor. Sensor ID
 * @return meta for BR5: Sensor failure
 * @throws Exception 
 */
public static synchronized String createTextFailureMeta(User user, BasicRule rule, String medium, String sensor) throws Exception {
	// final <BAW_Meta> pattern
	String finalMeta = "";
    
	// This is the WNS ID of the user. Each user is subscribed to the WNS with an E-Mail address.
	String wnsID;
	
    String regelName = rule.getName();

    // get the wnsID
    if (medium.equals("SMS")) {
        wnsID = user.getWnsSmsId();
    } else {
        wnsID = user.getWnsEmailId();
    }

    // location of the meta file
    URL metaURL = new URL(SesConfig.resLocation_meta_text);

    // message with place holders
    String message =
        "_T_userID="
        + wnsID
        + "_T_shortMessageEinstieg=SM Regel "
        + regelName
        + " hat einen Alarm ausgeloest. "
        + "Fuer den Sensor " + sensor + " kommen keine Daten mehr. Zeitpunkt:_R__T_MessageEinstieg=Regel "
        + regelName
        + " hat einen Alarm ausgeloest. "
        + "Fuer den Sensor " + sensor + " kommen keine Daten mehr. Zeitpunkt:_R_._T_shortMessageAusstieg=SM Regel "
        + regelName
        + " hat den Alarmzustand beendet. "
        + "Fuer den Sensor " + sensor + " kommen wieder Daten. Zeitpunkt:_R__T_MessageAusstieg=Regel "
        + regelName
        + " hat den Alarmzustand beendet. "
        + "Fuer den Sensor " + sensor + " kommen wieder Daten. Zeitpunkt:_R_!_T_";

    // build meta document
    DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFac.newDocumentBuilder();
    Document doc = docBuilder.parse(metaURL.openStream());

    // transformer for final output
    Transformer transormer = TransformerFactory.newInstance().newTransformer();
    transormer.setOutputProperty(OutputKeys.INDENT, "yes");

    // parse document
    NodeList eventNameList = doc.getElementsByTagName(Constants.selectFunction);
    Node eventNameNode = eventNameList.item(0);
    eventNameNode.getAttributes().getNamedItem(Constants.newEventName).setTextContent("BAW_META_AUSFALL");
    
    // set message
    NodeList messageList = doc.getElementsByTagName(Constants.message);
    Node messageNode = messageList.item(0);
    messageNode.setTextContent(message);

    // build final output
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transormer.transform(source, result);
    finalMeta = result.getWriter().toString();
    finalMeta = finalMeta.substring(38);

    return finalMeta;
}
 
Example 13
Source File: InfoPlist.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void setBundleIdentifier(String pkg) {
    Node n = getPackageNode();
    if (n!=null) {
         n.setTextContent(pkg);
    }
}
 
Example 14
Source File: JunitXmlReportWriter.java    From ossindex-gradle-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void modifyElementAttribute(Document doc, String tagName, Integer index, String attrName, String value) {
  Node target = doc.getElementsByTagName(tagName).item(index);
  NamedNodeMap attr = target.getAttributes();
  Node nodeAttr = attr.getNamedItem(attrName);
  nodeAttr.setTextContent(value);
}
 
Example 15
Source File: HtmlAssetTranslator.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private static void translateOneFile(String language, Path targetHtmlDir, Path sourceFile,
		String translationTextTranslated) throws IOException {

	Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	Document document;
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		document = builder.parse(sourceFile.toFile());
	} catch (ParserConfigurationException pce) {
		throw new IllegalStateException(pce);
	} catch (SAXException sae) {
		throw new IOException(sae);
	}

	Element rootElement = document.getDocumentElement();
	rootElement.normalize();

	Queue<Node> nodes = new LinkedList<>();
	nodes.add(rootElement);

	while (!nodes.isEmpty()) {
		Node node = nodes.poll();
		if (shouldTranslate(node)) {
			NodeList children = node.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				nodes.add(children.item(i));
			}
		}
		if (node.getNodeType() == Node.TEXT_NODE) {
			String text = node.getTextContent();
			if (!text.trim().isEmpty()) {
				text = StringsResourceTranslator.translateString(text, language);
				node.setTextContent(' ' + text + ' ');
			}
		}
	}

	Node translateText = document.createTextNode(translationTextTranslated);
	Node paragraph = document.createElement("p");
	paragraph.appendChild(translateText);
	Node body = rootElement.getElementsByTagName("body").item(0);
	body.appendChild(paragraph);

	DOMImplementationRegistry registry;
	try {
		registry = DOMImplementationRegistry.newInstance();
	} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
		throw new IllegalStateException(e);
	}

	DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	String fileAsString = writer.writeToString(document);
	// Replace default XML header with HTML DOCTYPE
	fileAsString = fileAsString.replaceAll("<\\?xml[^>]+>", "<!DOCTYPE HTML>");
	Files.write(destFile, Collections.singleton(fileAsString), StandardCharsets.UTF_8);
}
 
Example 16
Source File: CharacterRange.java    From DeskChan with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Node toXMLNode(Document doc, String name) {
	Node node = doc.createElement(name);
	node.setTextContent(start + " | " + end);
	return node;
}
 
Example 17
Source File: Meta_Builder.java    From SensorWebClient with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param user. This is the owner of the rule
 * @param ruleName
 * @param medium. The selected communication ways. (e.g SMS, E-Mail, ...)
 * @return {@link String}
 * @throws Exception 
 */
public static synchronized String createTextMeta(User user, String ruleName, String medium) throws Exception {
    
	// final <BAW_Meta> pattern

	String finalMeta = "";
    
    // This is the WNS ID of the user. Each user is subscribed to the WNS with an E-Mail address.
    String wnsID;

    // get the wnsID
    if (medium.equals("SMS")) {
        wnsID = user.getWnsSmsId();
    } else {
        wnsID = user.getWnsEmailId();
    }

    // location of the meta file
    URL metaURL = new URL(SesConfig.resLocation_meta_text);

    // create document
    DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFac.newDocumentBuilder();
    Document doc = docBuilder.parse(metaURL.openStream());

    // transformer for final output
    Transformer transormer = TransformerFactory.newInstance().newTransformer();
    transormer.setOutputProperty(OutputKeys.INDENT, "yes");

    // parse document
    NodeList messageList = doc.getElementsByTagName(Constants.message);
    Node messageNode = messageList.item(0);

    // replace values
    String tempMessage = messageNode.getTextContent();

    // must exist
    if (!tempMessage.contains("wnsID") || !tempMessage.contains("_ruleName_")) {
        throw new Exception();
    }

    tempMessage = tempMessage.replace("wnsID", wnsID);
    tempMessage = tempMessage.replace("_ruleName_", ruleName);

    // set new Text content
    messageNode.setTextContent(tempMessage);

    // build final output
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transormer.transform(source, result);
    finalMeta = result.getWriter().toString();
    // remove the first line of the XML file
    finalMeta = finalMeta.substring(finalMeta.indexOf("<SimplePattern"));

    return finalMeta;
}
 
Example 18
Source File: ConfigXml.java    From syncthing-android with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Updates the config file.
 *
 * Sets ignorePerms flag to true on every folder, force enables TLS, sets the
 * username/password, and disables weak hash checking.
 */
@SuppressWarnings("SdCardPath")
public void updateIfNeeded() {
    boolean changed = false;

    /* Perform one-time migration tasks on syncthing's config file when coming from an older config version. */
    changed = migrateSyncthingOptions() || changed;

    /* Get refs to important config objects */
    NodeList folders = mConfig.getDocumentElement().getElementsByTagName("folder");

    /* Section - folders */
    for (int i = 0; i < folders.getLength(); i++) {
        Element r = (Element) folders.item(i);
        // Set ignorePerms attribute.
        if (!r.hasAttribute("ignorePerms") ||
                !Boolean.parseBoolean(r.getAttribute("ignorePerms"))) {
            Log.i(TAG, "Set 'ignorePerms' on folder " + r.getAttribute("id"));
            r.setAttribute("ignorePerms", Boolean.toString(true));
            changed = true;
        }

        // Set 'hashers' (see https://github.com/syncthing/syncthing-android/issues/384) on the
        // given folder.
        changed = setConfigElement(r, "hashers", "1") || changed;
    }

    /* Section - GUI */
    Element gui = getGuiElement();

    // Platform-specific: Force REST API and Web UI access to use TLS 1.2 or not.
    Boolean forceHttps = Constants.osSupportsTLS12();
    if (!gui.hasAttribute("tls") ||
            Boolean.parseBoolean(gui.getAttribute("tls")) != forceHttps) {
        gui.setAttribute("tls", forceHttps ? "true" : "false");
        changed = true;
    }

    // Set user to "syncthing"
    changed = setConfigElement(gui, "user", "syncthing") || changed;

    // Set password to the API key
    Node password = gui.getElementsByTagName("password").item(0);
    if (password == null) {
        password = mConfig.createElement("password");
        gui.appendChild(password);
    }
    String apikey = getApiKey();
    String pw = password.getTextContent();
    boolean passwordOk;
    try {
        passwordOk = !TextUtils.isEmpty(pw) && BCrypt.checkpw(apikey, pw);
    } catch (IllegalArgumentException e) {
        Log.w(TAG, "Malformed password", e);
        passwordOk = false;
    }
    if (!passwordOk) {
        Log.i(TAG, "Updating password");
        password.setTextContent(BCrypt.hashpw(apikey, BCrypt.gensalt(4)));
        changed = true;
    }

    /* Section - options */
    // Disable weak hash benchmark for faster startup.
    // https://github.com/syncthing/syncthing/issues/4348
    Element options = (Element) mConfig.getDocumentElement()
            .getElementsByTagName("options").item(0);
    changed = setConfigElement(options, "weakHashSelectionMethod", "never") || changed;

    /* Dismiss "fsWatcherNotification" according to https://github.com/syncthing/syncthing-android/pull/1051 */
    NodeList childNodes = options.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeName().equals("unackedNotificationID")) {
            if (node.equals("fsWatcherNotification")) {
                Log.i(TAG, "Remove found unackedNotificationID 'fsWatcherNotification'.");
                options.removeChild(node);
                changed = true;
                break;
            }
        }
    }

    // Save changes if we made any.
    if (changed) {
        saveChanges();
    }
}
 
Example 19
Source File: IOUtil.java    From keycloak with Apache License 2.0 3 votes vote down vote up
/**
 * Modifies attribute value according to the given regex (first occurrence) iff 
 * there are following conditions accomplished:
 * 
 *  - exactly one node is found within the document
 *  - the attribute of the node exists
 *  - the regex is found in the value of the attribute
 * 
 * Otherwise there is nothing changed.
 * 
 * @param doc
 * @param tagName
 * @param attributeName
 * @param regex
 * @param replacement
 */
public static void modifyDocElementAttribute(Document doc, String tagName, String attributeName, String regex, String replacement) {
    NodeList nodes = doc.getElementsByTagName(tagName);
    if (nodes.getLength() != 1) {
        log.warn("Not able or ambiguous to find element: " + tagName);
        return;
    }

    Node node = nodes.item(0).getAttributes().getNamedItem(attributeName);
    if (node == null || node.getTextContent() == null) {
        log.warn("Not able to find attribute " + attributeName + " within element: " + tagName);
        return;
    }
    node.setTextContent(node.getTextContent().replaceFirst(regex, replacement));
}
 
Example 20
Source File: XMLParser.java    From CogniCrypt with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * This method updates the value of a certain {@link Node}.
 * 
 * @param node
 * @param newValue
 */
public void updateNodeValue(final Node node, final String newValue) {
	node.setTextContent(newValue);
	this.doc = node.getOwnerDocument();
}