java-html-sanitizer icon indicating copy to clipboard operation
java-html-sanitizer copied to clipboard

Thread Safety Problem with Preprocessor

Open subbudvk opened this issue 1 year ago • 1 comments

I am using Preprocessor to change content of a specific tag. The implementation looks like follows,

I will listen for openTag event and when current tag is style, I handle it in a boolean and in the text() callback, I am checking whether current tag is style.

The problem, is in a multi-threaded environment, when openTag set current tag as style and before text() resets the boolean anything called text() is considered as style tag.

I moved the boolean below asnew HtmlStreamEventReceiverWrapper(eventReceiver) { boolean isCurrentTagStyle = false; }and it seems to be working fine. Any better suggestions to handle this without a preprocessor or is there a threadsafe event processor i can use?

(new HtmlStreamEventProcessor() {
			boolean isCurrentTagStyle = false;
                        @Override
			public HtmlStreamEventReceiver wrap(HtmlStreamEventReceiver eventReceiver) {
				return new HtmlStreamEventReceiverWrapper(eventReceiver) {
					@Override
					public void openTag(String elementName, List<String> attrs) {
						if (STYLE.equals(elementName))
							isCurrentTagStyle = true;
						super.openTag(elementName, attrs);
					}

					@Override
					public void text(String text) {
						String textContent = new String(text);
						if (isCurrentTagStyle) {	
							try { 
								//Change style content here	
							} catch (Exception e) {
								textContent = "";
							}
	                                           isCurrentTagStyle = false;
						}
						super.text(textContent);
					}
				};

			}
		});

subbudvk avatar Jan 15 '25 10:01 subbudvk

@mikesamuel

subbudvk avatar Jan 15 '25 10:01 subbudvk