Run Checker Framework with Bazel - bazel

Consider this github repository. https://github.com/dfabulich/bazel-checker-framework-bug
It includes a sample X.java file that flagrantly violates the rules of the #Nonnull annotation.
import javax.annotation.Nonnull;
public class X {
public static void main(String[] args) {
new X().exec();
}
public void exec() {
System.out.println(this.method());
}
#Nonnull
private String method() {
return null;
}
}
The WORKSPACE file just includes checker.jar.
maven_jar(
name="checker",
artifact="org.checkerframework:checker:2.3.1"
)
The BUILD file invokes the compiler with the checker framework configured as a java_plugin.
java_library(
name='x',
srcs=['X.java'],
deps=['#checker//jar'],
plugins=['checker'],
)
java_plugin(
name='checker',
deps=['#checker//jar'],
processor_class='org.checkerframework.checker.nullness.NullnessChecker',
)
When I bazel build x, the build fails with this error:
error: InvocationTargetException when invoking constructor for class org.checkerframework.checker.nullness.KeyForAnnotatedTypeFactory; Underlying cause: java.lang.StackOverflowError; The Checker Framework crashed. Please report the crash. To see the full stack trace invoke the compiler with -AprintErrorStack
When I comment out the plugins line in the BUILD file, the build succeeds without error. (That makes sense, but I ultimately want the Checker Framework to fail this build with a return.type.incompatible error.)
Am I making a mistake here? Is this a bug in Bazel?

I got a good answer on the bazel-discuss mailing list, telling me to try NullAway, an Error Prone plugin that depends on the Checker Framework.
The github repo now includes a working example using NullAway, like this.
WORKSPACE:
maven_jar(
name='jsr305',
artifact='com.google.code.findbugs:jsr305:3.0.2',
)
maven_jar(
name="nullaway",
artifact="com.uber.nullaway:nullaway:0.3.2"
)
maven_jar(
name="guava",
artifact="com.google.guava:guava:22.0",
)
BUILD:
java_library(
name='x',
srcs=['X.java'],
deps=['#jsr305//jar'],
plugins=['nullaway'],
javacopts=[
'-Xep:NullAway:ERROR',
'-XepOpt:NullAway:AnnotatedPackages=com.example',
],
)
java_plugin(
name='nullaway',
deps=[
'#nullaway//jar',
'#guava//jar',
],
)
(The dependency on guava is unfortunate; it's required because without Guava, NullAway refuses to load.)

Related

where is `cc_proto_library` implementation in bazel?

I read the source code of bazel, and I found cc_binary and cc_library in src/main/starlark/builtins_bzl/common/cc.
Also I found proto_library in src/main/starlark/builtins_bzl/common/proto. But I can't find where is the cc_proto_library's implementation.
Can anyone tell me how it works?
Tip: use the Bazel codesearch at https://source.bazel.build to navigate its source code.
You can quickly find the implementation of any built-in rule using a query like:
language:java "implements RuleDefinition" "\"cc_proto_library\")"
This will bring you to the CcProtoLibraryRule.java definition:
public class CcProtoLibraryRule implements RuleDefinition {
private final CcProtoAspect ccProtoAspect;
public CcProtoLibraryRule(CcProtoAspect ccProtoAspect) {
this.ccProtoAspect = ccProtoAspect;
}
#Override
public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment environment) {
return builder
.requiresConfigurationFragments(CppConfiguration.class)
/* <!-- #BLAZE_RULE(cc_proto_library).ATTRIBUTE(deps) -->
The list of <code>proto_library</code>
rules to generate C++ code for.
<!-- #END_BLAZE_RULE.ATTRIBUTE --> */
.override(
attr("deps", LABEL_LIST)
.allowedRuleClasses("proto_library")
.allowedFileTypes()
.aspect(ccProtoAspect))
.build();
}
#Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("cc_proto_library")
.factoryClass(CcProtoLibrary.class)
.ancestors(BaseRuleClasses.NativeActionCreatingRule.class)
.build();
}
}
The implementation is defined with .factoryClass(CcProtoLibrary.class).
For the second part of your question, "builtins" are a Bazel-internal concept to transparently swap out the Java implementation of a Bazel rule to its Starlark equivalent, without needing to add any load statements in the BUILD file. This is necessary to migrate existing users to Starlark implementations without causing user impact.

Error when using MvxAppCompatActivity

I am writing an application with Xamarin.Android with MvvmCross. I want my Activity to inherit from MvxAppCompatActivity so that I can use fragments. Here is my base class:
public class BaseActivity<TViewModel> : MvxAppCompatActivity<TViewModel> where TViewModel : MvxViewModel
{
public new TViewModel ViewModel
{
get { return base.ViewModel; }
set { base.ViewModel = value; }
}
}
I get this error on the OnCreate of my Activity:
Failed resolution of: Landroid/support/v7/appcompat/R$drawable; Didn't
find class "android.support.v7.appcompat.R$drawable" on path:
DexPathList...
But if I change MvxAppCompatActivity to MvxActivity it works fine...why?
I downloaded your solution and tried to build the Android project. It fails with 18 occurrences of the same error:
error: No resource identifier found for attribute 'loginButtonBackgroundColor' in package ...
So after a little inspection of your solution, I did the following steps to solve your issue:
1) In login_screen.axml I saw you had this line:
xmlns:[YOURNAMESPACE]="http://schemas.android.com/apk/res/[YOUR PACKAGE]"
Which is unnecessary. After removing it, and changing the lines [YOURNAMESPACE]:loginButtonBackgroundColor=... to local:loginButtonBackgroundColor=... the build succeeds.
2) I saw some layout files are located inside the /drawable folder (button_round_corner.xml, input_box.xml and login_button.xml). I moved them to the /layout folder and fixed the issues the change produced (only two).
3) Made Setup class inherit from MvxAppCompatSetup.
4) Added a RegisterAttribute over the LoginButton control. So the class definition looks like this:
using Android.Runtime;
...
namespace Xxx.Droid.Components
{
[Register(nameof(LoginButton))]
public class LoginButton : FrameLayout, IMvxNotifyPropertyChanged
{
...
}
}
And that's it! Probably (2) was not necessary, but leaving it here just in case.
It could be several things but it is probably the lack of some android support packages. Mainly the lack of Xamarin.Android.Support.Design gives that error. So check if you have that added and if not add it and it should solve your problem.
If it doesn't it's highly likely you lack some other android support packages

C-CDA validation fails because of "Unknown type" in my server but not in standalone project

I was checking how to use the MDHT libraries to validate C-CDA documents, reviewing the current implementations, to create a validation web service for my project. I firstly made a Eclipse local Java Project, added the JARs to the classpath, and implement the code. The execution was successful. But when I copy the same code to my web project (made with Spring Boot) and send a request that executes such code, the program fails.
To explain better, I made the following minimal method:
public void executeMDHTCode(byte[] fileContents) {
System.out.println(Arrays.toString(fileContents));
ValidationResult result = new ValidationResult();
ClinicalDocument doc = null;
try {
ConsolPackage.eINSTANCE.eClass();
doc = CDAUtil.load(new ByteArrayInputStream(fileContents), result);
} catch (ClassCastException|SAXParseException|Resource.IOWrappedException e) {
doc = null;
} catch (Exception e) {
throw new RuntimeException("Unknown error: " + e.getMessage(), e);
}
}
Then I used it in the following main method in my test project
public static void main(String[] args) throws IOException {
ByteArrayOutputStream outstr = new ByteArrayOutputStream();
int b = -1;
InputStream stream = AppTest.class.getResourceAsStream("xml_ccda_invalid.xml");
while((b = stream.read()) != -1) {
outstr.write(b);
}
executeMDHTCode(outstr.toByteArray()); // only added 'static'
}
And then used the same code in my server project (encapsulating it in a ccdaService)
#RequestMapping(/*POST endpoint properties*/)
public ResponseEntity<Object> validateCCDAFile(#RequestBody MultipartFile file) throws IOException {
ccdaService.executeMDHTCode(file.getBytes());
return null;
}
The document to be tested in both cases, xml_ccda_invalid.xml, contains the following:
<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">
<realmCode code="US"/>
</ClinicalDocument>
As I said, the test project version terminates correctly. But the server version throws the following exception:
java.lang.UnsupportedOperationException: Unknown type ([vocab, ActClinicalDocument, DOCCLIN])
at org.eclipse.mdht.uml.cda.operations.ClinicalDocumentOperations.validateClassCode(ClinicalDocumentOperations.java:133) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.impl.ClinicalDocumentImpl.validateClassCode(ClinicalDocumentImpl.java:1659) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument_validateClassCode(CDAValidator.java:1769) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument(CDAValidator.java:1753) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAValidator.validate(CDAValidator.java:1075) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.emf.ecore.util.EObjectValidator.validate(EObjectValidator.java:324) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
at org.eclipse.emf.ecore.util.Diagnostician.doValidate(Diagnostician.java:171) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:158) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:137) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:108) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:707) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:696) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAUtil.performEMFValidation(CDAUtil.java:830) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:277) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:252) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
at companypackage.service.impl.CCDAServiceImpl.executeMDHTCode(CCDAServiceImpl.java:109) ~[bin/:?]
at companypackage.controller.CCDAController.validateCCDAFile(CCDAController.java:32) ~[bin/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_102]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_102]
at (other spring and apache calls...)
I used the println statement to check the contents of the input array, and they are in both cases identical, so it's not a matter of server processing of the file.
I have not idea why this happens. I put all the jars of the server project into the test project's classpath and it still worked, so it's not a class name clash. It seems to be only interfere when actually used.
What could I be missing?
The looks to be an issue with the war file deployment - the ActClinicalDocument is defined in the org.eclipse.mdht.uml.hl7.vocab jar; if you are using maven for the build you can look at the following maven example https://github.com/mdht/mdht-models/tree/develop/examples/org.openhealthtools.mdht.cda.maven.example
if not make sure in your eclipse project that the jars etc are included in the binary build
It sounds like you aren't applying a schema in your standalone project, or maybe not the same schema, so it is validating without reference to the validation process.

How to populate parameter "defaultValue" in Maven "AbstractMojoTestCase"?

I have a Maven plugin that I am attempting to test using a subclass of the AbstractMojoTestCase. The plugin Mojo defines an outputFolder parameter with a defaultValue. This parameter is not generally expected to be provided by the user in the POM.
#Parameter(defaultValue = "${project.build.directory}/someOutputFolder")
private File outputFolder;
And if I use the plugin in a real scenario then the outputFolder gets defaulted as expected.
But if I test the Mojo using the AbstractMojoTestCase then while parameters defined in the test POM are populated, parameters with a defaultValue that are not defined in the POM are not populated.
public class MyPluginTestCase extends AbstractMojoTestCase {
public void testAssembly() throws Exception {
final File pom = getTestFile( "src/test/resources/test-pom.xml");
assertNotNull(pom);
assertTrue(pom.exists());
final MyMojo myMojo = (BaselineAssemblyMojo) lookupMojo("assemble", pom);
assertNotNull(myMojo);
myMojo.execute(); // Dies due to NullPointerException on outputFolder.
}
}
Further: if I define the outputFolder parameter in the POM like so:
<outputFolder>${project.build.directory}/someOutputFolder</outputFolder>
then ${project.build.directory} is NOT resolved within the AbstractMojoTestCase.
So what do I need to do to get the defaultvalue populated when testing?
Or is this a fault in the AbstractMojoTestCase?
This is Maven-3.2.3, maven-plugin-plugin-3.2, JDK 8
You need to use lookupConfiguredMojo.
Here's what I ended up using:
public class MyPluginTest
{
#Rule
public MojoRule mojoRule = new MojoRule();
#Test
public void noSource() throws Exception
{
// Just give the location, where the pom.xml is located
MyPlugin plugin = (MyPlugin) mojoRule.lookupConfiguredMojo(getResourcesFile("basic-test"), "myGoal");
plugin.execute();
assertThat(plugin.getSomeInformation()).isEmpty();
}
public File getResourcesFile(String filename)
{
return new File("src/test/resources", filename);
}
}
Of course you need to replace myGoal with your plugin's goal. You also need to figure out how to assert that your plugin executed successfully.
For a more complete example, check out the tests I wrote for fmt-maven-plugin

Exception in thread "main" java.lang.Error: Unresolved compilation problems: JNI4net

I am working with JNI4net and although the libraries and installed in the build path and eclipse recognizes them, it still gives me run time error. Why could that be in your opinion? Here is the code.
import net.sf.jni4net.*;
import java.io.IOException;
import java.lang.String;
import system.*;
import system.Object;
import system.io.TextWriter;
import system.collections.IDictionary;
import system.collections.IEnumerator;
/**
* #author Pavel Savara (original)
*/
public class Program {
public static void main(String[] args) throws IOException {
// create bridge, with default setup
// it will lookup jni4net.n.dll next to jni4net.j.jar
//Bridge.setVerbose(true);
Bridge.setVerbose(true);
Bridge.init();
// here you go!
Console.WriteLine("Hello .NET world!\n");
// OK, simple hello is boring, let's play with System.Environment
// they are Hashtable realy
final IDictionary variables = system.Environment.GetEnvironmentVariables();
// let's enumerate all keys
final IEnumerator keys = variables.getKeys().GetEnumerator();
while (keys.MoveNext()) {
// there hash table is not generic and returns system.Object
// but we know is should be system.String, so we could cast
final system.String key = (system.String) keys.getCurrent();
Console.Write(key);
// this is automatic conversion of JVM string to system.String
Console.Write(" : ");
// we use the hashtable
Object value = variables.getItem(key);
// and this is JVM toString() redirected to CLR ToString() method
String valueToString = value.toString();
Console.WriteLine(valueToString);
}
// Console output is really TextWriter on stream
final TextWriter writer = Console.getOut();
writer.Flush();
}
}
AND here is the message I get!
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Bridge cannot be resolved
Bridge cannot be resolved
Console cannot be resolved
IDictionary cannot be resolved to a type
system cannot be resolved
IEnumerator cannot be resolved to a type
system cannot be resolved to a type
system cannot be resolved to a type
Console cannot be resolved
Console cannot be resolved
Console cannot be resolved
TextWriter cannot be resolved to a type
Console cannot be resolved
at Program.main(Program.java:37)
To make your life easier, I am going to share my findings here. Read Martin Serrano's answer to my question. It will help you understand what needs to be done. Then go to jni4net's website and download their example zip folder. Extract that. There is an example there called myCSharpDemoCalc. Replace your dll with myCSharpDemoCalc.dll (inside work folder) and then run generateProxies.cmd (be sure to edit this file to your dll name) and run.cmd. Then go to the work folder and run build.cmd (edit name) to create your JAR file. It might not spit out the j4n.dll you probably need to twik the path yourself. Use this JAR file. This was the easiest way to create a JAR file from a third party dll for me.

Resources