List of usage examples for com.google.gson ExclusionStrategy ExclusionStrategy
ExclusionStrategy
From source file:org.eclipse.mylyn.internal.gerrit.core.client.JSonSupport.java
License:Open Source License
public JSonSupport() { TypeToken<Map<Id, PatchSetApproval>> approvalMapType = new TypeToken<Map<ApprovalCategory.Id, PatchSetApproval>>() { };/*from ww w. j av a 2 s . c om*/ ExclusionStrategy exclustionStrategy = new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { // commentLinks requires instantiation of com.google.gwtexpui.safehtml.client.RegexFindReplace which is not on classpath if (f.getDeclaredClass() == List.class && f.getName().equals("commentLinks") //$NON-NLS-1$ && f.getDeclaringClass() == GerritConfig.class) { return true; } if (f.getDeclaredClass() == Map.class && f.getName().equals("given")) { //$NON-NLS-1$ //return true; } // GSon 2.1 fails to deserialize the SubmitType enum if (f.getDeclaringClass() == Project.class && f.getName().equals("submitType")) { //$NON-NLS-1$ return true; } return false; } public boolean shouldSkipClass(Class<?> clazz) { return false; } }; gson = JsonServlet.defaultGsonBuilder() .registerTypeAdapter(JSonResponse.class, new JSonResponseDeserializer()) .registerTypeAdapter(Edit.class, new JsonDeserializer<Edit>() { public Edit deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); if (array.size() == 4) { return new Edit(array.get(0).getAsInt(), array.get(1).getAsInt(), array.get(2).getAsInt(), array.get(3).getAsInt()); } } return new Edit(0, 0); } }) // ignore GerritForge specific AuthType "TEAMFORGE" which is unknown to Gerrit .registerTypeAdapter(AuthType.class, new JsonDeserializer<AuthType>() { @Override public AuthType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String jsonString = json.getAsString(); if (jsonString != null) { try { return AuthType.valueOf(jsonString); } catch (IllegalArgumentException e) { // ignore the error since the connector does not make use of AuthType //GerritCorePlugin.logWarning("Ignoring unkown authentication type: " + jsonString, e); } } return null; } }) .registerTypeAdapter(approvalMapType.getType(), new JsonDeserializer<Map<Id, PatchSetApproval>>() { @Override public Map<Id, PatchSetApproval> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Gerrit 2.2: the type of PatchSetPublishDetail.given changed from a map to a list Map<Id, PatchSetApproval> map = new HashMap<ApprovalCategory.Id, PatchSetApproval>(); if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); for (Iterator<JsonElement> it = array.iterator(); it.hasNext();) { JsonElement element = it.next(); Id key = context.deserialize(element, Id.class); if (key.get() != null) { // Gerrit < 2.1.x: json is map element = it.next(); } PatchSetApproval value = context.deserialize(element, PatchSetApproval.class); if (key.get() == null) { // Gerrit 2.2: json is a list, deduct key from value key = value.getCategoryId(); } map.put(key, value); } } return map; } }).setExclusionStrategies(exclustionStrategy).create(); }
From source file:org.gisho.spring.config.GsonConfiguration.java
@Bean @ConditionalOnMissingBean//from w w w . ja v a2s .c o m public Gson gson() { Gson gson = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes field) { return field.getName().equals("echantillonList") || field.getName().equals("cofisemUserList") || field.getName().equals("spiUserList") || field.getName().equals("userRoleSet") || field.getName().equals("password"); } @Override public boolean shouldSkipClass(Class<?> arg0) { return false; } }).serializeNulls().setDateFormat("dd/MM/yyyy").create(); return gson; }
From source file:org.jboss.aerogear.android.impl.unifiedpush.AeroGearGCMPushRegistrar.java
License:Apache License
@Override public void register(final Context context, final Callback<Void> callback) { new AsyncTask<Void, Void, Exception>() { @Override/* w ww . j a v a 2 s . co m*/ protected Exception doInBackground(Void... params) { try { if (gcm == null) { gcm = gcmProvider.get(context); } String regid = getRegistrationId(context); if (regid.length() == 0) { regid = gcm.register(config.senderIds.toArray(new String[] {})); AeroGearGCMPushRegistrar.this.setRegistrationId(context, regid); } config.setDeviceToken(regid); URL deviceRegistryURL = UrlUtils.appendToBaseURL(pushServerURI.toURL(), registryDeviceEndpoint); HttpRestProviderForPush httpProvider = httpProviderProvider.get(deviceRegistryURL, TIMEOUT); httpProvider.setPasswordAuthentication(config.getVariantID(), config.getSecret()); Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { private final ImmutableSet<String> fields; { fields = ImmutableSet.<String>builder().add("deviceToken").add("deviceType") .add("alias").add("operatingSystem").add("osVersion").add("categories").build(); } @Override public boolean shouldSkipField(FieldAttributes f) { return !(f.getDeclaringClass() == PushConfig.class && fields.contains(f.getName())); } @Override public boolean shouldSkipClass(Class<?> arg0) { return false; } }).create(); try { httpProvider.post(gson.toJson(config)); return null; } catch (HttpException ex) { return ex; } } catch (Exception ex) { return ex; } } @SuppressWarnings("unchecked") @Override protected void onPostExecute(Exception result) { if (result == null) { callback.onSuccess(null); } else { callback.onFailure(result); } }; }.execute((Void) null); }
From source file:org.mitre.oauth2.view.TokenIntrospection.java
License:Apache License
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override//from www.j a va 2 s. com public boolean shouldSkipField(FieldAttributes f) { /* if (f.getDeclaringClass().isAssignableFrom(OAuth2AccessTokenEntity.class)) { // we don't want to serialize the whole object, just the scope and timeout if (f.getName().equals("scope")) { return false; } else if (f.getName().equals("expiration")) { return false; } else { // skip everything else on this class return true; } } else { // serialize other classes without filter (lists and sets and things) return false; } */ return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } else { return false; } } }).registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() { public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject token = new JsonObject(); token.addProperty("valid", true); JsonArray scopes = new JsonArray(); for (String scope : src.getScope()) { scopes.add(new JsonPrimitive(scope)); } token.add("scope", scopes); token.add("expires", context.serialize(src.getExpiration())); return token; } }).setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); response.setContentType("application/json"); Writer out = response.getWriter(); Object obj = model.get("entity"); if (obj == null) { obj = model; } gson.toJson(obj, out); }
From source file:org.mitre.oauth2.view.TokenIntrospectionView.java
License:Apache License
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {// w ww . j av a 2 s .c o m Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { /* if (f.getDeclaringClass().isAssignableFrom(OAuth2AccessTokenEntity.class)) { // we don't want to serialize the whole object, just the scope and timeout if (f.getName().equals("scope")) { return false; } else if (f.getName().equals("expiration")) { return false; } else { // skip everything else on this class return true; } } else { // serialize other classes without filter (lists and sets and things) return false; } */ return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } else { return false; } } }).registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() { @Override public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject token = new JsonObject(); token.addProperty("active", true); token.addProperty("scope", Joiner.on(" ").join(src.getScope())); token.add("exp", context.serialize(src.getExpiration())); //token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId()); token.addProperty("sub", src.getAuthenticationHolder().getAuthentication().getName()); token.addProperty("client_id", src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId()); token.addProperty("token_type", src.getTokenType()); return token; } }).registerTypeAdapter(OAuth2RefreshTokenEntity.class, new JsonSerializer<OAuth2RefreshTokenEntity>() { @Override public JsonElement serialize(OAuth2RefreshTokenEntity src, Type typeOfSrc, JsonSerializationContext context) { JsonObject token = new JsonObject(); token.addProperty("active", true); token.addProperty("scope", Joiner.on(" ") .join(src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope())); token.add("exp", context.serialize(src.getExpiration())); //token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId()); token.addProperty("sub", src.getAuthenticationHolder().getAuthentication().getName()); token.addProperty("client_id", src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId()); return token; } }).setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); response.setContentType("application/json"); Writer out; try { out = response.getWriter(); Object obj = model.get("entity"); if (obj == null) { obj = model; } gson.toJson(obj, out); } catch (IOException e) { logger.error("IOException occurred in TokenIntrospectionView.java: ", e); } }
From source file:org.mitre.openid.connect.view.JSONIdTokenView.java
License:Apache License
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { return false; }/*from w ww . jav a 2 s. c o m*/ public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } return false; } }).registerTypeHierarchyAdapter(ClaimSet.class, new JsonSerializer<ClaimSet>() { @Override public JsonElement serialize(ClaimSet src, Type typeOfSrc, JsonSerializationContext context) { if (src != null) { return src.getAsJsonObject(); } else { return JsonNull.INSTANCE; } } }).create(); response.setContentType("application/json"); Writer out = response.getWriter(); Object obj = model.get("entity"); if (obj == null) { obj = model; } gson.toJson(obj, out); }
From source file:org.mitre.openid.connect.view.JSONUserInfoView.java
License:Apache License
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {//from www.j ava 2 s . co m UserInfo userInfo = (UserInfo) model.get("userInfo"); Set<String> scope = (Set<String>) model.get("scope"); Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { return false; } public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } return false; } }).create(); response.setContentType("application/json"); Writer out; try { out = response.getWriter(); gson.toJson(toJson(userInfo, scope), out); } catch (IOException e) { logger.error("IOException in JSONUserInfoView.java: ", e); } }
From source file:org.mitre.openid.connect.view.JwkKeyListView.java
License:Apache License
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {/*w ww.j a v a2 s . c om*/ Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { return false; } public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } return false; } }).create(); response.setContentType("application/json"); //BiMap<String, PublicKey> keyMap = (BiMap<String, PublicKey>) model.get("keys"); Map<String, JwtSigner> signers = (Map<String, JwtSigner>) model.get("signers"); JsonObject obj = new JsonObject(); JsonArray keys = new JsonArray(); obj.add("keys", keys); for (String keyId : signers.keySet()) { JwtSigner src = signers.get(keyId); if (src instanceof RsaSigner) { RsaSigner rsaSigner = (RsaSigner) src; RSAPublicKey rsa = (RSAPublicKey) rsaSigner.getPublicKey(); // we're sure this is an RSAPublicKey b/c this is an RsaSigner BigInteger mod = rsa.getModulus(); BigInteger exp = rsa.getPublicExponent(); String m64 = Base64.encodeBase64URLSafeString(mod.toByteArray()); String e64 = Base64.encodeBase64URLSafeString(exp.toByteArray()); JsonObject o = new JsonObject(); o.addProperty("use", "sig"); // since we don't do encryption yet o.addProperty("alg", "RSA"); //rsaSigner.getAlgorithm()); // we know this is RSA o.addProperty("mod", m64); o.addProperty("exp", e64); o.addProperty("kid", keyId); keys.add(o); } // TODO: deal with non-RSA key types } Writer out; try { out = response.getWriter(); gson.toJson(obj, out); } catch (IOException e) { logger.error("IOException in JwkKeyListView.java: ", e); } }
From source file:org.mitre.openid.connect.view.POCOUserInfoView.java
License:Apache License
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {//from ww w.j a v a2s . c o m UserInfo userInfo = (UserInfo) model.get("userInfo"); Set<String> scope = (Set<String>) model.get("scope"); Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes f) { return false; } public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } return false; } }).create(); response.setContentType("application/json"); Writer out; try { out = response.getWriter(); gson.toJson(toPoco(userInfo, scope), out); } catch (IOException e) { logger.error("IOException in POCOUserInfoView.java: ", e); } }
From source file:org.mitre.swd.view.JsonOpenIdConfigurationView.java
License:Apache License
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {// w ww. j a va2s .c om Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { // skip the JPA binding wrapper if (clazz.equals(BeanPropertyBindingResult.class)) { return true; } else { return false; } } }).create(); response.setContentType("application/json"); Object obj = model.get("entity"); if (obj == null) { obj = model; } Writer out; try { out = response.getWriter(); gson.toJson(obj, out); } catch (IOException e) { logger.error("IOException in JsonOpenIdConfigurationView.java: ", e); } }