Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.json; 16 : 17 : import com.google.gson.FieldNamingPolicy; 18 : import com.google.gson.Gson; 19 : import com.google.gson.GsonBuilder; 20 : import java.sql.Timestamp; 21 : 22 : /** Standard output format used by an API call. */ 23 157 : public enum OutputFormat { 24 : /** 25 : * The output is a human readable text format. It may also be regular enough to be machine 26 : * readable. Whether or not the text format is machine readable and will be committed to as a long 27 : * term format that tools can build upon is specific to each API call. 28 : */ 29 157 : TEXT, 30 : 31 : /** 32 : * Pretty-printed JSON format. This format uses whitespace to make the output readable by a human, 33 : * but is also machine readable with a JSON library. The structure of the output is a long term 34 : * format that tools can rely upon. 35 : */ 36 157 : JSON, 37 : 38 : /** 39 : * Same as {@link #JSON}, but with unnecessary whitespace removed to save generation time and copy 40 : * costs. Typically JSON_COMPACT format is used by a browser based HTML client running over the 41 : * network. 42 : */ 43 157 : JSON_COMPACT; 44 : 45 : /** Returns true when the format is either JSON or JSON_COMPACT. */ 46 : public boolean isJson() { 47 157 : return this == JSON_COMPACT || this == JSON; 48 : } 49 : 50 : /** Returns a new Gson instance configured according to the format. */ 51 : public GsonBuilder newGsonBuilder() { 52 157 : if (!isJson()) { 53 0 : throw new IllegalStateException(String.format("%s is not JSON", this)); 54 : } 55 157 : GsonBuilder gb = 56 : new GsonBuilder() 57 157 : .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) 58 157 : .registerTypeAdapter(Timestamp.class, new SqlTimestampDeserializer()) 59 157 : .registerTypeAdapterFactory(new EnumTypeAdapterFactory()); 60 157 : if (this == OutputFormat.JSON) { 61 15 : gb.setPrettyPrinting(); 62 : } 63 157 : return gb; 64 : } 65 : 66 : /** Returns a new Gson instance configured according to the format. */ 67 : public Gson newGson() { 68 157 : return newGsonBuilder().create(); 69 : } 70 : }