de.fhg.iais.asc.transformer.jdom.handler.XmlFieldCleanser.java Source code

Java tutorial

Introduction

Here is the source code for de.fhg.iais.asc.transformer.jdom.handler.XmlFieldCleanser.java

Source

package de.fhg.iais.asc.transformer.jdom.handler;

/******************************************************************************
 * Copyright 2011 (c) Fraunhofer IAIS Netmedia  http://www.iais.fraunhofer.de *
 * ************************************************************************** *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License.                   *
 * You may obtain a copy of the License at                                    *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 * Unless required by applicable law or agreed to in writing,                 *
 * software distributed under the License is distributed on an "AS IS" BASIS, *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

import org.apache.commons.lang.StringUtils;
import org.jdom.Element;

import de.fhg.iais.commons.annotation.OnlyCalledFromTests;

/**
 * Bereinigt einen Feld-Inhalt, wenn Feld und Inhalt angegebenen Mustern entsprechen.
 * 
 * @author kst
 */
@OnlyCalledFromTests
public class XmlFieldCleanser extends AbstractXmlFieldContentTransformer {
    final String[] searchTerms;
    final String replacement;

    /**
     * @param fieldPattern XPath expression pointing to a field.
     * @param contentPattern Regex must match field content to trigger changes.
     * @param searchTerms A string inside the content that is being replaced.
     * @param replacement A replacement for the searched term.
     */
    public XmlFieldCleanser(String fieldPattern, String contentPattern, String[] searchTerms, String replacement) {

        super(fieldPattern, contentPattern);
        this.searchTerms = searchTerms.clone();
        this.replacement = replacement;
    }

    @Override
    protected String transform(Element element, String text) {
        String result = text;

        for (String term : this.searchTerms) {
            if (result.contains(term)) {
                result = StringUtils.replace(result, term, this.replacement).trim();
            }
        }

        return result;
    }
}