Custom Rules in Checkstyle for ensuring Logger is declared as a Static Final Class Attribute - checkstyle

I have written the above rule and when trying to run it from the command line I keep getting the same message namely:
Unable to create Checker: cannot initialize module TreeWalker - Unable to instantiate LoggerAttrCheck
I have stripped down my checks to just one in Checker and one in Treewalker, copied religiously the entries as suggested in the manual and no joy. Anyone had similar issues with custom rules. I am WinXP, java 1.6 (Eclipse), checkstyle-5.1 folder is in path.
I can provide code but this smells of an environmental issue.
Code is as follows:
package com.mystuff.checkstyle.hecks;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
/**
*
*
* This package provides the custom checks that were required outside
* of the standard checks provided
*
*/
public class LoggerAttrCheck extends Check
{
/**
*
*
* The Logger must be declared as a static final class attribute
*
*/
#Override
public int[] getDefaultTokens()
{
return new int[] { TokenTypes.VARIABLE_DEF};
}
#Override
public void visitToken(DetailAST aAST)
{
if(aAST.getType()==TokenTypes.VARIABLE_DEF)
visitVariableDef(aAST);
}
/**
* Checks type of given variable.
* #param aAST variable to check.
*/
private void visitVariableDef(DetailAST aAST)
{
checkVariableDefn(aAST);
}
/**
*
* Checks variable to see if its a Logger and static final
* * #param aAST node to check.
*/
private void checkVariableDefn(DetailAST aAST)
{
final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE);
final FullIdent ident = CheckUtils.createFullType(type);
if ((ident.getText().equals("Logger")))
{
if((!aAST.branchContains(TokenTypes.FINAL))||(!aAST.branchContainsTokenTypes.LITERAL_STATIC)))
{
log(type.getLineNo(), type.getColumnNo(),
"Logger not defined as static final class attribute", type.getText());
}
}
}
}
This builds com.stuff.checkstyle.checks.jar, so the the checkstyle_packages.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE checkstyle-packages PUBLIC
"-//Puppy Crawl//DTD Package Names 1.3//EN"
"http://www.puppycrawl.com/dtds/packages_1_3.dtd">
<checkstyle-packages>
<package name="com.mystuff.checkstyle.checks"/>
</checkstyle-packages>
All ideas gratefully received !

What does your checkstyle configuration file look like? It appears that your checkstyle_packages.xml is being ignored. I found I couldn't add my package to the checkstyle-packages and so declared my check with the full package name:
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.2//EN"
"http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<module name="Checker">
<module name="TreeWalker">
<!-- Blundell specific checks -->
<module name="com.blundell.checks.AntiHungarian" />
</module>
</module>
Note that the java class name for the check is AntiHungarianCheck but you declare is as just AntiHungarian
Taken from my custom checkstyle example here:
http://blog.blundell-apps.com/create-your-own-checkstyle-check/
and source code here:
https://github.com/blundell/CreateYourOwnCheckStyleCheck

Related

Where are attributes defined for PrimeFaces 6.x UIComponents?

I'm browsing the PrimeFaces 6.1 source at GitHub.
The components only seem to have a renderer class and no component class. For example, the OutputLabelRenderer references
the OutputLabel, but the OutputLabel class is nowhere to be found. I expected it to be in the same folder as the renderer (as there was no import).
I did find this template file though. So it looks like it is generated somehow.
Where can I find the attributes for a PrimeFaces component?
After checking the pom.xml I've found this plugin:
<plugin>
<groupId>org.primefaces</groupId>
<artifactId>maven-jsf-plugin</artifactId>
<version>1.3.3-SNAPSHOT</version>
<executions>
<execution>
<id>generate-ui</id>
<phase>generate-sources</phase>
<configuration>
<uri>http://primefaces.org/ui</uri>
<shortName>p</shortName>
<templatesDir>src/main/java-templates</templatesDir>
<componentConfigsDir>target/resources-maven-jsf/ui</componentConfigsDir>
<standardFacesConfig>src/main/resources-maven-jsf/standard-faces-config.xml</standardFacesConfig>
<standardFaceletsTaglib>src/main/resources-maven-jsf/standard-facelets-taglib.xml</standardFaceletsTaglib>
<standardTLD>src/main/resources-maven-jsf/standard-tld.xml</standardTLD>
</configuration>
<goals>
<goal>generate-components</goal>
<goal>generate-facelets-taglib</goal>
</goals>
</execution>
...
</executions>
</plugin>
The definition (including the attributes) are located in the /src/main/resources-maven-jsf/ui/ folder. For examplate outputLabel.xml.
You can also download the sources JAR from Maven. It will include the component code. For example:
/*
* Generated, Do Not Modify
*/
/*
* Copyright 2009-2013 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.component.outputlabel;
import javax.faces.component.html.HtmlOutputLabel;
import javax.faces.context.FacesContext;
import javax.faces.component.UINamingContainer;
import javax.el.ValueExpression;
import javax.el.MethodExpression;
import javax.faces.render.Renderer;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.event.AbortProcessingException;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import java.util.List;
import java.util.ArrayList;
import org.primefaces.util.ComponentUtils;
#ResourceDependencies({
})
public class OutputLabel extends HtmlOutputLabel {
public static final String COMPONENT_TYPE = "org.primefaces.component.OutputLabel";
public static final String COMPONENT_FAMILY = "org.primefaces.component";
public static final String DEFAULT_RENDERER = "org.primefaces.component.OutputLabelRenderer";
public enum PropertyKeys {
indicateRequired;
String toString;
PropertyKeys(String toString) {
this.toString = toString;
}
PropertyKeys() {}
public String toString() {
return ((this.toString != null) ? this.toString : super.toString());
}
}
public OutputLabel() {
setRendererType(DEFAULT_RENDERER);
}
public String getFamily() {
return COMPONENT_FAMILY;
}
public boolean isIndicateRequired() {
return (java.lang.Boolean) getStateHelper().eval(PropertyKeys.indicateRequired, true);
}
public void setIndicateRequired(boolean _indicateRequired) {
getStateHelper().put(PropertyKeys.indicateRequired, _indicateRequired);
}
public final static String STYLE_CLASS = "ui-outputlabel ui-widget";
public final static String REQUIRED_FIELD_INDICATOR_CLASS = "ui-outputlabel-rfi";
}

Apache CXF DSOGI with JSON on Karaf

I am trying to create a RESTful web service in Karaf 4.0.8 with Apache CXF DOSGI. The service is being called but I am getting this error: No message body writer has been found for class....
Any suggestion is welcome. Thank you!!!
Component:
#Component(immediate = true, property = {
"service.exported.interfaces=*",
"service.exported.configs=org.apache.cxf.rs",
"org.apache.cxf.rs.provider=com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider",
"org.apache.cxf.rs.address=/integr" })
public class AccountRestService implements AccountWebUserIdResource {
...
}
Interface:
------------
#GET
#Produces({
"application/json"
})
AccountWebUserIdResource.GetAccountByWebUserIdResponse getAccountByWebUserId(
#PathParam("webUserId")
String webUserId,
#QueryParam("sc")
String sc,
#QueryParam("fields")
String fields)
throws Exception
;
Entity:
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"href",
"crm_member_id",
"email_address",
"account_status"
})
public class Account {
/**
*
* (Required)
*
*/
#JsonProperty("href")
private String href;
/**
*
* (Required)
*
*/
#JsonProperty("crm_member_id")
private String crmMemberId;
/**
*
* (Required)
*
*/
#JsonProperty("email_address")
private String emailAddress;
....
At least with CXF-DOSGi 2 your code probably will not work. Loading the provider from a class name is problematic in OSGi anyway as the CXF DOSGi code has no visibility of the com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider class.
In CXF-DOSGi this can be done using an intent. This is more OSGi friendly as the JacksonJsonProvider is then directly used as a class and so OSGi class loading works nicely. It is also necessary to set a bus property to all to override the jacksonprovider as the spec normally would not allow this.
cxf.bus.prop.skip.default.json.provider.registration=true
The intent class looks like this:
#Component(property = "org.apache.cxf.dosgi.IntentName=jackson")
public class JacksonIntent implements Callable<List<Object>> {
public List<Object> call() throws Exception {
return Arrays.asList((Object)new JacksonJaxbJsonProvider());
}
}
The intents provide a generic way to define features and other overrides for CXF without directly influencing your service class.
The intent then has to be referenced in the service using the service property service.exported.intents=jackson.
I just added a jackson example to CXF-DOSGi.
Another small obstacle is that the current cxf-jackson feature misses a bundle. See CXF-7298.

How to run jul-to-slf4j bridge once per JVM?

I'd like to run Surefire in parallel mode (multiple JVMs) where each JVM must run:
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
exactly once before the first test. How can this be done?
There are various ways to make some code run at the beginning of a test suite.
Here are 4 (I'm sure there are more):
JUnit via RunWith Suite with Suite.SuiteClasses and BeforeClass (adapted from examples in SuiteTest):
#RunWith(Suite.class)
#SuiteClasses({FirstTest.class, SecondTest.class/*, ...*/, LastTest.class})
public static class AllWithSLF4JBridgeHandler {
#BeforeClass
public static void registerRootLoggerHandlers() {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
}
TestNG with BeforeSuite:
/**
* Base class for each test class (i.e. every test class should extend this class).
*/
public abstract class BaseTest {
#BeforeSuite
public void registerRootLoggerHandlers() {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
}
TestNG with Guice:
/**
* Test module. Each test class should be annotated with `#Guice(TestModule.class)`.
*/
public class TestModule implements Module {
#Override
public void configure(Binder binder) {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
}
Static initialization blocks (test-framework independent):
/**
* Base class for each test class (i.e. every test class should extend this class).
*/
public abstract class BaseTest {
static {
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
}
I'm not sure how all of these methods work with Surefire's parallel mode. Methods 1 and 2 may not work there but I believe methods 3 and 4 should.
Another option would be to not use the programmatic installation of the SLF4JBridgeHandler but to use a java.util.logging.config file or class (see LogManager):
"java.util.logging.config.file":
logging.properties file:
// register SLF4JBridgeHandler as handler for the j.u.l. root logger
handlers = org.slf4j.bridge.SLF4JBridgeHandler
System property assignment:
java -Djava.util.logging.config.file=/path/to/logging.properties ...
This works well if you know the path to your logging file beforehand.
"java.util.logging.config.class":
Using a file may not be a good option if you're deploying a WAR and don't know where the file will be, etc. so alternatively you can create a logging config class:
public class SLF4JBridgeHandlerInitializer {
public SLF4JBridgeHandlerInitializer() throws IOException {
String loggingConfigurationString = "handlers = " + SLF4JBridgeHandler.class.getName();
InputStream inputStream = new ByteArrayInputStream(loggingConfigurationString.getBytes());
LogManager.getLogManager().readConfiguration(inputStream);
}
}
System property assignment:
java -Djava.util.logging.config.class=package.SLF4JBridgeHandlerInitializer ...
I've done this before and it has worked well for me (SLF4JBridgeHandler.Initializer by mfulton26 · Pull Request #57 · qos-ch/slf4j).
These final two options should initialize each JVM instance as long as the appropriate system property is set.

Action script3 trace in flex builder

this is the code, i am using flex builder 4.5,
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
public var ss:Array = ["a", "b", "c"];
trace(ss[0]);
public var str:String = "Good Luck";
trace(str);
]]>
</fx:Script>
</s:Application>
i get red cross next to trace statment and fault is
"1120:Access of defined property ss"
i have tried the commented line as well but no luck. i have tried with 3.5, 4.1 and 4.5 sdk.
Am i missing something? please guide!!
(i tried googling it but nothing came up )
thanks in advance.
(updated the code)
public var ss:String is a field declaration and trace(ss) is an action in code execution flow. Place trace(ss) in an appropriate scope (in a function aka method) and it will be compiled and executed without any problem.
I think you are getting confused between Class member properties and local variables. Inside a method, you can only declare local variables, for example:
public function debugString() : void {
// declare a local property, only this, 'debugString' function can acess
// or modify this property - it is deleted when this function finishes.
var myString : String = "Hello World";
trace(myString);
}
However, it would appear that you were trying to define Class member properties instead (because you were declaring the visibility of the property (ie: public)).
public class HelloWorld {
// Define a Class member property; all functions in this Class will be
// able to access, and modify it. This property will live for as long as the
// Class is still referenced.
public var myString : String = "Hello World";
public function debugString() : void {
// notice how we did not declare the 'myString' variable inside
// this function.
trace(myString);
}
}
Note that you can only access member properties once a Class has been constructed; so the earliest you can (sensibly) access them is in your Constructor, for example:
class HelloWorld {
public var myString : String = "Hello World";
// This will not work, because you can only access static properties
// outside of a function body. This makes sense because a member property
// belongs to each instance of a given Class, and you have not constructed
// that instance yet.
trace(myString);
// This is the Class Constructor, it will be called automatically when a
// new instance of the HelloWorld class is created.
public function HelloWorld() {
trace(myString);
}
}
What you might be trying to do is make use of a static property; these differ from Class member properties as they are Globally shared amongst all instances of a given class. By convention, static properties are defined in CAPS:
public class HelloWorld {
// Here we define a static property; this is accessible straight away and you
// don't even need to create a new instance of the host class in order to
// access it, for example, you can call HelloWorld.MY_STRING from anywhere in your
// application's codebase - ie: trace(HelloWorld.MY_STRING)
public static var MY_STRING : String = "Hello World";
}

Cant mock static functions with powermock-easymock-testng (non-maven project)

To tell you first, i have tried and tried it again and now i need some help
Heres my code
package staticPkg;
public class Static {
public static final String staticMethod() {
System.out.println("Static method called");
return "Static called";
}
}
package staticPkg;
public class TargetClass {
Static staticClass;
public String callHere() {
return Static.staticMethod();
}
}
package staticPkg;
import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
#PrepareForTest({Static.class})
public class TestClass {
Static staticClass = null;
#ObjectFactory
public IObjectFactory getObjectFactory() {
System.out.println("got object factory");
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#BeforeMethod
public void setup() {
System.out.println("print me");
PowerMock.mockStatic(Static.class);
staticClass = PowerMock.createMock(Static.class);
}
#Test
public void testMe() {
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}
}
And heres the log
[Parser] Running:
C:\MockWorkspace\Mock\temp-testng-customsuite.xml
got object factory
print me
Static method called
FAILED: testMe
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at staticPkg.TestClass.testMe(TestClass.java:46)
... Removed 22 stack frames
===============================================
staticPkg.TestClass
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Mock
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Help please, i have tried a variety of solutions, can't get it done.
Please can anyone try this code and correct it for success?
I get error in EasyMock.expect ...............
Got a work around at http://blogs.bytecode.com.au/glen/2006/10/12/doing-bytecode-kungfu-with-javassist.html
And it works
But wait..........I am stuck again
My testcase works fine when runs alone, but when run with Ant, it gives problem. Might be other test cases of different files are interfering.
I got the same error, when my individual test case was using #PrepareTest & easymock/powermock
[testng] ====================STATIC CALLED===========================
[testng] javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of sun/misc/Launcher$AppClass
Loader): attempted duplicate class definition for name: "com/symantec/mobius/aggregator/submission/SubmissionFactory"
[testng] at javassist.ClassPool.toClass(ClassPool.java:1085)
[testng] at javassist.ClassPool.toClass(ClassPool.java:1028)
[testng] at javassist.ClassPool.toClass(ClassPool.java:986)
[testng] at javassist.CtClass.toClass(CtClass.java:1110)
Try extending from PowerMockTestCase. The TestNG support will also be updated in next version of PowerMock (1.4.9).
I faced this same issue, and struggled a lot. Finally, found the following solution:
Another alternative is to set the object-factory to org.powermock.modules.testng.PowerMockObjectFactory in the TestNG suite.xml. Here is a sample suite file:
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
<test name="dgf">
<classes>
<class name="com.example.ClientTest"/>
</classes>
</test>
</suite>
Of course, you can also extend your test case from PowerMockTestCase as told by Johan.
Mock all the static methods in static class before proceeding to mock the static method. Try with this:
#Test
public void testMe() {
PowerMock.mockStatic(Static.class);
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}