Example usage for com.google.gson.reflect TypeToken getType

List of usage examples for com.google.gson.reflect TypeToken getType

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken getType.

Prototype

public final Type getType() 

Source Link

Document

Gets underlying Type instance.

Usage

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestAuthenticatedGetRequest.java

License:Open Source License

@Override
protected void authenticate(IOperationMonitor monitor) throws IOException {
    UserCredentials credentials = getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
    if (credentials == null) {
        throw new IllegalStateException("Authentication requested without valid credentials");
    }/*from www .  ja  v a2  s  .co m*/
    HttpRequestBase request = new HttpGet(baseUrl() + MessageFormat.format("/login?login={0}&password={1}",
            new Object[] { credentials.getUserName(), credentials.getPassword() }));
    request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
    request.setHeader(ACCEPT, APPLICATION_JSON);
    HttpResponse response = getClient().execute(request, monitor);
    try {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            getClient().setAuthenticated(false);
            throw new AuthenticationException("Authentication failed",
                    new AuthenticationRequest<AuthenticationType<UserCredentials>>(getClient().getLocation(),
                            AuthenticationType.REPOSITORY));
        } else {
            TypeToken<LoginToken> type = new TypeToken<LoginToken>() {
            };
            InputStream is = response.getEntity().getContent();
            InputStreamReader in = new InputStreamReader(is);
            LoginToken loginToken = new Gson().fromJson(in, type.getType());
            ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
            getClient().setAuthenticated(true);
        }
    } finally {
        HttpUtil.release(request, response, monitor);
    }
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestGetTaskData.java

License:Open Source License

@Override
protected List<TaskData> parseFromJson(InputStreamReader in) throws BugzillaRestException {
    TypeToken<List<TaskData>> type = new TypeToken<List<TaskData>>() {
    };/* w w  w  . j ava  2 s.  c o  m*/
    return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()).create()
            .fromJson(in, type.getType());
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPostNewTask.java

License:Open Source License

@Override
protected BugzillaRestIdResult parseFromJson(InputStreamReader in) {
    TypeToken<BugzillaRestIdResult> type = new TypeToken<BugzillaRestIdResult>() {
    };//  w w w .ja v  a 2s .  com
    return new Gson().fromJson(in, type.getType());
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPostNewTask.java

License:Open Source License

protected BugzillaRestStatus parseErrorFromJson(InputStreamReader in) {
    TypeToken<BugzillaRestStatus> type = new TypeToken<BugzillaRestStatus>() {
    };/* www .j av  a2 s.c  o  m*/
    return new Gson().fromJson(in, type.getType());
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestPutUpdateTask.java

License:Open Source License

@Override
protected PutUpdateResult parseFromJson(InputStreamReader in) {
    TypeToken<PutUpdateResult> type = new TypeToken<PutUpdateResult>() {
    };/*from   w w w.jav  a 2  s.  c  o m*/
    return new Gson().fromJson(in, type.getType());
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient27.java

License:Open Source License

private Map<String, ProjectInfo> listProjects(IProgressMonitor monitor) throws GerritException {
    final String uri = "/projects/"; //$NON-NLS-1$
    TypeToken<Map<String, ProjectInfo>> resultType = new TypeToken<Map<String, ProjectInfo>>() {
    };// w ww .  j a v a  2  s. com
    return executeGetRestRequest(uri, resultType.getType(), monitor);
}

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>>() {
    };/* w w w .j a  va  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.eclipse.mylyn.internal.phabricator.core.client.TracWebClient.java

License:Open Source License

private boolean parseAttributesJSon(String text) {
    // remove surrounding JavaScript
    if (text.startsWith("var properties=")) { //$NON-NLS-1$
        text = text.substring("var properties=".length()); //$NON-NLS-1$
    }/*  w  w w . jav  a 2 s  .  com*/
    int i = text.indexOf("};"); //$NON-NLS-1$
    if (i != -1) {
        text = text.substring(0, i + 1);
    }

    // parse JSon stream
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    TypeToken<Map<String, TracConfigurationField>> type = new TypeToken<Map<String, TracConfigurationField>>() {
    };
    Map<String, TracConfigurationField> fieldByName;
    try {
        fieldByName = gson.fromJson(text, type.getType());
        if (fieldByName == null) {
            return false;
        }
    } catch (JsonSyntaxException e) {
        return false;
    }

    // copy parsed JSon objects in to client data 
    TracConfiguration configuration = new TracConfiguration(data);
    for (Map.Entry<String, TracConfigurationField> entry : fieldByName.entrySet()) {
        AttributeFactory factory = configuration.getFactoryByField(entry.getKey());
        if (factory != null) {
            factory.initialize();

            TracConfigurationField field = entry.getValue();
            if (field.options != null && field.options.size() > 0) {
                for (String option : field.options) {
                    factory.addAttribute(option);
                }
            } else if (field.optgroups != null && field.optgroups.size() > 0) {
                // milestones in Trac 0.13 support groups for labeling related options: ignore groups but extract options  
                for (TracConfigurationOptGroup group : field.optgroups) {
                    if (group.options != null) {
                        for (String option : group.options) {
                            factory.addAttribute(option);
                        }
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != Multiset.class || !(type instanceof ParameterizedType)) {
        return null;
    }// www  .  ja v  a 2 s .c  o m

    Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
    TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
    return (TypeAdapter<T>) newMultisetAdapter(elementAdapter);
}

From source file:org.eclipse.smarthome.storage.json.PropertiesTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings({ "unused", "unchecked" })
@Override//from   w w  w.  j  a v a 2  s  .c  o  m
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

    Class<? super T> rawType = typeToken.getRawType();
    if (!PropertiesTypeAdapter.TOKEN.equals(typeToken)) {
        return null;
    }

    return (TypeAdapter<T>) new PropertiesTypeAdapter(gson);
}