Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / tools / development / agent / impl / AgentImpl.java
blobd1425fb19bb8683af5cda0556f1410b21ae5ca8d
1 // Copyright 2009 Google Inc. All Rights Reserved.
3 package com.google.appengine.tools.development.agent.impl;
5 import java.lang.instrument.Instrumentation;
6 import java.lang.ref.ReferenceQueue;
7 import java.lang.ref.WeakReference;
8 import java.util.HashSet;
9 import java.util.Iterator;
10 import java.util.Set;
12 /**
13 * Performs the actual agent work.
16 public class AgentImpl implements Agent {
18 static final String AGENT_RUNTIME =
19 "com/google/appengine/tools/development/agent/runtime/Runtime";
21 private static final AgentImpl instance = new AgentImpl();
23 private final Set<ClassLoaderReference> appUrlClassLoaders = new HashSet<ClassLoaderReference>();
24 private final ReferenceQueue<ClassLoader> classLoaderReferenceQueue =
25 new ReferenceQueue<ClassLoader>();
27 public void run(Instrumentation instrumentation,
28 boolean treatRestrictedClassListViolationsAsErrors) {
29 instrumentation.addTransformer(new Transformer(treatRestrictedClassListViolationsAsErrors));
32 @Override
33 public Set<String> getBlackList() {
34 return BlackList.getBlackList();
37 @Override
38 public synchronized void recordAppClassLoader(ClassLoader loader) {
39 prune();
40 appUrlClassLoaders.add(new ClassLoaderReference(loader));
43 public static AgentImpl getInstance() {
44 return instance;
47 private AgentImpl() {
48 if (instance != null) {
49 throw new IllegalStateException("There can only be one AgentImpl");
53 public synchronized boolean isAppConstructedURLClassLoader(ClassLoader loader) {
54 prune();
55 return appUrlClassLoaders.contains(new ClassLoaderReference(loader));
58 private void prune() {
59 boolean any = false;
60 while (classLoaderReferenceQueue.poll() != null) {
61 any = true;
63 if (any) {
64 for (Iterator<ClassLoaderReference> it = appUrlClassLoaders.iterator(); it.hasNext(); ) {
65 ClassLoaderReference classLoaderReference = it.next();
66 if (classLoaderReference.get() == null) {
67 it.remove();
73 private class ClassLoaderReference {
74 private final WeakReference<ClassLoader> classLoaderReference;
75 private final int hashCode;
77 ClassLoaderReference(ClassLoader classLoader) {
78 this.classLoaderReference =
79 new WeakReference<ClassLoader>(classLoader, classLoaderReferenceQueue);
80 this.hashCode = System.identityHashCode(classLoader);
83 ClassLoader get() {
84 return classLoaderReference.get();
87 @Override
88 public boolean equals(Object obj) {
89 if (obj instanceof ClassLoaderReference) {
90 ClassLoaderReference that = (ClassLoaderReference) obj;
91 return get() == that.get();
92 } else {
93 return false;
97 @Override
98 public int hashCode() {
99 return hashCode;