net.bytebuddy.utility.RandomString Java Examples

The following examples show how to use net.bytebuddy.utility.RandomString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClassReloadingStrategyTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce(retransformsClasses = true)
@JavaVersionRule.Enforce(atMost = 10) // Wait for mechanism in sun.misc.Unsafe to define class.
public void testFromAgentClassWithAuxiliaryReloadingStrategy() throws Exception {
    assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
    Foo foo = new Foo();
    assertThat(foo.foo(), is(FOO));
    ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent();
    String randomName = FOO + RandomString.make();
    new ByteBuddy()
            .redefine(Foo.class)
            .method(named(FOO))
            .intercept(FixedValue.value(BAR))
            .make()
            .include(new ByteBuddy().subclass(Object.class).name(randomName).make())
            .load(Foo.class.getClassLoader(), classReloadingStrategy);
    try {
        assertThat(foo.foo(), is(BAR));
    } finally {
        classReloadingStrategy.reset(Foo.class);
        assertThat(foo.foo(), is(FOO));
    }
    assertThat(Class.forName(randomName), notNullValue(Class.class));
}
 
Example #2
Source File: RedissonTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
public void testLeak() throws InterruptedException {
    Config config = new Config();
    config.useSingleServer()
          .setAddress(RedisRunner.getDefaultRedisServerBindAddressAndPort());

    RedissonClient localRedisson = Redisson.create(config);

    String key = RandomString.make(120);
    for (int i = 0; i < 500; i++) {
        RMapCache<String, String> cache = localRedisson.getMapCache("mycache");
        RLock keyLock = cache.getLock(key);
        keyLock.lockInterruptibly(10, TimeUnit.SECONDS);
        try {
            cache.get(key);
            cache.put(key, RandomString.make(4*1024*1024), 5, TimeUnit.SECONDS);
        } finally {
            if (keyLock != null) {
                keyLock.unlock();
            }
        }
    }
    

}
 
Example #3
Source File: AssertFactoryProvider.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
private AssertFactory<Node, SingleNodeAssert> createProxyInstance(JAXPXPathEngine engine) {

        try {
            synchronized (AssertFactoryProvider.class) {
                if (assertFactoryClass == null) {
                    assertFactoryClass = new ByteBuddy()
                            .subclass(AssertFactory.class)
                            .name(NodeAssertFactoryDelegate.class.getPackage().getName() + ".XmlUnit$AssertFactory$" + RandomString.make())
                            .method(ElementMatchers.named("createAssert"))
                            .intercept(MethodDelegation.to(new NodeAssertFactoryDelegate(createDefaultInstance(engine))))
                            .make()
                            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                            .getLoaded();
                }
            }

            @SuppressWarnings("unchecked")
            AssertFactory<Node, SingleNodeAssert> instance = (AssertFactory<Node, SingleNodeAssert>) assertFactoryClass.newInstance();
            return instance;

        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return createDefaultInstance(engine);
    }
 
Example #4
Source File: CachedReturnPlugin.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a plugin for caching method return values.
 */
public CachedReturnPlugin() {
    super(declaresMethod(isAnnotatedWith(Enhance.class)));
    randomString = new RandomString();
    classFileLocator = ClassFileLocator.ForClassLoader.of(CachedReturnPlugin.class.getClassLoader());
    TypePool typePool = TypePool.Default.of(classFileLocator);
    adviceByType = new HashMap<TypeDescription, TypeDescription>();
    for (Class<?> type : new Class<?>[]{
            boolean.class,
            byte.class,
            short.class,
            char.class,
            int.class,
            long.class,
            float.class,
            double.class,
            Object.class
    }) {
        adviceByType.put(TypeDescription.ForLoadedType.ForLoadedType.of(type), typePool.describe(CachedReturnPlugin.class.getName()
                + ADVICE_INFIX
                + type.getSimpleName()).resolve());
    }
}
 
Example #5
Source File: Implementation.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new default implementation context.
 *
 * @param instrumentedType            The description of the type that is currently subject of creation.
 * @param classFileVersion            The class file version of the created class.
 * @param auxiliaryTypeNamingStrategy The naming strategy for naming an auxiliary type.
 * @param typeInitializer             The type initializer of the created instrumented type.
 * @param auxiliaryClassFileVersion   The class file version to use for auxiliary classes.
 */
protected Default(TypeDescription instrumentedType,
                  ClassFileVersion classFileVersion,
                  AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy,
                  TypeInitializer typeInitializer,
                  ClassFileVersion auxiliaryClassFileVersion) {
    super(instrumentedType, classFileVersion);
    this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy;
    this.typeInitializer = typeInitializer;
    this.auxiliaryClassFileVersion = auxiliaryClassFileVersion;
    registeredAccessorMethods = new HashMap<SpecialMethodInvocation, DelegationRecord>();
    registeredGetters = new HashMap<FieldDescription, DelegationRecord>();
    registeredSetters = new HashMap<FieldDescription, DelegationRecord>();
    auxiliaryTypes = new HashMap<AuxiliaryType, DynamicType>();
    registeredFieldCacheEntries = new HashMap<FieldCacheEntry, FieldDescription.InDefinedShape>();
    registeredFieldCacheFields = new HashSet<FieldDescription.InDefinedShape>();
    suffix = RandomString.make();
    fieldCacheCanAppendEntries = true;
}
 
Example #6
Source File: AndroidClassLoadingStrategy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Android class loading strategy that uses the given folder for storing classes. The directory is not cleared
 * by Byte Buddy after the application terminates. This remains the responsibility of the user.
 *
 * @param privateDirectory A directory that is <b>not shared with other applications</b> to be used for storing
 *                         generated classes and their processed forms.
 * @param dexProcessor     The dex processor to be used for creating a dex file out of Java files.
 */
protected AndroidClassLoadingStrategy(File privateDirectory, DexProcessor dexProcessor) {
    if (!privateDirectory.isDirectory()) {
        throw new IllegalArgumentException("Not a directory " + privateDirectory);
    }
    this.privateDirectory = privateDirectory;
    this.dexProcessor = dexProcessor;
    randomString = new RandomString();
}
 
Example #7
Source File: ClassInjector.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instrumentation-based class injector.
 *
 * @param folder          The folder to be used for storing jar files.
 * @param target          A representation of the target path to which classes are to be appended.
 * @param instrumentation The instrumentation to use for appending to the class path or the boot path.
 * @param randomString    The random string generator to use.
 */
protected UsingInstrumentation(File folder,
                               Target target,
                               Instrumentation instrumentation,
                               RandomString randomString) {
    this.folder = folder;
    this.target = target;
    this.instrumentation = instrumentation;
    this.randomString = randomString;
}
 
Example #8
Source File: ClassLoadingStrategyForBootstrapInjectionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
public void testBootstrapInjection() throws Exception {
    ClassLoadingStrategy<ClassLoader> bootstrapStrategy = new ClassLoadingStrategy.ForBootstrapInjection(ByteBuddyAgent.install(), file);
    String name = FOO + RandomString.make();
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> loaded = bootstrapStrategy.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(loaded.size(), is(1));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getClassLoader(), nullValue(ClassLoader.class));
}
 
Example #9
Source File: ClassLoadingStrategyForBootstrapInjectionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
@ClassReflectionInjectionAvailableRule.Enforce
public void testClassLoaderInjection() throws Exception {
    ClassLoadingStrategy<ClassLoader> bootstrapStrategy = new ClassLoadingStrategy.ForBootstrapInjection(ByteBuddyAgent.install(), file);
    String name = BAR + RandomString.make();
    ClassLoader classLoader = new URLClassLoader(new URL[0], null);
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> loaded = bootstrapStrategy.load(classLoader, Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(loaded.size(), is(1));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getClassLoader(), is(classLoader));
}
 
Example #10
Source File: ClassInjectorUsingInstrumentationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    File file = File.createTempFile(FOO, BAR);
    assertThat(file.delete(), is(true));
    folder = new File(file.getParentFile(), RandomString.make());
    assertThat(folder.mkdir(), is(true));
}
 
Example #11
Source File: ClassInjectorUsingInstrumentationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
public void testBootstrapInjection() throws Exception {
    ClassInjector classInjector = ClassInjector.UsingInstrumentation.of(folder,
            ClassInjector.UsingInstrumentation.Target.BOOTSTRAP,
            ByteBuddyAgent.install());
    String name = FOO + RandomString.make();
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> types = classInjector.inject(Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(types.size(), is(1));
    assertThat(types.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(types.get(dynamicType.getTypeDescription()).getClassLoader(), nullValue(ClassLoader.class));
}
 
Example #12
Source File: ClassInjectorUsingInstrumentationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
public void testSystemInjection() throws Exception {
    ClassInjector classInjector = ClassInjector.UsingInstrumentation.of(folder,
            ClassInjector.UsingInstrumentation.Target.SYSTEM,
            ByteBuddyAgent.install());
    String name = BAR + RandomString.make();
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> types = classInjector.inject(Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(types.size(), is(1));
    assertThat(types.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(types.get(dynamicType.getTypeDescription()).getClassLoader(), is(ClassLoader.getSystemClassLoader()));
}
 
Example #13
Source File: DynamicTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
private static File makeTemporaryFolder() throws IOException {
    File file = File.createTempFile(TEMP, TEMP);
    try {
        File folder = new File(file.getParentFile(), TEMP + RandomString.make());
        assertThat(folder.mkdir(), is(true));
        return folder;
    } finally {
        assertThat(file.delete(), is(true));
    }
}
 
Example #14
Source File: AndroidClassLoadingStrategy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public dalvik.system.DexFile loadDex(File privateDirectory,
                                     File jar,
                                     ClassLoader classLoader,
                                     RandomString randomString) throws IOException {
    return dalvik.system.DexFile.loadDex(jar.getAbsolutePath(),
            new File(privateDirectory.getAbsolutePath(), randomString.nextString() + EXTENSION).getAbsolutePath(),
            NO_FLAGS);
}
 
Example #15
Source File: RedissonCodecTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnappyBigV2() throws IOException {
    Codec sc = new SnappyCodecV2();
    String randomData = RandomString.make(Short.MAX_VALUE*2 + 142);
    ByteBuf g = sc.getValueEncoder().encode(randomData);
    String decompressedData = (String) sc.getValueDecoder().decode(g, null);
    assertThat(decompressedData).isEqualTo(randomData);
}
 
Example #16
Source File: RedissonCodecTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnappyBig() throws IOException {
    SnappyCodec sc = new SnappyCodec();
    String randomData = RandomString.make(Short.MAX_VALUE*2 + 142);
    ByteBuf g = sc.getValueEncoder().encode(randomData);
    String decompressedData = (String) sc.getValueDecoder().decode(g, null);
    assertThat(decompressedData).isEqualTo(randomData);
}
 
Example #17
Source File: AccessTokenService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Saves a new {@link AccessToken} for a {@link App}. If the {@link AccessToken} does not
 * have a token it generates a new token for it.
 *
 * @param 	accessTokenPersist 		{@link AccessTokenPersist}
 * @return 						The {@link AccessToken} that was saved to the repository
 */
@Transactional
public AccessToken save(AccessTokenPersist accessTokenPersist) {

     AccessToken accessToken = GenericConverter.mapper(accessTokenPersist, AccessToken.class);

     App appRecover = appRespository.findOne(accessTokenPersist.getApp().getId());
     HeimdallException.checkThrow(appRecover == null, APP_NOT_EXIST);
     HeimdallException.checkThrow(!verifyIfPlansContainsInApp(appRecover, accessTokenPersist.getPlans()), SOME_PLAN_NOT_PRESENT_IN_APP);

     AccessToken existAccessToken;
     if (accessToken.getCode() != null) {

          existAccessToken = accessTokenRepository.findByCode(accessToken.getCode());
          HeimdallException.checkThrow(existAccessToken != null, ACCESS_TOKEN_ALREADY_EXISTS);
     } else {

          RandomString randomString = new RandomString(12);
          String token = randomString.nextString();

          while (accessTokenRepository.findByCode(token) != null) {
       	   token = randomString.nextString();
          }

          accessToken.setCode(token);
     }

     accessToken = accessTokenRepository.save(accessToken);

     return accessToken;
}
 
Example #18
Source File: LaunchShortcutTest.java    From dartboard with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void launchShortcut__DartProjectNoLaunchConfig__NewLaunchConfigIsCreated() throws Exception {
	String projectName = RandomString.make(8);
	String mainClass = RandomString.make(4) + ".dart";
	ProjectUtil.createDartProject(projectName);

	ProjectExplorer projectExplorer = new ProjectExplorer();
	projectExplorer.open();
	projectExplorer.getProject(projectName).select();

	new ContextMenuItem(new WithMnemonicTextMatcher("Run As"), new RegexMatcher("\\d Run as Dart Program"))
			.select();

	new WaitUntil(new ShellIsActive("Edit Configuration"));
	new LabeledCombo("Project:").setSelection(projectName);
	new LabeledText("Main class:").setText(mainClass);
	new PushButton("Run").click();
	ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();

	// Find last launch configuration for selected project.
	ILaunchConfiguration launchConfiguration = null;
	for (ILaunchConfiguration conf : manager.getLaunchConfigurations()) {
		if (conf.getAttribute(Constants.LAUNCH_SELECTED_PROJECT, "").equalsIgnoreCase(projectName)) { //$NON-NLS-1$
			launchConfiguration = conf;
		}
	}

	assertNotNull(launchConfiguration);
	assertEquals(launchConfiguration.getAttribute("main_class", ""), mainClass);

	// Cleanup
	launchConfiguration.delete();
}
 
Example #19
Source File: PubGetHandlerTest.java    From dartboard with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setup() {
	projectName = RandomString.make(8);
}
 
Example #20
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Composable setsReference(Object value) {
    return setsReference(value, ForSetter.OfReferenceValue.PREFIX + "$" + RandomString.hashOf(value.hashCode()));
}
 
Example #21
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates any intercepted method to invoke a non-{@code static} method that is declared by the supplied type's instance or any
 * of its super types. To be considered a valid delegation target, a method must be visible and accessible to the instrumented type.
 * This is the case if the method's declaring type is either public or in the same package as the instrumented type and if the method
 * is either public or non-private and in the same package as the instrumented type. Private methods can only be used as
 * a delegation target if the delegation is targeting the instrumented type.
 *
 * @param target              The target instance for the delegation.
 * @param typeDefinition      The most specific type of which {@code target} should be considered. Must be a super type of the target's actual type.
 * @param methodGraphCompiler The method graph compiler to use.
 * @return A method delegation that redirects method calls to a static method of the supplied type.
 */
public MethodDelegation to(Object target, TypeDefinition typeDefinition, MethodGraph.Compiler methodGraphCompiler) {
    return to(target,
            typeDefinition,
            ImplementationDelegate.FIELD_NAME_PREFIX + "$" + RandomString.hashOf(target.hashCode()),
            methodGraphCompiler);
}
 
Example #22
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates any intercepted method to invoke a non-{@code static} method that is declared by the supplied type's instance or any
 * of its super types. To be considered a valid delegation target, a method must be visible and accessible to the instrumented type.
 * This is the case if the method's declaring type is either public or in the same package as the instrumented type and if the method
 * is either public or non-private and in the same package as the instrumented type. Private methods can only be used as
 * a delegation target if the delegation is targeting the instrumented type.
 *
 * @param target              The target instance for the delegation.
 * @param type                The most specific type of which {@code target} should be considered. Must be a super type of the target's actual type.
 * @param methodGraphCompiler The method graph compiler to use.
 * @return A method delegation that redirects method calls to a static method of the supplied type.
 */
public MethodDelegation to(Object target, Type type, MethodGraph.Compiler methodGraphCompiler) {
    return to(target,
            type,
            ImplementationDelegate.FIELD_NAME_PREFIX + "$" + RandomString.hashOf(target.hashCode()),
            methodGraphCompiler);
}
 
Example #23
Source File: NamingStrategy.java    From byte-buddy with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an immutable naming strategy with a given suffix but moves types that subclass types within
 * the {@code java.lang} package into a given namespace.
 *
 * @param suffix                The suffix for the generated class.
 * @param baseNameResolver      The base name resolver that is queried for locating the base name.
 * @param javaLangPackagePrefix The fallback namespace for type's that subclass types within the
 *                              {@code java.*} namespace. If The prefix is set to the empty string,
 *                              no prefix is added.
 */
public SuffixingRandom(String suffix, BaseNameResolver baseNameResolver, String javaLangPackagePrefix) {
    this.suffix = suffix;
    this.baseNameResolver = baseNameResolver;
    this.javaLangPackagePrefix = javaLangPackagePrefix;
    randomString = new RandomString();
}
 
Example #24
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new argument provider that stores the given value in a static field.
 *
 * @param value     The value that is to be provided to the bootstrapped method.
 * @param fieldType The type of the field which is also provided to the bootstrap method.
 */
protected ForInstance(Object value, TypeDescription fieldType) {
    this.value = value;
    this.fieldType = fieldType;
    name = FIELD_PREFIX + "$" + RandomString.make();
}
 
Example #25
Source File: FixedValue.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new static field fixed value implementation with a random name for the field containing the fixed
 * value.
 *
 * @param value The fixed value to be returned.
 */
protected ForValue(Object value) {
    this(PREFIX + "$" + RandomString.hashOf(value.hashCode()), value);
}
 
Example #26
Source File: ClassInjector.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an instrumentation-based class injector.
 *
 * @param folder          The folder to be used for storing jar files.
 * @param target          A representation of the target path to which classes are to be appended.
 * @param instrumentation The instrumentation to use for appending to the class path or the boot path.
 * @return An appropriate class injector that applies instrumentation.
 */
public static ClassInjector of(File folder, Target target, Instrumentation instrumentation) {
    return new UsingInstrumentation(folder, target, instrumentation, new RandomString());
}
 
Example #27
Source File: MethodNameTransformer.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new suffixing method name transformer which adds a default suffix with a random name component.
 *
 * @return A method name transformer that adds a randomized suffix to the original method name.
 */
public static MethodNameTransformer withRandomSuffix() {
    return new Suffixing(DEFAULT_SUFFIX + RandomString.make());
}
 
Example #28
Source File: AuxiliaryType.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new suffixing random naming strategy.
 *
 * @param suffix The suffix to extend to the instrumented type.
 */
public SuffixingRandom(String suffix) {
    this.suffix = suffix;
    randomString = new RandomString();
}
 
Example #29
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new target handler for a static field.
 *
 * @param target    The target on which the method is to be invoked.
 * @param fieldType The type of the field.
 */
protected Factory(Object target, TypeDescription.Generic fieldType) {
    this.target = target;
    this.fieldType = fieldType;
    name = FIELD_PREFIX + "$" + RandomString.make();
}
 
Example #30
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a factory that loads the value of a static field as an argument.
 *
 * @param value The value to supply as an argument.
 */
public Factory(Object value) {
    this.value = value;
    name = FIELD_PREFIX + "$" + RandomString.make();
}