/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.cosmos.internal.dr.drs.service.handler.common;

import java.util.Hashtable;
import java.util.Iterator;

public class JSONObject extends Hashtable<String, Object> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9174184187225511837L;
	
	
	@Override
	public synchronized String toString() {
		Iterator<String> keys = keySet().iterator();
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		int x = 0;
		while (keys.hasNext()){
			if (x > 0)
				sb.append(",");
			String key = keys.next();
			Object value = get(key);
			sb.append("\""+key+"\":");
			if (value instanceof String)
				sb.append("\""+removeTabAndReturnChar((String)value)+"\"");
			else 
				sb.append(value);
			x++;
		}
		sb.append("}");	

		return sb.toString();		
	}
	
	private String removeTabAndReturnChar(String value){
		String newVal = value.replaceAll("/", "\\\\/");
		newVal = newVal.replaceAll("\"", "\\\\\"");
		newVal = newVal.replaceAll("\'", "\\\\\'");
		newVal = newVal.replaceAll("\t", "\\\\t");
		newVal = newVal.replaceAll("\r", "\\\\r");
		return newVal.replaceAll("\n", "\\\\n");
		
	}
}
