@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); }
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); }
/** * 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; } }
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( "RedundantTypeArguments") // <Class<?>> is actually needed to compile @Override public ImmutableSet<Class<?>> load(Class<?> concreteClass) { return ImmutableSet.<Class<?>>copyOf( TypeToken.of(concreteClass).getTypes().rawTypes()); }
@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); } }; }
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; }
/** * 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); }
@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); }
/** * 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 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); }
/** * 模拟委托的接口,对应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()); }
@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()); }
/** 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; }
@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()); }
@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); } }
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(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(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)); }
protected Builder() { super(GleSYSApi.class, GleSYSAsyncApi.class); id("glesys") .name("GleSYS API") .identityName("Username") .credentialName("API Key") .documentation(URI.create("https://customer.glesys.com/api.php")) .version("1") .buildVersion("3.5.0") .defaultEndpoint("https://api.glesys.com") .defaultProperties(GleSYSApiMetadata.defaultProperties()) .view(TypeToken.of(ComputeServiceContext.class)) .defaultModules( ImmutableSet.<Class<? extends Module>>of( GleSYSComputeServiceContextModule.class, GleSYSRestClientModule.class)); }
/** * Gets all config properties for the given plugin. * * @return the name of the config field in the plugin class or {@code null} if the plugin doesn't * have a config field */ @Nullable private String getProperties(TypeToken<?> pluginType, Map<String, PluginPropertyField> result) throws UnsupportedTypeException { // Get the config field for (TypeToken<?> type : pluginType.getTypes().classes()) { for (Field field : type.getRawType().getDeclaredFields()) { TypeToken<?> fieldType = TypeToken.of(field.getGenericType()); if (PluginConfig.class.isAssignableFrom(fieldType.getRawType())) { // Pick up all config properties inspectConfigField(fieldType, result); return field.getName(); } } } return null; }
@Test public void builder_forSimpleType() { // Given(SetUp) // When(Exercise) final TypedDefaultMutableTreeNodeBuilder<String> builder = TypedDefaultMutableTreeNodeBuilder.newBuilder(TypeToken.of(String.class)); final String data1 = "1"; final String data2 = "2"; final TypedDefaultMutableTreeNode<String> node = builder.build(data1); // Then(Verify) TypedDefaultMutableTreeNodeTest.compareAndSetUserObject(node, data1, data2); Assert.assertEquals(node.getUserObject(), data2); }
/** Inspects the plugin file and extracts plugin classes information. */ private List<PluginClass> inspectPlugins( Id.Artifact artifactId, File artifactFile, PluginInstantiator pluginInstantiator) throws IOException { List<PluginClass> pluginClasses = Lists.newArrayList(); // See if there are export packages. Plugins should be in those packages Set<String> exportPackages = getExportPackages(artifactFile); if (exportPackages.isEmpty()) { return pluginClasses; } // Load the plugin class and inspect the config field. ArtifactDescriptor artifactDescriptor = new ArtifactDescriptor( artifactId.getName(), artifactId.getVersion(), Constants.SYSTEM_NAMESPACE_ID.equals(artifactId.getNamespace()), Locations.toLocation(artifactFile)); ClassLoader pluginClassLoader = pluginInstantiator.getArtifactClassLoader(artifactDescriptor); for (Class<?> cls : getPluginClasses(exportPackages, pluginClassLoader)) { Plugin pluginAnnotation = cls.getAnnotation(Plugin.class); if (pluginAnnotation == null) { continue; } Map<String, PluginPropertyField> pluginProperties = Maps.newHashMap(); try { String configField = getProperties(TypeToken.of(cls), pluginProperties); PluginClass pluginClass = new PluginClass( pluginAnnotation.type(), getPluginName(cls), getPluginDescription(cls), cls.getName(), configField, pluginProperties); pluginClasses.add(pluginClass); } catch (UnsupportedTypeException e) { LOG.warn("Plugin configuration type not supported. Plugin ignored. {}", cls, e); } } return pluginClasses; }
protected Builder(Class<?> syncClient, Class<?> asyncClient) { super(syncClient, asyncClient); id("swift") .name("OpenStack Swift with SwiftAuth") .identityName("tenantId:user") .credentialName("password") .documentation(URI.create("http://api.openstack.org/")) .version("1.0") .defaultProperties(SwiftApiMetadata.defaultProperties()) .view(TypeToken.of(BlobStoreContext.class)) .context(CONTEXT_TOKEN) .defaultModules( ImmutableSet.<Class<? extends Module>>builder() .add(StorageEndpointModule.class) .add(SwiftRestClientModule.class) .add(SwiftBlobStoreContextModule.class) .add(SwiftTemporaryUrlExtensionModule.class) .build()); }
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); }
protected Builder() { super(CloudLoadBalancersApi.class, CloudLoadBalancersAsyncApi.class); id("rackspace-cloudloadbalancers") .name("Rackspace Cloud Load Balancers API") .identityName("Username") .credentialName("API Key") .documentation( URI.create( "http://docs.rackspace.com/loadbalancers/api/clb-devguide-latest/index.html")) .version("1.0") .defaultEndpoint("https://identity.api.rackspacecloud.com/v2.0/") .defaultProperties(CloudLoadBalancersApiMetadata.defaultProperties()) .view(TypeToken.of(LoadBalancerServiceContext.class)) .defaultModules( ImmutableSet.<Class<? extends Module>>of( CloudIdentityAuthenticationModule.class, ZoneModule.class, CloudLoadBalancersRestClientModule.class, CloudLoadBalancersLoadBalancerContextModule.class)); }