JsonMagicTest.java

/***************************************************************************
   Copyright 2014 Emily Estes

   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.
***************************************************************************/
package net.metanotion.json;


import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.metanotion.util.Dictionary;
import net.metanotion.util.types.JsonMagicP;
import net.metanotion.util.types.Parser;
import net.metanotion.util.types.TypeDictionary;
import net.metanotion.util.reflect.GetInitializer;
import net.metanotion.util.reflect.ReflectiveFieldInitializer;

public final class JsonMagicTest {
	private static final Logger logger = LoggerFactory.getLogger(JsonMagicTest.class);

	private static final class Account {
		public String username;
		public Boolean validated;
	}

	private static final class AccountInfo {
		public final String username;
		public final List<Account> accounts;
		public AccountInfo(String username, List<Account> accounts) {
			this.username = username;
			this.accounts = accounts;
		}
	}

	private static final class MapTest {
		public Map<String,Object> keys = new HashMap<>();
	}

	private static final Dictionary<Class,Parser> td = new Dictionary<Class,Parser>() {
		private final TypeDictionary td = new TypeDictionary();
		@Override public Parser get(Class c) {
			Parser p = td.get(c);
			logger.debug("Class: '{}'", c);
			if(p == null) {
				logger.debug("is null");
				p = new JsonMagicP(c);
				td.addParser(c, p);
			}
			return p;
		}
	};

	public static void main(String[] args) throws Exception {
		GetInitializer<Account> acct = ReflectiveFieldInitializer.getInitializer(Account.class,td);
		GetInitializer<AccountInfo> gi = ReflectiveFieldInitializer.getInitializer(AccountInfo.class,td);

		LinkedList<Account> accts = new LinkedList<>();

		Account a = new Account();
		a.username = "awef";
		a.validated = true;
		accts.add(a);

		a = new Account();
		a.username = "baz";
		a.validated = false;
		accts.add(a);

		AccountInfo ai = new AccountInfo("asdf", accts);

		JsonMagic jm = new JsonMagic(AccountInfo.class);
		JsonObject o = jm.toJSON(ai);
		logger.debug("Object: {}", o.toString());

		MapTest mt = new MapTest();
		mt.keys.put("key1", ai);
		mt.keys.put("foo", 10);
		jm = new JsonMagic(MapTest.class);
		logger.debug(jm.toJSON(mt).toString());
	}
}