Java tutorial
/******************************************************************************* * Copyright (c) 2015 IBM Corp. * * 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 com.ibm.ws.lars.rest.model; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ibm.ws.lars.rest.exceptions.InvalidJsonAssetException; /** * */ public abstract class RepositoryObjectList<T> { private static ObjectMapper reader = new ObjectMapper(); private static ObjectMapper writer = new ObjectMapper(); protected final List<Map<String, Object>> state; protected RepositoryObjectList(List<Map<String, Object>> state) { if (state != null) { this.state = state; } else { this.state = new ArrayList<Map<String, Object>>(); } } public List<Map<String, Object>> getState() { return state; } public String toJson() throws JsonProcessingException { return writer.writeValueAsString(this.state); } public int size() { return state.size(); } public T get(int i) { return wrapState(state.get(i)); } protected abstract T wrapState(Map<String, Object> props); public boolean isEmpty() { return size() == 0; } protected static List<Map<String, Object>> readJsonState(String json) throws InvalidJsonAssetException { try { return reader.readValue(json, new TypeReference<List<Map<String, Object>>>() { }); } catch (JsonParseException e) { throw new InvalidJsonAssetException(e); } catch (JsonMappingException e) { throw new InvalidJsonAssetException(e); } catch (IOException e) { // No idea what would cause this. throw new InvalidJsonAssetException(e); } } protected static List<Map<String, Object>> readJsonState(byte[] json) throws InvalidJsonAssetException { try { return reader.readValue(json, new TypeReference<List<Map<String, Object>>>() { }); } catch (JsonParseException e) { throw new InvalidJsonAssetException(e); } catch (JsonMappingException e) { throw new InvalidJsonAssetException(e); } catch (IOException e) { // No idea what would cause this. throw new InvalidJsonAssetException(e); } } }