當前位置: 首頁>>代碼示例>>Java>>正文


Java Instrumentation類代碼示例

本文整理匯總了Java中java.lang.instrument.Instrumentation的典型用法代碼示例。如果您正苦於以下問題:Java Instrumentation類的具體用法?Java Instrumentation怎麽用?Java Instrumentation使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Instrumentation類屬於java.lang.instrument包,在下文中一共展示了Instrumentation類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: initTransformer

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
/**
 * 初始化類字節碼的轉換器
 *
 * @param inst 用於管理字節碼轉換器
 */
private static void initTransformer(Instrumentation inst) throws UnmodifiableClassException {
    LinkedList<Class> retransformClasses = new LinkedList<Class>();
    CustomClassTransformer customClassTransformer = new CustomClassTransformer();
    inst.addTransformer(customClassTransformer, true);
    Class[] loadedClasses = inst.getAllLoadedClasses();
    for (Class clazz : loadedClasses) {
        for (final AbstractClassHook hook : customClassTransformer.getHooks()) {
            if (hook.isClassMatched(clazz.getName().replace(".", "/"))) {
                if (inst.isModifiableClass(clazz) && !clazz.getName().startsWith("java.lang.invoke.LambdaForm")) {
                    retransformClasses.add(clazz);
                }
            }
        }
    }
    // hook已經加載的類
    Class[] classes = new Class[retransformClasses.size()];
    retransformClasses.toArray(classes);
    if (classes.length > 0) {
        inst.retransformClasses(classes);
    }
}
 
開發者ID:baidu,項目名稱:openrasp,代碼行數:27,代碼來源:Agent.java

示例2: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
/**
 * 啟動時加載的agent入口方法
 *
 * @param agentArg 啟動參數
 * @param inst     {@link Instrumentation}
 */
public static void premain(String agentArg, Instrumentation inst) {
    try {
        JarFileHelper.addJarToBootstrap(inst);
        if (!loadConfig(JarFileHelper.getLocalJarParentPath())) {
            return;
        }
        readVersion();
        // 初始化插件係統
        JsPluginManager.init();
        CheckerManager.init();
        initTransformer(inst);
        String message = "OpenRasp Initialized [" + projectVersion + " (build: GitCommit=" + gitCommit + " date="
                + buildTime + ")]";
        System.out.println(message);
        Logger.getLogger(Agent.class.getName()).info(message);
        HookHandler.enableHook.set(true);
    } catch (Exception e) {
        System.out.println("[OpenRASP] Failed to initialize, will continue without security protection.");

        e.printStackTrace();
    }
}
 
開發者ID:baidu,項目名稱:openrasp,代碼行數:29,代碼來源:Agent.java

示例3: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String agentArg, Instrumentation inst)
{
    String[] args = agentArg.split(":");
    if (args.length > 2) {
        System.err.println(USAGE);
    }

    int port = 7400;
    try {
        port = Integer.parseInt(args[0]);
    } catch(Exception e) {
        System.err.println(USAGE + ". No port specified so using default port for cassandra prometheus exporter " + port);
    }

    String path = "metrics";
    if (args.length == 2) {
        if (args[1].length() > 0) {
            path = args[1];
        } else {
            System.err.println(USAGE + ". Invalid path defined so using default path for cassandra prometheus exporter: " + path);
        }
    }

    PrometheusExporter exp = new PrometheusExporter(port, path);
}
 
開發者ID:nabto,項目名稱:cassandra-prometheus,代碼行數:26,代碼來源:Exporter.java

示例4: initManager

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
private void initManager(final Instrumentation inst,
                         final CoreConfigure cfg) {

    logger.debug("{} was init", EventListenerHandlers.getSingleton());

    final ModuleLifeCycleEventBus moduleLifeCycleEventBus = new DefaultModuleLifeCycleEventBus();
    final LoadedClassDataSource classDataSource = new DefaultLoadedClassDataSource(inst);
    final ClassLoader sandboxClassLoader = getClass().getClassLoader();

    // 初始化模塊資源管理器
    this.moduleResourceManager = new DefaultModuleResourceManager();
    moduleLifeCycleEventBus.append(this.moduleResourceManager);

    // 初始化服務管理器
    final ProviderManager providerManager = new DefaultProviderManager(cfg, sandboxClassLoader);

    // 初始化模塊管理器
    this.coreModuleManager = new DefaultCoreModuleManager(
            inst, classDataSource, cfg, sandboxClassLoader, moduleLifeCycleEventBus, providerManager
    );
}
 
開發者ID:alibaba,項目名稱:jvm-sandbox,代碼行數:22,代碼來源:JettyCoreServer.java

示例5: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String agentArgs, Instrumentation inst) {
    System.out.println("Hello from RedefineMethodInBacktraceAgent!");
    System.out.println("isRedefineClassesSupported()=" +
            inst.isRedefineClassesSupported());

    instrumentation = inst;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:8,代碼來源:RedefineMethodInBacktraceAgent.java

示例6: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String args, Instrumentation instrumentation) {
    if (!instrumentation.isRetransformClassesSupported()) {
        System.out.println("Class retransformation is not supported.");
        return;
    }
    System.out.println("Calling lambda to ensure that lambda forms were created");

    Agent.lambda.run();

    System.out.println("Registering class file transformer");

    instrumentation.addTransformer(new Agent());

    for (Class c : instrumentation.getAllLoadedClasses()) {
        if (c.getName().contains("LambdaForm") &&
            instrumentation.isModifiableClass(c)) {
            System.out.format("We've found a modifiable lambda form: %s%n", c.getName());
            try {
                instrumentation.retransformClasses(c);
            } catch (UnmodifiableClassException e) {
                throw new AssertionError("Modification of modifiable class " +
                                         "caused UnmodifiableClassException", e);
            }
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:TestLambdaFormRetransformation.java

示例7: testAddReads

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
/**
 * Use redefineModule to update java.base to read java.instrument
 */
public void testAddReads() {
    Module baseModule = Object.class.getModule();
    Module instrumentModule = Instrumentation.class.getModule();

    // pre-conditions
    assertFalse(baseModule.canRead(instrumentModule));

    // update java.base to read java.instrument
    Set<Module> extraReads = Set.of(instrumentModule);
    redefineModule(baseModule, extraReads, Map.of(), Map.of(), Set.of(), Map.of());
    assertTrue(baseModule.canRead(instrumentModule));
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:16,代碼來源:RedefineModuleTest.java

示例8: agentmain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
/**
 * 動態加載
 *
 * @param featureString 啟動參數
 *                      [namespace,token,ip,port,prop]
 * @param inst          inst
 */
public static void agentmain(String featureString, Instrumentation inst) {
    LAUNCH_MODE = LAUNCH_MODE_ATTACH;
    final Map<String, String> featureMap = toFeatureMap(featureString);
    writeAttachResult(
            getNamespace(featureMap),
            getToken(featureMap),
            main(featureMap, inst)
    );
}
 
開發者ID:alibaba,項目名稱:jvm-sandbox,代碼行數:17,代碼來源:AgentLauncher.java

示例9: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(final String args, Instrumentation instrumentation) throws Exception {
    instrumentation.addTransformer(new MenuItemTransformer());
    instrumentation.addTransformer(new FileChooserTransformer());
    logger.info("JavaVersion: " + System.getProperty("java.version"));
    final int port;
    if (args != null && args.trim().length() > 0) {
        port = Integer.parseInt(args.trim());
    } else {
        throw new Exception("Port number not specified");
    }
    windowTitle = System.getProperty("start.window.title", "");
    ObservableList<Stage> stages = StageHelper.getStages();
    stages.addListener(new ListChangeListener<Stage>() {
        boolean done = false;

        @Override public void onChanged(javafx.collections.ListChangeListener.Change<? extends Stage> c) {
            if (done) {
                return;
            }
            if (!"".equals(windowTitle)) {
                logger.warning("WindowTitle is not supported yet... Ignoring it.");
            }
            c.next();
            if (c.wasAdded()) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    @Override public Object run() {
                        return new JavaFxRecorderHook(port);
                    }
                });
                done = true;
            }
        }
    });
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:35,代碼來源:JavaFxRecorderHook.java

示例10: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String agentArgs, Instrumentation inst) {
        try {
            PromagentCollectorRegistry registry = new PromagentCollectorRegistry();
            ManagementFactory.getPlatformMBeanServer().registerMBean(new Exporter(registry), new ObjectName("io.promagent:type=exporter"));
            Map<String, String> args = parseCmdline(agentArgs);
            if (args.containsKey("port")) {
                BuiltInServer.run(args.get("host"), args.get("port"), registry);
            }
            ClassLoaderCache classLoaderCache = ClassLoaderCache.getInstance();
            List<Path> hookJars = classLoaderCache.getPerDeploymentJars();
            SortedSet<HookMetadata> hookMetadata = new HookMetadataParser(hookJars).parse();
            MetricsStore metricsStore = new MetricsStore(registry);
            Delegator.init(hookMetadata, metricsStore, classLoaderCache);
            printHookMetadata(hookMetadata);

            AgentBuilder agentBuilder = new AgentBuilder.Default()
                    .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
                    .with(AgentBuilder.TypeStrategy.Default.REDEFINE);
                    // .with(AgentBuilder.Listener.StreamWriting.toSystemError()); // use this to see exceptions thrown in instrumented code
            agentBuilder = applyHooks(agentBuilder, hookMetadata, classLoaderCache);
            agentBuilder.installOn(inst);

            // TODO -- the following is an experiment supporting collectors directly (in addition to hooks)
//            io.prometheus.client.Collector jmxCollector = (io.prometheus.client.Collector) classLoaderCache.currentClassLoader().loadClass("io.promagent.collectors.JmxCollector").newInstance();
//            registry.registerNoJmx(jmxCollector);

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
 
開發者ID:fstab,項目名稱:promagent,代碼行數:31,代碼來源:Promagent.java

示例11: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String arg, Instrumentation instrumentation) {
	try {
		log("launched from javaagent");
		if (arg != null && !arg.isEmpty()) {
			System.setProperty("org.to2mbn.authlibinjector.config", arg);
		}
		bootstrap(instrumentation::addTransformer);
	} catch (Throwable e) {
		// prevent the exception being thrown to VM
		e.printStackTrace();
	}
}
 
開發者ID:to2mbn,項目名稱:authlib-injector,代碼行數:13,代碼來源:AuthlibInjectorPremain.java

示例12: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(final String args, final Instrumentation instrumentation) throws Exception {

        final BootstrapConfiguration configuration = getConfigurationFromFile();
        loadMavenArtifacts(instrumentation, configuration);
        loadClassPathFiles(instrumentation, configuration.files);
        loadClassPathUrlsAsString(instrumentation, configuration.urls);
        loadShutdownHooks(configuration);
        loadApplicationBootstrapClassName(configuration);
    }
 
開發者ID:stacs-srg,項目名稱:shabdiz,代碼行數:10,代碼來源:Bootstrap.java

示例13: loadMavenArtifacts

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
private static void loadMavenArtifacts(final Instrumentation instrumentation, final BootstrapConfiguration configuration) throws Exception {

        if (configuration.hasMavenArtifact()) {
            initMavenDependencyResolver(instrumentation);
            addMavenRepositories(configuration.maven_repositories);
            resolveAndLoadMavenArtifacts(instrumentation, configuration.maven_artifacts);
        }
    }
 
開發者ID:stacs-srg,項目名稱:shabdiz,代碼行數:9,代碼來源:Bootstrap.java

示例14: DefaultCoreModuleManager

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
/**
 * 模塊模塊管理
 *
 * @param inst                    inst
 * @param classDataSource         已加載類數據源
 * @param cfg                     模塊核心配置
 * @param sandboxClassLoader      沙箱加載ClassLoader
 * @param moduleLifeCycleEventBus 模塊生命周期通知總線
 * @param providerManager         服務提供者管理器
 */
public DefaultCoreModuleManager(final Instrumentation inst,
                                final LoadedClassDataSource classDataSource,
                                final CoreConfigure cfg,
                                final ClassLoader sandboxClassLoader,
                                final ModuleLifeCycleEventBus moduleLifeCycleEventBus,
                                final ProviderManager providerManager) {
    this.inst = inst;
    this.classDataSource = classDataSource;
    this.cfg = cfg;
    this.sandboxClassLoader = sandboxClassLoader;
    this.moduleLifeCycleEventBus = moduleLifeCycleEventBus;
    this.providerManager = providerManager;

    // 初始化模塊目錄
    this.moduleLibDirArray = mergeFileArray(
            new File[]{new File(cfg.getSystemModuleLibPath())},
            cfg.getUserModuleLibFilesWithCache()
    );

    // 初始化加載所有的模塊
    try {
        reset();
    } catch (ModuleException e) {
        logger.warn("init module[id={};] occur error={}.", e.getUniqueId(), e.getErrorCode(), e);
    }
}
 
開發者ID:alibaba,項目名稱:jvm-sandbox,代碼行數:37,代碼來源:DefaultCoreModuleManager.java

示例15: premain

import java.lang.instrument.Instrumentation; //導入依賴的package包/類
public static void premain(String agentArgs, Instrumentation inst) {
    System.out.println("Hello from ManifestTestAgent!");
    System.out.println("isNativeMethodPrefixSupported()=" +
        inst.isNativeMethodPrefixSupported());
    System.out.println("isRedefineClassesSupported()=" +
        inst.isRedefineClassesSupported());
    System.out.println("isRetransformClassesSupported()=" +
        inst.isRetransformClassesSupported());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:10,代碼來源:ManifestTestAgent.java


注:本文中的java.lang.instrument.Instrumentation類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。