# [jQuery UI](http://jqueryui.com/) - Interactions and Widgets for the web jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of jQuery. Whether you're building highly interactive web applications, or you just need to add a date picker to a form control, jQuery UI is the perfect choice. If you want to use jQuery UI, go to [jqueryui.com](http://jqueryui.com) to get started, [jqueryui.com/demos/](http://jqueryui.com/demos/) for demos, [api.jqueryui.com](http://api.jqueryui.com/) for API documentation, or the [Using jQuery UI Forum](http://forum.jquery.com/using-jquery-ui) for discussions and questions. If you want to report a bug/issue, please visit [bugs.jqueryui.com](http://bugs.jqueryui.com). If you are interested in helping develop jQuery UI, you are in the right place. To discuss development with team members and the community, visit the [Developing jQuery UI Forum](http://forum.jquery.com/developing-jquery-ui) or [#jqueryui-dev on irc.freenode.net](http://irc.jquery.org/). ## For Contributors If you want to help and provide a patch for a bugfix or new feature, please take a few minutes and look at [our Getting Involved guide](http://wiki.jqueryui.com/w/page/35263114/Getting-Involved). In particular check out the [Coding standards](http://wiki.jqueryui.com/w/page/12137737/Coding-standards) and [Commit Message Style Guide](http://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines). In general, fork the project, create a branch for a specific change and send a pull request for that branch. Don't mix unrelated changes. You can use the commit message as the description for the pull request. For more information, see the [contributing page](CONTRIBUTING.md). ## Running the Unit Tests Run the unit tests manually with appropriate browsers and any local web server. See our [environment setup](CONTRIBUTING.md#environment-minimum-required) and [information on running tests](CONTRIBUTING.md#running-the-tests). You can also run the unit tests inside phantomjs by [setting up your environment](CONTRIBUTING.md#user-content-environment-recommended-setup).
path: root/src/main/javassist/util/HotSwapAgent.java
blob: 5bfbe53c23ec6c78d6c289b1bf0a66e3a149be21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
 * Javassist, a Java-bytecode translator toolkit.
 * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License.  Alternatively, the contents of this file may be used under
 * the terms of the GNU Lesser General Public License Version 2.1 or later,
 * or the Apache License Version 2.0.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 */
package javassist.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.lang.management.ManagementFactory;
import com.sun.tools.attach.VirtualMachine;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;

/**
 * A utility class for dynamically adding a new method
 * or modifying an existing method body.
 * This class provides {@link #redefine(Class, CtClass)}
 * and {@link #redefine(Class[], CtClass[])}, which replace the
 * existing class definition with a new one.
 * These methods perform the replacement by
 * {@code java.lang.instrument.Instrumentation}.  For details
 * of acceptable modification,
 * see the {@code Instrumentation} interface.
 *
 * <p>Before calling the {@code redefine} methods, the hotswap agent
 * has to be deployed.</p>
 *
 * <p>To create a hotswap agent, run {@link #createAgentJarFile(String)}.
 * For example, the following command creates an agent file named {@code hotswap.jar}.
 *
 * <pre>
 * $ jshell --class-path javassist.jar
 * jshell> javassist.util.HotSwapAgent.createAgentJarFile("hotswap.jar") 
 * </pre>
 *
 * <p>Then, run the JVM with the VM argument {@code -javaagent:hotswap.jar}
 * to deploy the hotswap agent.
 * </p>
 *
 * <p>If the {@code -javaagent} option is not given to the JVM, {@code HotSwapAgent}
 * attempts to automatically create and start the hotswap agent on demand.
 * This automated deployment may fail.  If it fails, manually create the hotswap agent
 * and deploy it by {@code -javaagent}.</p>
 *
 * <p>The {@code HotSwapAgent} requires {@code tools.jar} as well as {@code javassist.jar}.</p>
 * 
 * <p>The idea of this class was given by <a href="https://github.com/alugowski">Adam Lugowski</a>.
 * Shigeru Chiba wrote this class by referring
 * to his <a href="https://github.com/turn/RedefineClassAgent">{@code RedefineClassAgent}</a>.
 * For details, see <a href="https://github.com/jboss-javassist/javassist/issues/119">this discussion</a>. 
 * </p>
 *
 * @see #redefine(Class, CtClass)
 * @see #redefine(Class[], CtClass[])
 * @since 3.22
 */
public class HotSwapAgent {
    private static Instrumentation instrumentation = null;

    /**
     * Obtains the {@code Instrumentation} object.
     *
     * @return null             when it is not available. 
     */
    public Instrumentation instrumentation() { return instrumentation; }

    /**
     * The entry point invoked when this agent is started by {@code -javaagent}. 
     */
    public static void premain(String agentArgs, Instrumentation inst) throws Throwable {
        agentmain(agentArgs, inst);
    }

    /**
     * The entry point invoked when this agent is started after the JVM starts.
     */
    public static void agentmain(String agentArgs, Instrumentation inst) throws Throwable {
        if (!inst.isRedefineClassesSupported())
            throw new RuntimeException("this JVM does not support redefinition of classes");

        instrumentation = inst;
    }

    /**
     * Redefines a class.
     */
    public static void redefine(Class oldClass, CtClass newClass)
        throws NotFoundException, IOException, CannotCompileException
    {
        Class[] old = { oldClass };
        CtClass[] newClasses = { newClass };
        redefine(old, newClasses);
    }

    /**
     * Redefines classes.
     */
    public static void redefine(Class[] oldClasses, CtClass[] newClasses)
        throws NotFoundException, IOException, CannotCompileException
    {
        startAgent();
        ClassDefinition[] defs = new ClassDefinition[oldClasses.length];
        for (int i = 0; i < oldClasses.length; i++)
            defs[i] = new ClassDefinition(oldClasses[i], newClasses[i].toBytecode());

        try {
            instrumentation.redefineClasses(defs);
        }
        catch (ClassNotFoundException e) {
            throw new NotFoundException(e.getMessage(), e);
        }
        catch (UnmodifiableClassException e) {
            throw new CannotCompileException(e.getMessage(), e);
        }
    }

    /**
     * Ensures that the agent is ready.
     * It attempts to dynamically start the agent if necessary.
     */
    private static void startAgent() throws NotFoundException {
        if (instrumentation != null)
            return;

        try {
            File agentJar = createJarFile();

            String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
            String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));

            VirtualMachine vm = VirtualMachine.attach(pid);
            vm.loadAgent(agentJar.getAbsolutePath(), "");
            vm.detach();
        }
        catch (Exception e) {
            throw new NotFoundException("hotswap agent", e);
        }

        for (int sec = 0; sec < 10 /* sec */; sec++) {
            if (instrumentation != null)
                return;

            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        throw new NotFoundException("hotswap agent (timeout)");
    }

    /**
     * Creates an agent file for using {@code HotSwapAgent}. 
     */
    public static File createAgentJarFile(String fileName)
        throws IOException, CannotCompileException, NotFoundException
    {
        return createJarFile(new File(fileName));
    }

    private static File createJarFile()
        throws IOException, CannotCompileException, NotFoundException
    {
        File jar = File.createTempFile("agent", ".jar");
        jar.deleteOnExit();
        return createJarFile(jar);
    }

    private static File createJarFile(File jar)
        throws IOException, CannotCompileException, NotFoundException
    {
        Manifest manifest = new Manifest();
        Attributes attrs = manifest.getMainAttributes();
        attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        attrs.put(new Attributes.Name("Premain-Class"), HotSwapAgent.class.getName());
        attrs.put(new Attributes.Name("Agent-Class"), HotSwapAgent.class.getName());
        attrs.put(new Attributes.Name("Can-Retransform-Classes"), "true");
        attrs.put(new Attributes.Name("Can-Redefine-Classes"), "true");

        JarOutputStream jos = null;
        try {
            jos = new JarOutputStream(new FileOutputStream(jar), manifest);
            String cname = HotSwapAgent.class.getName();
            JarEntry e = new JarEntry(cname.replace('.', '/') + ".class");
            jos.putNextEntry(e);
            ClassPool pool = ClassPool.getDefault();
            CtClass clazz = pool.get(cname);
            jos.write(clazz.toBytecode());
            jos.closeEntry();
        }
        finally {
            if (jos != null)
                jos.close();
        }

        return jar;
    }
}