!Unknownsymbol! when writing java class for sonarqube - java

Hi StackOverflow community,
I am new to writing custom rules for java in SonarQube.
I am writing a custom rule to detect certain interfaces being in used via maven. However, during testing, "!unknownSymbol!" came out instead of the Interface classes being implemented by the test case.
In my test case, I have written a class which implements 2 interfaces: -
- java.util.List
- org.osgi.framework.BundleActivator
The test can detect both interfaces, but when I convert it into a symbolTree then use the method fullyQualifiedName(), it returns "!unknownSymbol!". However, when I am doing a simple toString() it returns the interface name.
I would like to know how to correctly convert it into a symbolTree object and get the correct interface without encountering "!unknownSymbol!"
Thank you very much.
The code:
package org.sonar.samples.java.checks;
import com.google.common.collect.ImmutableList;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.ListTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TypeTree;
import java.util.List;
#Rule(
key = "AvoidInterfaceClass",
name = "No Interfaces",
description = "Not allowed to implement any interface(s)",
priority = Priority.MAJOR
)
public class AvoidSuperInterfacesRule extends IssuableSubscriptionVisitor {
public static final List<String> SUPER_INTERFACE_AVOID = ImmutableList.of("org.osgi.framework.BundleActivator","java.util.List");
#Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.CLASS);
}
public void visitNode(Tree tree){
//System.out.println("Here");
ClassTree treeClass = (ClassTree) tree;
if (treeClass.superInterfaces().isEmpty()) {
return;
}
ListTree<TypeTree> superInterfaceNames = treeClass.superInterfaces();
System.out.println(superInterfaceNames.size()); //Number of interfaces
System.out.println();
for (TypeTree t:superInterfaceNames){
String name = t.symbolType().fullyQualifiedName();
System.out.println(name);
System.out.println(t.toString());
System.out.println();
if (SUPER_INTERFACE_AVOID.contains(name)){
reportIssue(t, "This interface is not allowed to be implemented.");
}
}
}
}
The output:
09:18:36.332 [main] INFO org.sonar.squidbridge.ProgressReport - 1 source files to be analyzed
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - ----- Classpath analyzed by Squid:
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\commons-collections4-4.0.jar
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\javaee-api-6.0.jar
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-context-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-web-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-webmvc-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-classes
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - -----
2 -> Number of Interfaces
!unknownSymbol! -> symbolType.getFullyQualifiedName()
BundleActivator -> toString()
!unknownSymbol! -> symbolType.getFullyQualifiedName()
List -> toString()
09:18:36.798 [Report about progress of Java AST analyzer] INFO org.sonar.squidbridge.ProgressReport - 1/1 source files have been analyzed

Related

Broadleaf Commerce Embedded Solr cannot run with root user

I download a fresh 6.1 broadleaf-commerce and run my local machine via java -javaagent:./admin/target/agents/spring-instrument.jar -jar admin/target/admin.jar successfully on mine macbook. But in my centos 7 I run sudo java -javaagent:./admin/target/agents/spring-instrument.jar -jar admin/target/admin.jar with following error
2020-10-12 13:20:10.838 INFO 2481 --- [ main] c.b.solr.autoconfigure.SolrServer : Syncing solr config file: jar:file:/home/mynewuser/seafood-broadleaf/admin/target/admin.jar!/BOOT-INF/lib/broadleaf-boot-starter-solr-2.2.1-GA.jar!/solr/standalone/solrhome/configsets/fulfillment_order/conf/solrconfig.xml to: /tmp/solr-7.7.2/solr-7.7.2/server/solr/configsets/fulfillment_order/conf/solrconfig.xml
*** [WARN] *** Your Max Processes Limit is currently 62383.
It should be set to 65000 to avoid operational disruption.
If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
WARNING: Starting Solr as the root user is a security risk and not considered best practice. Exiting.
Please consult the Reference Guide. To override this check, start with argument '-force'
2020-10-12 13:20:11.021 ERROR 2481 --- [ main] c.b.solr.autoconfigure.SolrServer : Problem starting Solr
Here is the source code of solr configuration, I believe it is the place to change the configuration to run with the argument -force in programming way.
package com.community.core.config;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.broadleafcommerce.core.search.service.SearchService;
import org.broadleafcommerce.core.search.service.solr.SolrConfiguration;
import org.broadleafcommerce.core.search.service.solr.SolrSearchServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
*
*
* #author Phillip Verheyden (phillipuniverse)
*/
#Component
public class ApplicationSolrConfiguration {
#Value("${solr.url.primary}")
protected String primaryCatalogSolrUrl;
#Value("${solr.url.reindex}")
protected String reindexCatalogSolrUrl;
#Value("${solr.url.admin}")
protected String adminCatalogSolrUrl;
#Bean
public SolrClient primaryCatalogSolrClient() {
return new HttpSolrClient.Builder(primaryCatalogSolrUrl).build();
}
#Bean
public SolrClient reindexCatalogSolrClient() {
return new HttpSolrClient.Builder(reindexCatalogSolrUrl).build();
}
#Bean
public SolrClient adminCatalogSolrClient() {
return new HttpSolrClient.Builder(adminCatalogSolrUrl).build();
}
#Bean
public SolrConfiguration blCatalogSolrConfiguration() throws IllegalStateException {
return new SolrConfiguration(primaryCatalogSolrClient(), reindexCatalogSolrClient(), adminCatalogSolrClient());
}
#Bean
protected SearchService blSearchService() {
return new SolrSearchServiceImpl();
}
}
Let me preface this by saying you would be better off simply not starting the application as root. If you are in Docker, you can use the USER command to switch to a non-root user.
The Solr server startup in Broadleaf Community is done programmatically via the broadleaf-boot-starter-solr dependency. This is the wrapper around Solr that ties it to the Spring lifecycle. All of the real magic happens in the com.broadleafcommerce.solr.autoconfigure.SolrServer class.
In that class, you will see a startSolr() method. This method is what adds startup arguments to Solr.
In your case, you will need to mostly copy this method wholesale and use cmdLine.addArgument(...) to add additional arguments. Example:
class ForceStartupSolrServer extends SolrServer {
public ForceStartupSolrServer(SolrProperties props) {
super(props);
}
protected void startSolr() {
if (!isRunning()) {
if (!downloadSolrIfApplicable()) {
throw new IllegalStateException("Could not download or expand Solr, see previous logs for more information");
}
stopSolr();
synchConfig();
{
CommandLine cmdLine = new CommandLine(getSolrCommand());
cmdLine.addArgument("start");
cmdLine.addArgument("-p");
cmdLine.addArgument(Integer.toString(props.getPort()));
// START MODIFICATION
cmdLine.addArgument("-force");
// END MODIFICATION
Executor executor = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(System.out);
streamHandler.setStopTimeout(1000);
executor.setStreamHandler(streamHandler);
try {
executor.execute(cmdLine);
created = true;
checkCoreStatus();
} catch (IOException e) {
LOG.error("Problem starting Solr", e);
}
}
}
}
}
Then create an #Configuration class to override the blAutoSolrServer bean created by SolrAutoConfiguration (note the specific package requirement for org.broadleafoverrides.config):
package org.broadleafoverrides.config;
public class OverrideConfiguration {
#Bean
public ForceStartupSolrServer blAutoSolrServer(SolrProperties props) {
return new ForceStartupSolrServer(props);
}
}

Issue with custom logback appenders for DropWizard

I'm trying to add a custom LogAppender to be used in drop-wizard. From my understanding, you add an appender:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.cloud.logging.logback.LoggingAppender;
import io.dropwizard.logging.AbstractAppenderFactory;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;
#JsonTypeName("stack-driver-console")
public class StackDriverAppenderFactory extends AbstractAppenderFactory {
private String appenderName = "CLOUD";
private boolean includeContextName = true;
#JsonProperty
public String getName() {
return this.appenderName;
}
#JsonProperty
public void setName(String name) {
this.appenderName = name;
}
#Override
public Appender build(
LoggerContext loggerContext,
String s,
LayoutFactory layoutFactory,
LevelFilterFactory levelFilterFactory,
AsyncAppenderFactory asyncAppenderFactory) {
setNeverBlock(true);
setTimeZone("utc");
setLogFormat("%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n");
LoggingAppender cloudAppender = new LoggingAppender();
cloudAppender.addEnhancer("com.google.cloud.logging.TraceLoggingEnhancer");
cloudAppender.addFilter(levelFilterFactory.build(Level.toLevel(getThreshold())));
cloudAppender.setFlushLevel(Level.WARN);
cloudAppender.setLog("application.log");
cloudAppender.setName(appenderName);
cloudAppender.setContext(loggerContext);
cloudAppender.start();
return wrapAsync(cloudAppender, asyncAppenderFactory);
}
}
then in the /main/resources/META-INF/services/io.dropwizard.logging.AppenderFactory
io.dropwizard.logging.ConsoleAppenderFactory
io.dropwizard.logging.FileAppenderFactory
io.dropwizard.logging.SyslogAppenderFactory
com.example.logger.StackDriverAppenderFactory
Dropwizard version: compile 'io.dropwizard:dropwizard-core:1.3.16'
config.yaml
# Logging settings.
logging:
level: DEBUG
appenders:
- type: stack-driver-console
threshold: INFO
# use the simple server factory if you only want to run on a single port
server:
applicationConnectors:
- type: http
port: 8080
adminConnectors:
- type: http
port: 8081
# the only required property is resourcePackage, for more config options see below
swagger:
resourcePackage: com.example.resources
When I put a break point in io.dropwizard.configuration.BasicConfigurationFactory:build() line 127,
final T config = mapper.readValue(new TreeTraversingParser(node), klass);
where the node is defined as:
{
"logging":{
"level":"DEBUG",
"appenders":[
{
"type":"stack-driver-console",
"threshold":"INFO"
}
]
},
"server":{
"applicationConnectors":[
{
"type":"http",
"port":8080
}
],
"adminConnectors":[
{
"type":"http",
"port":8081
}
]
},
"swagger":{
"resourcePackage":"com.example.resources"
}
}
throws an exception
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'stack-driver-console' as a subtype of [simple type, class io.dropwizard.logging.AppenderFactory<ch.qos.logback.classic.spi.ILoggingEvent>]: known type ids = [console, file, syslog, tcp, udp] (for POJO property 'appenders')
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.example.App["logging"]->io.dropwizard.logging.DefaultLoggingFactory["appenders"]->java.util.ArrayList[0])
It's not clear to my why dropwizard is having a hard time identifying the custom type. This use to work, has something changed?
I followed this example as well "https://gist.github.com/ajmath/e9f90c29cd224653c218"

btrace didn't print out anything when the specified method is invoked

I'm learning how to use btrace. In order to do that, I created a spring-boot project which contained the following code.
#Controller
public class MainController {
private static Logger logger = LoggerFactory.getLogger(MainController.class);
#ResponseBody
#GetMapping("/testFile")
public Map<String, Object> testFile() throws IOException {
File file = new File("/tmp/a");
if (file.exists()) {
file.delete();
}
file.createNewFile();
return ImmutableMap.of("success", true);
}
}
Then I started the project using mvn spring-boot:run, after which I wrote a btrace script, as follows.
import com.sun.btrace.annotations.*;
import com.sun.btrace.BTraceUtils;
#BTrace
public class HelloWorld {
#OnMethod(clazz = "java.io.File", method = "createNewFile")
public static void onNewFileCreated(String fileName) {
BTraceUtils.println("New file is being created");
BTraceUtils.println(fileName);
}
}
As you can see, this script should print something when java.io.File#createNewFile is called, which is exactly what the above controller does. Then I attached btrace to the running spring-boot project using the following code.
btrace 30716 HelloWorld.java
30716 is the PID of the running spring-boot project. Then I tried accessing http://localhost:8080/testFile, and I got the following extra output from the running spring-boot project.
objc[30857]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/bin/java (0x10e2744c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x1145e24e0). One of the two will be used. Which one is undefined.
2019-01-04 11:24:49.003 INFO 30857 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-01-04 11:24:49.003 INFO 30857 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-01-04 11:24:49.019 INFO 30857 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms
I was expecting it to output New file is being created, but it didn't. Why? Did I do something wrong?
Your trace method, onNewFileCreated(String fileName), cannot be used to intercept java.io.File.createNewFile() as the signatures don't agree (createNewFile() doesn't take any arguments, while onNewFileCreated() has one). If there are arguments in the trace method (unless they have a BTrace annotation), BTrace will attempt to "bind" them to the arguments in the intercepted method. If it can't do so, it will not successfully intercept that method.
Try
#OnMethod(clazz = "java.io.File", method = "createNewFile")
public static void onNewFileCreated() {
BTraceUtils.println("method createNewFile called");
}
or
#OnMethod(clazz = "java.io.File", method = "createNewFile")
public static void onNewFileCreated(#ProbeMethodName String methodName) {
BTraceUtils.println("method " + methodName + " called");
}
Update 1:
First, what version of the JDK are you using? BTrace doesn't appear to support JDK > 8 (https://github.com/btraceio/btrace/issues/292).
Second, can you try running this tracing script:
import com.sun.btrace.annotations.*;
import com.sun.btrace.BTraceUtils;
#BTrace
public class TracingScript {
#OnMethod(clazz = "java.io.File", method = "createNewFile")
public static void onNewFileCreated(#ProbeMethodName String methodName) {
BTraceUtils.println("method " + methodName + " called");
}
}
against a simple test application:
import java.io.File;
public class FileCreator {
public static void main(String[] args) throws Exception{
for(int i = 0; i < 250; i++) {
File file = new File("C://Temp//file" + i);
if (file.exists()) {
file.delete();
}
file.createNewFile();
Thread.sleep(10000);
}
}
}
This works for me with BTrace 1.3.11.3 (and via the BTrace Workbench JVisualVM Plugin 0.6.8, which is where I usually use BTrace).

Why is the result of pluginManager.getExtensions empty?

When trying to use PF4J i created the necessary parts as outlined in
https://github.com/pf4j/pf4j
an Interface that extends the ExtensionPoint
a Plugin
Jar with Manifest
Plugin load and activation
Why is the List of clickHandlers empty?
I have tested this with a JUnit test where I can debug the other parts which seem to work fine. See debug log below.
I have also looked at https://github.com/pf4j/pf4j/issues/21 and activated the Eclipse annotation processing with no positive effect.
1. Interface that extends the Extension Point
public interface ClickHandler extends ExtensionPoint {
...
}
2. a Plugin
public class MBClickHandlerPlugin extends Plugin {
/**
* construct me
* #param wrapper
*/
public MBClickHandlerPlugin(PluginWrapper wrapper) {
super(wrapper);
}
#Extension
public static class MBClickHandler implements ClickHandler {
}
}
3. Jar with Manifest
unzip -q -c target/com.bitplan.mb-0.0.1.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Plugin-Dependencies:
Plugin-Id: com.bitplan.mb
Built-By: wf
Plugin-Provider: BITPlan GmbH
Plugin-Version: 0.0.1
Plugin-Class: com.bitplan.mb.MBClickHandlerPlugin
Created-By: Apache Maven 3.5.2
Build-Jdk: 1.8.0_152
4. Plugin load and activation
/**
* activate the plugins requested on the command line
*/
public void activatePlugins() {
pluginManager = new DefaultPluginManager();
for (String plugin : plugins) {
Path pluginPath = Paths.get(plugin);
pluginManager.loadPlugin(pluginPath);
}
pluginManager.startPlugins();
List<ClickHandler> clickHandlers = pluginManager
.getExtensions(ClickHandler.class);
for (ClickHandler clickHandler : clickHandlers) {
installClickHandler(clickHandler);
}
}
Debug log
22 [main] DEBUG org.pf4j.CompoundPluginDescriptorFinder - Try to continue with the next finder
22 [main] DEBUG org.pf4j.CompoundPluginDescriptorFinder - 'org.pf4j.ManifestPluginDescriptorFinder#73d4cc9e' is applicable for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
24 [main] DEBUG org.pf4j.AbstractPluginManager - Found descriptor PluginDescriptor [pluginId=com.bitplan.mb, pluginClass=com.bitplan.mb.MBClickHandlerPlugin, version=0.0.1, provider=BITPlan GmbH, dependencies=[], description=, requires=*, license=null]
24 [main] DEBUG org.pf4j.AbstractPluginManager - Class 'com.bitplan.mb.MBClickHandlerPlugin' for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
24 [main] DEBUG org.pf4j.AbstractPluginManager - Loading plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
24 [main] DEBUG org.pf4j.CompoundPluginLoader - 'org.pf4j.DefaultPluginLoader#6366ebe0' is not applicable for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
24 [main] DEBUG org.pf4j.CompoundPluginLoader - 'org.pf4j.JarPluginLoader#44f75083' is applicable for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
25 [main] DEBUG org.pf4j.PluginClassLoader - Add 'file:/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
25 [main] DEBUG org.pf4j.AbstractPluginManager - Loaded plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar' with class loader 'org.pf4j.PluginClassLoader#43d7741f'
25 [main] DEBUG org.pf4j.AbstractPluginManager - Creating wrapper for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
25 [main] DEBUG org.pf4j.AbstractPluginManager - Created wrapper 'PluginWrapper [descriptor=PluginDescriptor [pluginId=com.bitplan.mb, pluginClass=com.bitplan.mb.MBClickHandlerPlugin, version=0.0.1, provider=BITPlan GmbH, dependencies=[], description=, requires=*, license=null], pluginPath=/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar]' for plugin '/Users/wf/Documents/workspace/com.bitplan.mb/target/com.bitplan.mb-0.0.1.jar'
26 [main] DEBUG org.pf4j.DependencyResolver - Graph:
com.bitplan.mb -> []
26 [main] DEBUG org.pf4j.DependencyResolver - Plugins order: [com.bitplan.mb]
27 [main] INFO org.pf4j.AbstractPluginManager - Plugin 'com.bitplan.mb#0.0.1' resolved
27 [main] INFO org.pf4j.AbstractPluginManager - Start plugin 'com.bitplan.mb#0.0.1'
27 [main] DEBUG org.pf4j.DefaultPluginFactory - Create instance for plugin 'com.bitplan.mb.MBClickHandlerPlugin'
28 [main] DEBUG org.pf4j.AbstractExtensionFinder - Finding extensions of extension point 'com.bitplan.uml2mxgraph.ClickHandler'
28 [main] DEBUG org.pf4j.LegacyExtensionFinder - Reading extensions storages from classpath
28 [main] DEBUG org.pf4j.AbstractExtensionFinder - No extensions found
28 [main] DEBUG org.pf4j.LegacyExtensionFinder - Reading extensions storages from plugins
28 [main] DEBUG org.pf4j.LegacyExtensionFinder - Reading extensions storage from plugin 'com.bitplan.mb'
28 [main] DEBUG org.pf4j.LegacyExtensionFinder - Cannot find 'META-INF/extensions.idx'
28 [main] DEBUG org.pf4j.AbstractExtensionFinder - No extensions found
28 [main] DEBUG org.pf4j.AbstractExtensionFinder - Finding extensions of extension point 'com.bitplan.uml2mxgraph.ClickHandler' for plugin 'null'
28 [main] DEBUG org.pf4j.AbstractExtensionFinder - Finding extensions of extension point 'com.bitplan.uml2mxgraph.ClickHandler' for plugin 'com.bitplan.mb'
29 [main] DEBUG org.pf4j.AbstractExtensionFinder - Found 0 extensions for extension point 'com.bitplan.uml2mxgraph.ClickHandler
'
Workaround #1
use a customized PluginManager
pluginManager = new JarPluginManager(this.getClass().getClassLoader());
from the class that will use the plugin to make sure the same classloader is used
JarPluginManager source code:
import java.nio.file.Path;
import org.pf4j.DefaultPluginManager;
import org.pf4j.JarPluginLoader;
import org.pf4j.ManifestPluginDescriptorFinder;
import org.pf4j.PluginClassLoader;
import org.pf4j.PluginDescriptor;
import org.pf4j.PluginDescriptorFinder;
import org.pf4j.PluginLoader;
import org.pf4j.PluginManager;
/**
* see https://github.com/pf4j/pf4j/issues/249 see
* https://pf4j.org/doc/class-loading.html
*
* #author wf
*
*/
public class JarPluginManager extends DefaultPluginManager {
public static class ParentClassLoaderJarPluginLoader extends JarPluginLoader {
static ClassLoader parentClassLoader;
/**
*
* #param pluginManager
*/
public ParentClassLoaderJarPluginLoader(PluginManager pluginManager) {
super(pluginManager);
}
static PluginClassLoader pluginClassLoader;
#Override
public ClassLoader loadPlugin(Path pluginPath,
PluginDescriptor pluginDescriptor) {
if (pluginClassLoader == null) {
boolean parentFirst=true;
pluginClassLoader = new PluginClassLoader(pluginManager,
pluginDescriptor, parentClassLoader,parentFirst);
}
pluginClassLoader.addFile(pluginPath.toFile());
return pluginClassLoader;
}
}
/**
* construct me with the given classloader
* #param classLoader
*/
public JarPluginManager(ClassLoader classLoader) {
ParentClassLoaderJarPluginLoader.parentClassLoader=classLoader;
//System.setProperty("pf4j.mode", RuntimeMode.DEPLOYMENT.toString());
//System.setProperty("pf4j.mode", RuntimeMode.DEVELOPMENT.toString());
}
#Override
protected PluginLoader createPluginLoader() {
// load only jar plugins
return new ParentClassLoaderJarPluginLoader(this);
}
#Override
protected PluginDescriptorFinder createPluginDescriptorFinder() {
// read plugin descriptor from jar's manifest
return new ManifestPluginDescriptorFinder();
}
}
Workaround #2
If the extensions.idx file is not created there is something wrong with your annotation processing. You might want to fix the source of the problem but it is also possible to try to work around it:
https://groups.google.com/forum/#!topic/pf4j/nn20axJHpfI
pointed me to creating the META-INF/extensions.idx file manually and making sure there is a no args constructor for the static inner class. With this change things work.
Watch out for setting the classname correctly in the extensions.idx
file - otherwise you'll end up with a null entry in the handler list
Watch out for having a null argument constructor otherwise you'll endup with an exception
#Extension
public static class MBClickHandler implements ClickHandler {
/**
* constructor with no argument
*/
public MBClickHandler() {
}
src/main/resources/META-INF/extensions.idx
com.bitplan.mb.MBClickHandlerPlugin$MBClickHandler
Code to check
Correct name for extension.idx entry
MBClickHandler ch=new MBClickHandler();
File extFile=new File("src/main/resources/META-INF/extensions.idx");
String extidx=FileUtils.readFileToString(extFile,"UTF-8");
assertEquals(extidx,ch.getClass().getName());
checking the extensions
List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins();
for (PluginWrapper plugin : startedPlugins) {
String pluginId = plugin.getDescriptor().getPluginId();
System.out.println(String.format("Extensions added by plugin '%s':", pluginId));
Set<String> extensionClassNames = pluginManager.getExtensionClassNames(pluginId);
for (String extension : extensionClassNames) {
System.out.println(" " + extension);
}
}

EhCache, on-heap tier: No serializer found

I need on-heap cache, so I'm trying to work with ehcache v3.5.2
I have the next test:
public class TestEhCache {
public static class MyObj {
String message;
public MyObj(String message) {
this.message = message;
}
}
#Test
public void testDebugLogs() {
CacheManager cacheManager;
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
Cache<String, MyObj> myCache = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, MyObj.class, ResourcePoolsBuilder.heap(3))
.build());
}
}
As result I see the next warning
2018-04-26 19:56:26,237 [main] DEBUG org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider - Serializer for <java.lang.String> : org.ehcache.impl.serialization.StringSerializer#365185bd
2018-04-26 19:56:26,238 [main] DEBUG org.ehcache.core.EhcacheManager - Could not create serializers for myCache
org.ehcache.spi.serialization.UnsupportedTypeException: No serializer found for type 'it.TestEhcache$MyObj'
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider.getSerializerClassFor(DefaultSerializationProvider.java:136)
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider.createSerializer(DefaultSerializationProvider.java:98)
at org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider.createValueSerializer(DefaultSerializationProvider.java:90)
at org.ehcache.core.EhcacheManager.getStore(EhcacheManager.java:477)
at org.ehcache.core.EhcacheManager.createNewEhcache(EhcacheManager.java:316)
at org.ehcache.core.EhcacheManager.createCache(EhcacheManager.java:265)
at org.ehcache.core.EhcacheManager.createCache(EhcacheManager.java:243)
at it.TestEhcache.testDebugLogs(TestEhcache.java:29)
2018-04-26 19:56:26,243 [main] DEBUG org.ehcache.impl.internal.spi.copy.DefaultCopyProvider - Copier for <java.lang.String> : org.ehcache.impl.copy.IdentityCopier#150c158
2018-04-26 19:56:26,244 [main] DEBUG org.ehcache.impl.internal.spi.copy.DefaultCopyProvider - Copier for <it.TestEhcache$MyObj> : org.ehcache.impl.copy.IdentityCopier#4524411f
2018-04-26 19:56:26,292 [main] DEBUG class org.ehcache.core.Ehcache-myCache - Initialize successful.
2018-04-26 19:56:26,292 [main] INFO org.ehcache.core.EhcacheManager - Cache 'myCache' created in EhcacheManager.
How to suppress "No serializer found for type" warning? As I understood it's not required for no-heap tier. (see Louis's Jacomet reply here)
Decrease the log level - this is printed at DEBUG so it is not technically a warning.
And indeed your on-heap cache will work fine.

Categories

Resources