package org.ctrip.ops.sysdev.filters;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONValue;

public class Json extends BaseFilter {
	private static final Logger logger = Logger.getLogger(Json.class.getName());

	public Json(Map config) {
		super(config);
	}

	private String tagOnFailure;
	private String field;
	private ArrayList<String> removeFields;

	protected void prepare() {
		if (!config.containsKey("field")) {
			logger.error("no field configured in Json");
			System.exit(1);
		}
		this.field = (String) config.get("field");

		this.removeFields = (ArrayList<String>) this.config
				.get("remove_fields");

		if (config.containsKey("tag_on_failure")) {
			this.tagOnFailure = (String) config.get("tag_on_failure");
		} else {
			this.tagOnFailure = "jsonfail";
		}
	};

	@Override
	protected Map filter(final Map event) {
		Map<String, Object> obj = null;
		if (event.containsKey(this.field)) {
			obj = (HashMap<String, Object>) JSONValue.parse((String) event
					.get(field));

		}

		if (obj == null) {
			if (!event.containsKey("tags")) {
				event.put("tags",
						new ArrayList<String>(Arrays.asList(this.tagOnFailure)));
			} else {
				Object tags = event.get("tags");
				if (tags.getClass() == ArrayList.class
						&& ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) {
					((ArrayList) tags).add(this.tagOnFailure);
				}
			}
		} else {
			event.putAll(obj);
			if (this.removeFields != null) {
				for (String f : this.removeFields) {
					event.remove(f);
				}
			}
		}
		return event;
	}
}

@@ -36,61 +36,8 @@
 s;%0A%0A
-import java.util.ArrayList;%0Aimport java.util.Arrays;%0A
 impo
@@ -334,84 +334,13 @@
 ing 
-tagOnFailure;%0A%09private String field;%0A%09private ArrayList%3CString%3E removeFields
+field
 ;%0A%0A%09
@@ -525,90 +525,8 @@
 );%0A%0A
-%09%09this.removeFields = (ArrayList%3CString%3E) this.config%0A%09%09%09%09.get(%22remove_fields%22);%0A%0A
 %09%09if
@@ -894,17 +894,16 @@
 ield));%0A
-%0A
 %09%09%7D%0A%0A%09%09i
@@ -909,17 +909,17 @@
 if (obj 
-=
+!
 = null) 
@@ -927,489 +927,71 @@
 %0A%09%09%09
-if (!event.containsKey(%22tags%22)) %7B%0A%09%09%09%09event.put(%22tags%22,%0A%09%09%09%09%09%09new ArrayList%3CString%3E(Arrays.asList(this.tagOnFailure)));%0A%09%09%09%7D else %7B%0A%09%09%09%09Object tags = event.get(%22tags%22);%0A%09%09%09%09if (tags.getClass() == ArrayList.class%0A%09%09%09%09%09%09&& ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) %7B%0A%09%09%09%09%09((ArrayList) tags).add(this.tagOnFailure);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D else %7B%0A%09%09%09event.putAll(obj);%0A%09%09%09if (this.removeFields != null) %7B%0A%09%09%09%09for (String f : this.removeFields) %7B%0A%09%09%09%09%09event.remove(f);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D
+event.putAll(obj);%0A%09%09%7D%0A%0A%09%09this.postProcess(event, obj != null);
 %0A%09%09r

use postProcess in Json filter