/** Creates a {@link PluginPropertyField} based on the given field. */ private PluginPropertyField createPluginProperty(Field field, TypeToken<?> resolvingType) throws UnsupportedTypeException { TypeToken<?> fieldType = resolvingType.resolveType(field.getGenericType()); Class<?> rawType = fieldType.getRawType(); Name nameAnnotation = field.getAnnotation(Name.class); Description descAnnotation = field.getAnnotation(Description.class); String name = nameAnnotation == null ? field.getName() : nameAnnotation.value(); String description = descAnnotation == null ? "" : descAnnotation.value(); if (rawType.isPrimitive()) { return new PluginPropertyField(name, description, rawType.getName(), true); } rawType = Primitives.unwrap(rawType); if (!rawType.isPrimitive() && !String.class.equals(rawType)) { throw new UnsupportedTypeException("Only primitive and String types are supported"); } boolean required = true; for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().endsWith(".Nullable")) { required = false; break; } } return new PluginPropertyField( name, description, rawType.getSimpleName().toLowerCase(), required); }
@Override public void serialize(TypeToken<?> type, Mute mute, ConfigurationNode node) throws ObjectMappingException { node.getNode("muted").setValue(TypeToken.of(UUID.class), mute.getMuted()); node.getNode("muter").setValue(TypeToken.of(UUID.class), mute.getMuter()); node.getNode("endtime").setValue(mute.getEndtime()); node.getNode("starttime").setValue(mute.getStarttime()); node.getNode("reason").setValue(TypeToken.of(Text.class), mute.getReason()); }
@Override public Mute deserialize(TypeToken<?> type, ConfigurationNode node) throws ObjectMappingException { UUID muted = node.getNode("muted").getValue(TypeToken.of(UUID.class)); UUID muter = node.getNode("muter").getValue(TypeToken.of(UUID.class)); Long endtime = node.getNode("endtime").getLong(); Long starttime = node.getNode("starttime").getLong(); Text reason = node.getNode("reason").getValue(TypeToken.of(Text.class)); return new Mute(muted, muter, endtime, starttime, reason); }
@Test public void testTypeToken() throws NoSuchMethodException, SecurityException, InvocationTargetException, IllegalAccessException { TypeToken<TypeTokenTest> token = TypeToken.of(TypeTokenTest.class); Invokable<TypeTokenTest, ?> invokable = token.method(TypeTokenTest.class.getMethod("helloWorld")); invokable.invoke(this); }
public static <K, V> ThriftType map(ThriftType keyType, ThriftType valueType) { checkNotNull(keyType, "keyType is null"); checkNotNull(valueType, "valueType is null"); @SuppressWarnings("serial") Type javaType = new TypeToken<Map<K, V>>() {}.where( new TypeParameter<K>() {}, (TypeToken<K>) TypeToken.of(keyType.getJavaType())) .where(new TypeParameter<V>() {}, (TypeToken<V>) TypeToken.of(valueType.getJavaType())) .getType(); return new ThriftType(ThriftProtocolType.MAP, javaType, keyType, valueType); }
/** * Constructor. * * @param contentType the type of request this parser can handle */ protected ParserSupport(String contentType) { this.contentType = contentType; TypeToken<O> typeToken = new TypeToken<O>(getClass()) {}; if (typeToken.getType() instanceof Class) { @SuppressWarnings("unchecked") Class<O> rawType = (Class<O>) typeToken.getRawType(); this.optsType = rawType; } else { throw new IllegalArgumentException("Type parameter O of ParserSupport must be a Class"); } }
public class BlobStoreViewMBeanFactory implements ViewMBeanFactory<BlobStoreContext> { private static final TypeToken<BlobStoreContext> TYPE = TypeToken.of(BlobStoreContext.class); /** * Creates a {@link org.jclouds.management.ManagedBean} for the Context. * * @param view * @return */ @Override public ViewMBean<BlobStoreContext> create(BlobStoreContext view) { return new BlobStoreManagement(view); } /** * Returns the {@link com.google.common.reflect.TypeToken} of the {@link org.jclouds.View}. * * @return */ @Override public TypeToken<BlobStoreContext> getViewType() { return TYPE; } }
@Override public boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return List.class.isAssignableFrom(type) && TypeToken.of(genericType).resolveType(LIST_GENERIC_TOKEN).getRawType().equals(Page.class) && mediaType.isCompatible(PRESTO_PAGES_TYPE); }
@SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); if (typeToken.getRawType() != ImmutableMap.class || !(type instanceof ParameterizedType)) { return null; } com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken = (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>) com.google.common.reflect.TypeToken.of(typeToken.getType()); final TypeAdapter<HashMap<?, ?>> hashMapAdapter = (TypeAdapter<HashMap<?, ?>>) gson.getAdapter( TypeToken.get( betterToken.getSupertype(Map.class).getSubtype(HashMap.class).getType())); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value); hashMapAdapter.write(out, hashMap); } @Override public T read(JsonReader in) throws IOException { HashMap<?, ?> hashMap = hashMapAdapter.read(in); return (T) ImmutableMap.copyOf(hashMap); } }; }
@SuppressWarnings( "RedundantTypeArguments") // <Class<?>> is actually needed to compile @Override public ImmutableSet<Class<?>> load(Class<?> concreteClass) { return ImmutableSet.<Class<?>>copyOf( TypeToken.of(concreteClass).getTypes().rawTypes()); }
/** * Known keys for metadata * * @author Adrian Cole */ public enum Metadata { ROOT_AUTHORIZED_KEYS(TypeToken.of(String.class).getType()), /** * If the dataset you create a machine from is set to generate passwords for you, the * username/password pairs will be returned in the metadata response as a nested object, like: * * <pre> * "credentials": { * "root": "s8v9kuht5e", * "admin": "mf4bteqhpy" * } * </pre> */ CREDENTIALS( new TypeToken<Map<String, String>>() { private static final long serialVersionUID = -433136967305618708L; }.getType()); private final Type valueType; Metadata(Type valueType) { this.valueType = valueType; } public String key() { return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, name()); } /** type of the value; */ public Type type() { return valueType; } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AdapterKey<?> other = (AdapterKey<?>) obj; return key.equals(other.getKey()) && role.equals(other.role); }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((role == null) ? 0 : role.hashCode()); return result; }
/** * Creates a new {@link AdapterKey} for the given key and role. * * @param <T> The adapter type. * @param key The key to use for the newly created {@link AdapterKey}. May not be <code>null * </code>. * @param role The role to use for the newly created {@link AdapterKey}. May not be <code>null * </code>. * @return A new {@link AdapterKey} for the given key and role. */ public static <T> AdapterKey<T> get(Class<T> key, String role) { if (key == null) { throw new NullPointerException("Key may not be null."); } if (role == null) { throw new NullPointerException("Role may not be null."); } return new AdapterKey<T>(TypeToken.of(key), role); }
public static void main(String[] args) { ApplicationContext appContext = new AnnotationConfigApplicationContext(FieldsCheckerMain.class); FieldsChecker fieldsChecker = appContext.getBean(FieldsChecker.class); fieldsChecker.checkTableFields(); boolean resolved = false; TypeToken mapOfString = TypeTokens.mapOf(String.class, String.class); Type type = mapOfString.getType(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] types = pType.getActualTypeArguments(); if (types.length == 2) { TypeToken valueType = TypeToken.of(types[1]); resolved = valueType.getRawType().equals(String.class); } } System.out.println(resolved); }
/** * Creates a new optioninfo. * * @param name Name of the option. * @param help Help string. * @param prefix Prefix scope for the option. * @param type Concrete option target type. * @param <T> Option type. * @return A new optioninfo. */ public static <T> OptionInfo<T> create(String name, String help, String prefix, Class<T> type) { return new OptionInfo<T>( checkValidName(name), help, Arg.<T>create(), TypeToken.of(type), prefix, ImmutableList.<Annotation>of(), null); }
@Test public void shouldDownloadBundle() { client.downloadBundle(ANY_RESOURCE_ID); String expectedUri = ARTIFACTS_BUNDLE_URI + ARTIFACTS_BUNDLE_DOWNLOAD_URI + "/" + ANY_RESOURCE_ID; Request expectedRequest = new Request(HttpMethod.GET, expectedUri); then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(String.class).getType()); }
public static <E> ThriftType list(ThriftType valueType) { checkNotNull(valueType, "valueType is null"); @SuppressWarnings("serial") Type javaType = new TypeToken<List<E>>() {}.where( new TypeParameter<E>() {}, (TypeToken<E>) TypeToken.of(valueType.getJavaType())) .getType(); return new ThriftType(ThriftProtocolType.LIST, javaType, null, valueType); }
/** * 模拟委托的接口,对应C#中的委托Action(void -> void) * * @author Zhang Yifan */ @ParametersAreNonnullByDefault public interface Action0 extends IDelegate { /** */ void DoAction(); /** */ public static final TypeToken<Action0> ACTION0_TYPETOKEN = TypeToken.of(Action0.class); /** A Method object that represents the only method in Action0 interface. */ public static final Invokable<Action0, Void> ACTION0_METHOD = Methods.TryGetFirstMethod(TypeToken.of(Action0.class), "DoAction") .get() .returning(void.class); // public static final Method ACTION0_METHOD = Methods.TryGetFirstMethod(Action0.class, // "DoAction").get(); // public static final Invokable<Action0, Void> ACTION0_INVOKABLE = // ACTION0_TYPETOKEN.method(ACTION0_METHOD).returning(Void.class); }
@Test public void shouldGetSasLogicalInterconnectGroupById() { client.getById(ANY_RESOURCE_ID); String expectedUri = SAS_LOGICAL_INTERCONNECT_GROUP_URI + "/" + ANY_RESOURCE_ID; Request expectedRequest = new Request(HttpMethod.GET, expectedUri); then(baseClient) .should() .executeRequest(expectedRequest, TypeToken.of(SasLogicalInterconnectGroup.class).getType()); }
/** * Inspects the plugin config class and build up a map for {@link PluginPropertyField}. * * @param configType type of the config class * @param result map for storing the result * @throws UnsupportedTypeException if a field type in the config class is not supported */ private void inspectConfigField(TypeToken<?> configType, Map<String, PluginPropertyField> result) throws UnsupportedTypeException { for (TypeToken<?> type : configType.getTypes().classes()) { if (PluginConfig.class.equals(type.getRawType())) { break; } for (Field field : type.getRawType().getDeclaredFields()) { PluginPropertyField property = createPluginProperty(field, type); if (result.containsKey(property.getName())) { throw new IllegalArgumentException( "Plugin config with name " + property.getName() + " already defined in " + configType.getRawType()); } result.put(property.getName(), property); } } }
@Test public void shouldGetArtifactsBundle() { client.getById(ANY_RESOURCE_ID); String expectedUri = ARTIFACTS_BUNDLE_URI + "/" + ANY_RESOURCE_ID; Request expectedRequest = new Request(HttpMethod.GET, expectedUri); then(baseClient) .should() .executeRequest(expectedRequest, TypeToken.of(ArtifactsBundle.class).getType()); }
private <T> List<T> deserializeAsArray( JsonElement json, JsonDeserializationContext context, TypeToken<T> typeToken, Type listOfT) { if (json.isJsonPrimitive()) { List<T> list = new ArrayList<T>(); list.add((T) context.deserialize(json, typeToken.getType())); return list; } else { return context.deserialize(json, listOfT); } }
/** Constructor with hit for handling type. */ public ConfigureAdapterStage( CConfiguration cConf, Id.Namespace namespace, String adapterName, Location templateJarLocation, PluginRepository pluginRepository) { super(TypeToken.of(AdapterDeploymentInfo.class)); this.cConf = cConf; this.namespace = namespace; this.adapterName = adapterName; this.templateJarLocation = templateJarLocation; this.pluginRepository = pluginRepository; }
private List<ApplicationClass> inspectApplications(File artifactFile) throws IOException, InvalidArtifactException { List<ApplicationClass> apps = Lists.newArrayList(); Location artifactLocation = Locations.toLocation(artifactFile); Manifest manifest = BundleJarUtil.getManifest(artifactLocation); if (manifest == null) { return apps; } Attributes manifestAttributes = manifest.getMainAttributes(); if (manifestAttributes == null) { return apps; } // right now we force users to include the application main class as an attribute in their // manifest, // which forces them to have a single application class. // in the future, we may want to let users do this or maybe specify a list of classes or // a package that will be searched for applications, to allow multiple applications in a single // artifact. String mainClassName = manifestAttributes.getValue(ManifestFields.MAIN_CLASS); if (mainClassName != null) { try (CloseableClassLoader artifactClassLoader = artifactClassLoaderFactory.createClassLoader(Locations.toLocation(artifactFile))) { Object appMain = artifactClassLoader.loadClass(mainClassName).newInstance(); if (!(appMain instanceof Application)) { throw new InvalidArtifactException( String.format( "Application main class is of invalid type: %s", appMain.getClass().getName())); } Application app = (Application) appMain; TypeToken typeToken = TypeToken.of(app.getClass()); TypeToken<?> resultToken = typeToken.resolveType(Application.class.getTypeParameters()[0]); Type configType; // if the user parameterized their template, like 'xyz extends ApplicationTemplate<T>', // we can deserialize the config into that object. Otherwise it'll just be a Config if (resultToken.getType() instanceof Class) { configType = resultToken.getType(); } else { configType = Config.class; } apps.add(new ApplicationClass(mainClassName, "", schemaGenerator.generate(configType))); } catch (ClassNotFoundException e) { throw new InvalidArtifactException( String.format("Could not find Application main class %s.", mainClassName)); } catch (UnsupportedTypeException e) { throw new InvalidArtifactException( String.format("Config for Application %s has an unsupported schema.", mainClassName)); } catch (InstantiationException | IllegalAccessException e) { throw new InvalidArtifactException( String.format("Could not instantiate Application class %s.", mainClassName), e); } } return apps; }
@Override public void onInitialize() throws CraftBookException { super.onInitialize(); try { List<String> blockBagList = config.getNode("blockbags").getList(TypeToken.of(String.class)); blockBags = new BlockBag[blockBagList.size()]; for (int i = 0; i < blockBagList.size(); i++) { blockBags[i] = BlockBag.createFromString(blockBagList.get(i)); } } catch (ObjectMappingException e) { CraftBookPlugin.spongeInst().getLogger().error("Failed to map object.", e); } }
@Test public void shouldStopBundleCreation() { TaskUri taskUri = new TaskUri(); taskUri.setTaskUri(ANY_TASK_URI); client.stopBundleCreation(ANY_RESOURCE_ID, taskUri); String expectedUri = ARTIFACTS_BUNDLE_URI + "/" + ANY_RESOURCE_ID + ARTIFACTS_BUNDLE_STOP_ARTIFACT_CREATE_URI; Request expectedRequest = new Request(HttpMethod.PUT, expectedUri, taskUri); then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(String.class).getType()); }
protected Builder(Class<?> client, Class<?> asyncClient) { super(client, asyncClient); id("chef") .name("Opscode Platform Api") .identityName("User") .credentialName("Certificate") .version(ChefAsyncClient.VERSION) .documentation(URI.create("http://help.opscode.com/kb/api")) .defaultEndpoint("https://api.opscode.com") .defaultProperties(OpscodePlatformApiMetadata.defaultProperties()) .context(TypeToken.of(OpscodePlatformContext.class)) .defaultModules( ImmutableSet.<Class<? extends Module>>of( OpscodePlatformRestClientModule.class, JMXOhaiModule.class)); }
protected Builder() { super(CloudSigmaClient.class, CloudSigmaAsyncClient.class); id("cloudsigma") .name("CloudSigma API") .identityName("Email") .credentialName("Password") .documentation(URI.create("http://cloudsigma.com/en/platform-details/the-api")) .version("1.0") .defaultEndpoint("https://api.cloudsigma.com") .defaultProperties(CloudSigmaApiMetadata.defaultProperties()) .view(TypeToken.of(ComputeServiceContext.class)) .defaultModules( ImmutableSet.<Class<? extends Module>>of( CloudSigmaRestClientModule.class, CloudSigmaComputeServiceContextModule.class)); }
protected Builder() { super(AtmosClient.class, AtmosAsyncClient.class); id("atmos") .name("EMC's Atmos API") .identityName("Subtenant ID (UID)") .credentialName("Shared Secret") .documentation(URI.create("https://community.emc.com/docs/DOC-10508")) .version("1.4.0") .defaultEndpoint("https://accesspoint.atmosonline.com") .defaultProperties(AtmosApiMetadata.defaultProperties()) .view(TypeToken.of(BlobStoreContext.class)) .defaultModules( ImmutableSet.<Class<? extends Module>>of( AtmosRestClientModule.class, AtmosBlobStoreContextModule.class)); }