All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jfplugin.xsql.statement.TextStatement Maven / Gradle / Ivy

The newest version!
package com.jfplugin.xsql.statement;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Node;

import com.jfplugin.xsql.core.Context;
import com.jfplugin.xsql.core.VarParser;

/**
 * 文本节点
 * @author farmer
 *
 */
public class TextStatement extends Statement{

	static class Var{
		int start;
		int end;
		String text;
	}
	/**变量正则*/
	private static final String VAR_REG = "#\\{([^\\{\\}])+\\}";
	/**常量正则*/
	private static final String CONST_REG = "\\$\\{([^\\\\{\\\\}])+\\}";
	
	private static final Pattern VAR_PATTERN = Pattern.compile(VAR_REG);
	
	private static final Pattern CONST_PATTERN = Pattern.compile(CONST_REG);
	
	
	public TextStatement(Node node) {
		super(node);
	}

	@Override
	public void execute(Context ctx, Object localVar) {
		List vars = new ArrayList();
		List reverseArgs = new ArrayList();
		String text = node.getTextContent();
		Matcher matcher = VAR_PATTERN.matcher(text);
		while (matcher.find()) {
			Var var = new Var();
			var.start = matcher.start();
			var.end = matcher.end();
			var.text = text.substring(var.start+2, var.end-1);
			vars.add(var);
		}
		for (int i = vars.size() -1 ; i >= 0; i--) {
			Var var = vars.get(i);
			text = text.substring(0, var.start) + "?" + text.substring(var.end, text.length());
			reverseArgs.add(VarParser.parser(var.text,ctx.globalVar,localVar));
		}
		for (int i = reverseArgs.size() - 1; i >= 0; i--) {
			ctx.args.add(reverseArgs.get(i));
		}
		matcher = CONST_PATTERN.matcher(text);
		vars.clear();
		while (matcher.find()) {
			Var var = new Var();
			var.start = matcher.start();
			var.end = matcher.end();
			var.text = text.substring(var.start+2, var.end-1);
			vars.add(var);
		}
		for (int i = vars.size() -1 ; i >= 0; i--) {
			Var var = vars.get(i);
			text = text.substring(0, var.start) + VarParser.parser(var.text,ctx.globalVar,localVar) + text.substring(var.end, text.length());
		}
		ctx.sw.append(text);
	}

}