Archive for the ‘Uncategorized’ category

How to teach Sonar to find new bug?

19. April 2017

How to teach Sonar to find new bug?

Background

A few days ago my Jenkins instance gave me
the regurlar hint for updates. So I checked the changelog for changes which are
interesting to me. One of them hit my eye: Jenkins 2.53 – „GC Performance:
Avoid using FileInputStream and FileOutputStream in the core codebase.
“ I
read the two tickets (for Jenkins and the JDK itself) and was
surprised. I hadn’t knew that.

Some days later I regognized a longer
blog
about that by CloudBees on DZone.
Also interesting.

During thinking about changing the „new FIS/FOS“
to something better in the open source projects I am working on (Apache Ant, Apache Commons) – Stefan
was faster
. 😉

Using „search and (manually) replace“ on my
office-codebase I thought about how to ensure that nobody intoduced these
instantiations again?

The tool

At work we use a Sonar instance for detecting propable
issues. Sonar uses static code analysis for detecting errors – unclosed
streams, possible NullPointers, etc. But this (new) „bug pattern“ was not
implemented. Sonar itself could scan Java files, but also other languages.

The documentation of Sonar contains a
chapter of writing
custom Java rules
.

I don’t want to copy that tutorial with my
own word, but here are some highlights:

·       
Finally you end a with a plain JAR you‘ll have
to copy to the Sonar
extensions/plugins
directory, restart Sonar and activate your new rule.

·       
The Tutorial gives you a pointer to Github
repository
containing the sample sources, so you start with them. I decided
to start from scratch and copied the parts I could need instead of cloning the
whole repo and extend that.

·       
The entry class is an implementation of org.sonar.api.Plugin
and its declaration in the manifest file (key=Plugin-Class).

·       
This PlugIn registers two classes: one defining
your „repository“ with all the help files and metadata. And another which
registers the rules for production code or test code. They have to implement
the interfaces
org.sonar.api.server.rule.RulesDefinition respective org.sonar.plugins.java.api.CheckRegistrar.

·       
The rule itself could extend several entry
points, here the easiest is extending
org.sonar.plugins.java.api.IssuableSubscriptionVisitor, so you could benefit from the Java knowledge and the access to the
Java AST.

The rule

Implementing the IssuableSubscriptionVisitor itself is fairly easy:

1. 
Register which types of AST nodes you are
interested in – here instantiation of objects:
@Override

public
List nodesToVisit() {

    return
ImmutableList.of(Tree.Kind.
NEW_CLASS);

}

 

2.      Implement the logic for handling this. Here we are interested in
instantiation of
java.io.FileInputStream
or
java.io.FileOutputStream:

private
List
forbiddenClasses = ImmutableList.of(

        „java.io.FileInputStream“,

        „java.io.FileOutputStream“

    );

 

@Override

public void
visitNode(Tree
tree) {

    NewClassTree nct =
(NewClassTree)
tree;

    for(String forbiddenClass : forbiddenClasses) {

        if (nct.symbolType().is(forbiddenClass)) {

           
reportIssue(
tree, „Avoid using „ + forbiddenClass);

        }

    }

}

3.      The typecast in the visitNode
method could be done safely because we registered only (that) one type in the
nodesToVisit method. First I intended to use a list.contains(nct.symbolType()) but the is() method also checks
for subclasses.

When reporting
the issue the method registers the exact location via the give node.

4.      Provide metadata via a @org.sonar.check.Rule annotation:

@Rule(

   
key=
„AvoidClassRule“,

   
name=
„Avoid usage of FileInputStream or FileOutputStream“,

   
description=
„FileInputStream and FileOutputStream can cause memory
leaks

       
and should be replaced by NIO-functionality“
,

   
priority=Priority.
INFO,

   
tags={
„bug“}

)

public class AvoidClassRule
extends IssuableSubscriptionVisitor {

 

Sadly we have
to duplicate the key. Also the other information we have duplicated in metadata
files. I haven’t dived that deep to check if we could get rid of some
duplicatations here.

In addition to these Java files we supply
two resources: a JSON file with metadata and a HTML file with documentation.

The most interesting part of the JSON file
is (in my opinion) the remediation key: here you specify the amount of work to
fix the problem.

{

  „title“: „Avoid
usage of special Classes“,

  „status“:
„ready“,

  „remediation„: {

    „func„: „Constant\/Issue“,

    „constantCost“:
„5min“

  },

  „tags“: [

    „example“

  ],

  „defaultSeverity“:
„Minor“

}

The HTML file provides that part of the
which is shown as explanation of the rule.

blog1.jpg

Tests

Of course we have to test our code. The
example shows how to do that: provide classes which contains the error and use
org.sonar.java.checks.verifier.JavaCheckVerifier to verify that an issue was reported or not reported.

public class InValidFISInstance {

 

   
public void x() {

       
try (InputStream is = new
FileInputStream(
„test“)) {

           
is.available();

       
}
catch (IOException e) {

       
}

   
}

}

 

public class CompliantClass {

 

   
public void x() {

       
try (InputStream in = Files.newInputStream(Paths.get(„file.txt“))) {

           
in.available();

       
}
catch (IOException e) {

       
}

       
try (OutputStream out = Files.newOutputStream(Paths.get(„file.txt“))) {

           
out.flush();

       
}
catch (IOException e) {

       
}

   
}

   

}

 

public class AvoidClassRuleTest {

   

   
@Rule

   
public TestName testname = new
TestName();

 

 

   

   
@Test

    public void compliantClass() {

        verify( (file,rule) ->
JavaCheckVerifier.verifyNoIssue(
file, rule) );

   
}

   

   
@Test(expected=AssertionError.class)

   
public void invalidFISInstance()
{

       
verify( (
file,rule) ->
JavaCheckVerifier.verify(
file, rule) );

   
}

   

    private void
verify(BiConsumer
consumer) {

       
String
filename = String.format(„src/test/files/%s.java“,
StringUtils.capitalize(
testname.getMethodName()));

       
consumer.accept(filename, new
AvoidClassRule());

   
}

 

}

 

Some notes

The JSON and HTML resource have to be in /org/sonar/l10n/java/rules/squid/. Of course your RulesDefinition class could load them from wherever
you want, but the used JavaCheckVerifier expect them to be there.

The file names of the resources have to be ${ruleKey}.html and ${ruleKey}_${language}.json.

In constrast to the example I tend to also
have a positive test. I am not only interested in that the rule reports the
issue when required, it should do nothing if the code is compliant.

Rules could be parameterized via the web
ui. For that you annotate the field with
@RuleProperty. You could access the values via:

@Before

public void init() {

    JavaCustomRulesDefinition
rulesDefinition = new
JavaCustomRulesDefinition();

   
RulesDefinition.Context
context = new
RulesDefinition.Context();

    rulesDefinition.define(context);

    repository = context.repository((„RepositoryKey“);

}

 

@Test

public void
assertParameterProperties() {

    Param
param =
repository.rule(„RuleKey“).param(„paramName“);

    // Not
available:

    assertThat(param).isNull();

    // If
available:

    // assertThat(param).isNotNull();

    // assertThat(param.defaultValue()).isEqualTo(„Inject“);

    // assertThat(param.description()).isEqualTo(„…“);

    // assertThat(param.type()).isEqualTo(RuleParamType.STRING);

}

Werbung

Custom Eclipse Window Title

6. November 2012

I used Eclipse for a long time. Now I have to manage multiple running instances – mostly for the development branch and the production branch of our project. The problem is distinguishing the running instances by their task icon/window title. I search a little bit and found how to customize the branding or the -showlocation startup parameter. But after looking at the Eclipse preferences I found a very nice way: General | Workspace | Workspace name

Bild

This results in a nice and short solution to this problem – in the task bar

Bild

and in the Eclipse title bar

Bild

Custom Eclipse Window Title

6. November 2012

I used Eclipse for a long time. Now I have to manage multiple running instances – mostly for the development branch and the production branch of our project. The problem is distinguishing the running instances by their task icon/window title. I search a little bit and found how to customize the branding or the -showlocation startup parameter. But after looking at the Eclipse preferences I found a very nice way: General | Workspace | Workspace name

Bild

This results in a nice and short solution to this problem – in the task bar

Bild

and in the Eclipse title bar

Bild

Java-Cron-Jobs with Spring and Quartz

3. Februar 2012

We have several Jobs running the business. At the moment they are implemented as Spring-driven TimerTasks. But the next job should be run only nightly and a cron-like configuration syntax would be fine.

So I found Quartz and had to integrate that. For getting familiar with Quartz+Spring I wrote a small proof of concept.

The job implementation is just a POJO with a public void method. It should not throw any exception. The bean can be configured via usual Spring DI:

public class MyBean {

private String message;

public void doIt() {
System.out.println("Hello World: " + message);
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

So fine. But how to test? For this PoC a very simple test is ok – just wait for some Quartz run and check the output manually:

import static org.junit.Assert.assertNotNull;

import org.junit.AfterClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QuartzTest {

@Test
public void context() {
System.out.println("Starting Spring and within that: Quartz");
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
assertNotNull(ctx);
}

@AfterClass public static void sleep() throws InterruptedException {
System.out.println("Wait for job output");
Thread.sleep(8000);
System.out.println("ready");
}
}

When using Spring, we have to provide the configuration.
First I define my Job-bean

<bean id="myBean">
<property name="message" value="TEST" />
</bean>

After that I configure Quartz:

<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
scope="singleton">
<property name="triggers">
<list>
<!-- trigger list -->
<ref bean="job1" />
</list>
</property>
</bean>

The binding between job and Quartz is done via a configured CronTriggerBean.

<bean id="job1">
<property name="cronExpression" value="0/2 * * * * ?" />
<property name="jobDetail">
<bean>
<property name="name" value="job1" />
<property name="group" value="nightlyJobs" />
<!-- Delegieren auf unsere Bean und unsere Methode -->
<property name="targetObject" ref="myBean" />
<property name="targetMethod" value="doIt" />
<property name="concurrent" value="false" />
</bean>
</property>
</bean>

This CronTriggerBean defines two values:
1. cronExpression specifies when to run the job. An explanation about that syntax can be found at http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger.
2. jobDetail specifies a JavaBean with information about the job. But we dont have to write this Bean, we just can configure the generic one from Spring:
– name and group for controlling the execution via control interfaces
– targetObject and targetMethod for the delegation to our JobBean
– specify if this job should run in concurrent mode (where concurrent means in one VM!)

Building this sample with Maven is easy. You’ll need just following dependencies:

  • org.springframework::spring-core::3.0.5.RELEASE
  • org.springframework::spring-context::3.0.5.RELEASE
  • org.springframework::spring-context-support::3.0.5.RELEASE
  • org.springframework::spring-tx::3.0.5.RELEASE
  • org.quartz-scheduler::quartz::1.8.5
  • junit::junit::4.9::{scope=test}

As far as I read you can’t use Quartz 2.x because Spring 3 doesnt support that. But I havent tried it.

When running you’ll get this output:

Starting Spring and within that: Quartz
... logs from Spring
... infos from SLF4J
INFO: Starting Quartz Scheduler now
Wait for job output
Hello World: TEST
Hello World: TEST
Hello World: TEST
Hello World: TEST
Hello World: TEST
ready

Die Photovoltaikanlage im Steuerrecht

20. August 2011

Tja, nun bin ich auch betroffen. Ich habe eine Photovoltaikanlage geordert. Und der Vertreter sprach davon, dass man diese über 20 Jahre lang abschreiben kann und sogar die Mehrwertsteuer wiederbekommt! Toll …. Aber als ehemaliger Steuerrechtler wollte ich das genauer wissen. Ja, das EEG, das Erneuerbare-Energien-Gesetz, könnte ja so einiges bieten.

Aber fündig geworden bin ich ganz normal im Einkommensteuergesetz (EStG) wegen der Abschreibung und dem Umsatzsteuergesetz (UStG) wegen der Märchensteuer… Also mal von vorne 😉

Das UStG betrifft „Unternehmer“. Und jeder der „nachhaltig“ Einnahmen erzielt, ist erst einmal Unternehmer. Da ich nun mit der Photovoltaikanlage ein paar Jahre Strom einspeise und vergütet bekomme, ist dieses zu bejahen. Auf einen eventuellen Gewinn ist nach UStG übrigens nicht abzustellen. Ich bin also Unternehmer im Sinne der Umsatzsteuer. Damit habe ich entsprechende Rechte und Pflichten. Mein primäres Recht: der Vorsteuerabzug. Hierüber bekomme ich die USt des Kaufpreises wieder. Die Pflichten: regelmäßige Umsatzsteuererklärungen (idR jährlich) und die Versteuerung meiner Einnahmen. Ups – muss ich da 19% von meinem eingenommen Geld wieder abführen? Ne – der Energieversorger muss wissen, dass ich Unternehmer bin, dann zahlt er die oben drauf – meine „Rendite“ ist also nicht davon betroffen. 🙂

Einnahmen = Unternehmer = USt-Erklärung? Aber nicht immer! Das UStG führt im §19 die „Kleinunternehmerregel“. Wer wenig einnimmt, kann sich den ganzen steuerlichen Kram sparen. Es entfallen somit die lästigen Pflichten – aber eben auch die Rechte! Ich will aber meine Vorsteuer …. Ok, bleibe ich halt Unternehmer. Einen Strich könnte noch eine weitere Regel durch die Rechnung machen. Wenn meine Einnahmen komplett steuerfrei wären, könnte ich auch keine Vorsteuer abziehen. Sind sie aber nicht und daher bleibts beim Regelfall „Vorsteuer+Erklärungen“.

Aber wer vorher schon Kleinunternehmer war, muss etwas anderes berücksichtigen: das UStG kennt pro Person nur ein Unternehmen! Wenn die Photovoltaikanlage also regelbesteuert werden soll, dann werden auch die regelmäßigen eBay-Verkäufe oder Programmierarbeiten grundsätzlich steuerpflichtig … (eventuelle Steuerbefreiungen müssten dann geprüft werden). Also Vorsicht!

Nachdem ich also meine 19% Märchensteuer für den Kauf der Anlage wiederbekomme, die abzuführende Märchensteuer für die Einspeisung vom Versorger oben drauf kriege und also nur regelmäßig meine Steuerklärung machen muss, wäre noch zu klären, wie das mit der Abschreibung kommt.

Die Antwort liegt im EStG. Dieses gilt für alle „unbeschränkt Einkommersteuerpflichtigen“. Jemand mit Hauptwohnsitz in Deutschland ist das. Und damit dürfte dann die meisten sein, die sich eine PV-Anlagen aufs eigene Dach schrauben lassen… Per EStG greift der Staat nun für jeden verdienten Euro etwas ab. Auch hier gibt es Befreiungsvorschriften, die aber nicht zum Zuge kommen. Die Frage stellt sich nun nach dem Verdienst.

Mit dem Einspeisen von Strom in das Stromnetz gegen Geld nehme ich am gewerblichen Leben teil. Damit sind die Einspeisevergütungen Einnahmen aus Gewerbebetrieb (§15 EStG). (@myself: Vielleicht noch mal genauer subsummieren 😉 Der zu versteuernde „Verdienst“ ermittelt sich somit nach §4 und im einfachen Fall nach §4(3) EStG – der „Einnahme-Überschuss-Rechnung“. Also: alle Einnahmen abzüglich aller Ausgaben ergibt den Gewinn oder halt den Verlust, der dann mit allen anderen Einnahmen (z.B. Arbeitslohn, Künstlerhonorar, Mieteinnahmen, …) zusammen zur Einkommensteuer veranlagt wird.

Also alle Einnahmen: mmh, da wäre nur die brutto-Einspeisevergütung.

Und die Ausgaben? Der direkte Geldabfluss: die USt auf die Einspeisevergütung, die ich ja ans Finanzamt abführen muss. Eventuelle Ausgaben für eine PV-Versicherung, …. falls mal eine Wartung fällig wird … Finanzierungskosten (Zinsen, falls ich die Anlage fremdfinanziere) … Und dann noch die „umgelegten Ausgaben“ – die „Abschreibung für Abnutzung“ oder kurz AfA. Die kann ich gem. §7 EStG ansetzten und zwar so, dass die Anschaffungs- oder Herstellungskosten auf die Nutzungsdauer umgelegt werden. Die Anschaffungskosten sind hier der Netto-Preis, da ich als (USt)-Unternehmer die Märchensteuer ja nicht selber tragen muss. Die Nutzungsdauer wurde mal mit 20 Jahren festgelegt. Die Abschreibung kann mittlerweile nur noch linear erfolgen, so dass ich 5% jährlich abschreiben kann. Wobei allerdings monatsgenau zu rechnen ist.

Spitze, habe ich also auch die Abschreibung gefunden. Aber halt – da gibt es noch eine: Zur Förderung kleiner Betriebe (so wie mein PV-Betrieb) hat der Gesetzgeber die Förderung nach §7g EStG „Investitionsabzugsbeträge und Sonderabschreibungen zur Förderung kleiner und mittlerer Betriebe“ eingeführt. Mal genauer ansehen: „Steuerpflichte können für zukünftige Anschaffungen von beweglichen abnutzbaren Wirtschaftsgütern bis zu 40% der AK abziehen, wenn [der Betrieb klein ist, also bei einer 4(3)-Rechnung nicht mehr als 100.000 Euro jährlich rausspringen.“ Klingt gut, wenn es da nicht heißen würde „zukünftig“. Also im folgenden Jahr…. Also für alle, die die PV noch planen: wenn der Auftrag dieses Jahr rausgeht, aber erst im nächsten Jahr realisiert wird, wird das für Euch interessant! Aber dieser Abzug verschiebt nur die Kosten – der im Vorjahr abgezogene Betrag ist im Investitionsjahr wieder drauf zu rechnen. Schade …

Aber noch einen im 7g: nach Absatz 5 können zusätzlich zur regulären (monatsgenauen) AfA weitere 20% in den ersten fünf Jahren abgesetzt werden! (Was dann natürlich nicht das Abschreibungsvolumen erhöht. Die Anlage ist dann schneller abgeschrieben.) Mal genauer ansehen:

  1. abnutzbar
  2. beweglich
  3. Wirtschaftsgut (WG) des Anlagevermögens
  4. Voraussetzungen des Absatzes 6:
    1. Kleinbetrieb wie vor (4(3)-Überschuss 100.000 €; 4(1)-Bilanz-Betriebsvermögen bis 235.000 €)
    2. WG im Anschaffungs- und Folgejahr im Inland
    3. fast ausschließlich betrieblich genutzt

Also:

  • „abnutzbar“: jepp, sonst könnte ich das ja gar nicht linear abschreiben (bND=20Jahre)
  • „WG des AV“: jepp, will die Anlage ja betreiben
  • „Kleinbetrieb“: so groß ist meine PV auch wieder nicht, also ja.
  • „Inland“: da steht mein Haus, also auch ok
  • „betriebliche Nutzung“: sowohl das Einspeisen von Strom bringt Geld als auch der Eigenverbrauch (!). Damit 100% „betriebliche“ Nutzung.
  • „beweglich“????? Die ist doch fest am Dach! Aber halt nicht fest genug 🙂 Man könnte sie abmontieren ohne dass die PV oder das Haus Schaden nehmen würde. Damit liegt ein „Scheinbestandteil“ des Hauses vor und die PV bleibt „beweglich“ – puh …. Also auch ok.

Damit habe ich eine zusätzliche Abschreibungsmöglichkeit gefunden.

Dem Gewerbesteuerrecht widme ich mich jetzt hier nicht. Ein paar Links müsste ich noch einpflegen … Aber noch kurz eine Anregung wegen der Finanzierungskosten: Wenn zusätzlich zur PV beispielsweise noch ein Auto oder eine neue Heizung fällig wird und nicht beides direkt bezahlt werden kann, dann bitte die PV finanzieren, da diese Zinsen bei der ESt abgesetzt werden können. Bei Auto und Heizung ist das eher unwahrscheinlich … Ein nachträgliches Ändern müsste gehen (ich meine, da gab es mal einige BFH-Urteile), werden aber bestimmt nicht so einfach geschluckt …

Musical production has finished

30. Januar 2010

Some years ago a friend of mine – Richard – has written a musical (with his cousin). I joined with my trumpet and wrote the brass parts. Then sadly the project stopped …

But Richard has restarted the project and could produce the musical on CD (without brass 😦 ). But a demo is on youtube:

Links for 2009-05-29

29. Mai 2009

There is a new Windows 7 Blog by Microsoft MVPs

On DrBacchus is also a short article about the PHP MVC framework CakePHP. And a list of top-10 php frameworks on mustap.com

On MSDN there is a five part webcast series about programming with the task parallel library which will be part of Visual Studio 2010.

In his blog Jason Zander shows the highlights of VS 2010 and .NET 4.0.

Microsoft publishes a free tool for developing secure software.

JBoss 5.1 is out.

On Windowsblog@TheShop.at is a compatibility list of programs on Windows 7.

If you need an additional automat in your office (very nice for lunch) have a look at this video.

Links for 2009-05-12

12. Mai 2009

On 14.May there is free webinar about JSF 2.0 by Ed Burns.

Pearl provides with Tape2PC a hardware solution for copying from MC (music cassetes) to your PC (mp3).

With CamSpace you could control games, windows an applications via webcam. There is foto galery by chip.de.

Saros is a free available Eclipse plugin for pair programming. A demo online.

With Axum Microsoft releases a new programming language for parallel programming.

Links for 2009-01-28

28. Januar 2009

I read a blog about „How to log“ which refers to the logging checklist. If you want to get benefit from your logs, you should have a look at them.

According to Testticker.DE and ZDnet.de Microsoft gives software to students for free.

Another blog gave me the link to Java To C# Orange Book, which I’ll read in the future. But there are other interesting links für C# friends.

If you dont know whether to use a software version system because you are developing for your own, have a look at this. The author gives multiple reasons for using a VC.

On 1stWebdesigner.com there is a nice overview of free available galleries. I think I will use one for my site.

Jetty is now under the hood of Eclipse and I think it will benefit from that. (Is Jetty serving Eclipse helpfiles at the moment?)

Another tool worth looking at is APrompt which checks a website for accessibility. (Screen reader, colors etc…)

Vista looses monitor settings … (no more)

27. Januar 2009

I have two notebooks (Dell Lattitude D510 + Acer Aspire 5920G) connected via KMV-switch conntected to a 28″ monitor. It is nice to switch between the two notebooks. But while switching to the Dell (with WinXP) works fine, switching to the Acer is a pain: Vista always looses the monitor settings. The external monitor should work on 1920×1680 pixel resolution, should be the main monitor and is left from the notebook. And these settings are lost (1280er resolution, 2nd monitor, right from the notebook). Redoing these settings is always a seven step work. Ok when doing once a day. But always when switching? Brrrr … I thought for a long time that this „Vista bug“ should be fixed via Windows Update, but no update fixed that …

So I read different posts, but the best (which works on my my machine) was updating the graphics driver (on Microsoft TechNet Forum „Vista forgets display settings?“ – answer from 26.August 2007 11:19:46 by Andreas Stenhall. (Havent found a Permlink, sorry))

I recommend doing a restore point before installing the new driver.

Check what graphic card is built into your computer, download the driver and install that.

After that – it works with my settings 😉