How to enforce multiple exception catchs in separate lines with checkstyle or PMD? - static-analysis

We're using checkstyle and PMD in our project and I'm looking for a way to enforce newlines between multiple catchs in one row, e.g.
} catch(IOException | IllegalArgumentException ex) {
...
}
should fail the validation whereas
} catch(IOException
| IllegalArgumentException ex) {
...
}
should pass.
I'm not looking for alternatives like randomly working code formatters which introduce dependency on the IDE.
We're using checkstyle and PMD through Maven.

A simple XPath-based rule for PMD could use this XPath expression:
<rule name="MultipleCatchTypesOnSeparateLines"
language="java"
message="Use a separate line for each catch type"
class="net.sourceforge.pmd.lang.rule.XPathRule"
<description>TODO</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CatchStatement/FormalParameter[#SingleLine = true()]
]]>
</value>
</property>
<property name="version" value="2.0"/>
</properties>
</rule>
A more complex one, that would detect cases, where you have e.g. 3 catchs on 2 lines (which should be on three lines):
<rule name="MultipleCatchTypesOnSeparateLines"
language="java"
message="Use a separate line for each catch type"
class="net.sourceforge.pmd.lang.rule.XPathRule"
<description>TODO</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
for $a in //CatchStatement/FormalParameter
return for $b in (1 to count($a/Type))
return $a[Type[$b][#BeginLine = $a/Type[$b + 1]/#BeginLine]]
]]>
</value>
</property>
<property name="version" value="2.0"/>
</properties>
</rule>
Please note: With PMD you cannot verify that the | character is on the next line. This token is not available in the AST.

Related

get_activate not found in gtk::Swtich

I've been following a project based book which uses gtk and glade to build a UI. Went all fine until I got to using a gtk::Switch which the book uses like this:
let builder = gtk::Builder::from_string(include_str!("glade_config.glade"));
// ...
let is_dead_switch: gtk::Switch = builder
.get_object("is_dead_switch")
.unwrap();
Later on, to get the switch state it uses is_dead_switch.get_activate() but the method seems to no longer be a thing. I've looked into the documentation and found that gtk::Switch only has gtk::Switch::new listed as method. Anyone knows what's missing or what's wrong?
Cargo.toml dependencies:
[dependencies]
gio = "0.9.1"
[dependencies.gtk]
version = "0.9.2"
features = ["v3_22"]
glade config file stating this part:
<child>
<object class="GtkSwitch" id="is_dead_switch">
<property name="visible">True</property>
<property name="can_focus">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>

WSO2 websocket + SockJS - Cross origin requests blocked

Since WSO2 5.0 supports WebSockets, I have written a simple app following by tutorials:
WebSocket Transport
Sending a Message from a WebSocket Client to an HTTP Endpoint
Here's my source view output from WSO2:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://ws.apache.org/ns/synapse">
<registry provider="org.wso2.carbon.mediation.registry.WSO2Registry">
<parameter name="cachableDuration">15000</parameter>
</registry>
<taskManager provider="org.wso2.carbon.mediation.ntask.NTaskTaskManager"/>
<sequence name="fault">
<!-- Log the message at the full log level with the ERROR_MESSAGE and the ERROR_CODE-->
<log level="full">
<property name="MESSAGE" value="Executing default 'fault' sequence"/>
<property expression="get-property('ERROR_CODE')" name="ERROR_CODE"/>
<property expression="get-property('ERROR_MESSAGE')" name="ERROR_MESSAGE"/>
</log>
<!-- Drops the messages by default if there is a fault -->
<drop/>
</sequence>
<sequence name="main">
<in>
<!-- Log all messages passing through -->
<log level="full"/>
<!-- ensure that the default configuration only sends if it is one of samples -->
<!-- Otherwise Synapse would be an open proxy by default (BAD!) -->
<filter regex="http://localhost:9000.*" source="get-property('To')">
<!-- Send the messages where they have been sent (i.e. implicit "To" EPR) -->
<send/>
</filter>
</in>
<out>
<send/>
</out>
<description>The main sequence for the message mediation</description>
</sequence>
<sequence name="outDispatchSeq">
<log level="full"/>
<respond/>
</sequence>
<sequence name="dispatchSeq">
<switch
source="get-property('websocket.source.handshake.present')" xmlns:ns="http://org.apache.synapse/xsd">
<case regex="true">
<drop/>
</case>
<default>
<call/>
<respond/>
</default>
</switch>
</sequence>
<!-- You can add any flat sequences, endpoints, etc.. to this synapse.xml file if you do
*not* want to keep the artifacts in several files -->
<inboundEndpoint name="test" onError="fault" protocol="ws"
sequence="dispatchSeq" suspend="false">
<parameters>
<parameter name="inbound.ws.port">9091</parameter>
<parameter name="ws.client.side.broadcast.level">0</parameter>
<parameter name="ws.outflow.dispatch.sequence">outDispatchSeq</parameter>
<parameter name="ws.outflow.dispatch.fault.sequence">fault</parameter>
</parameters>
</inboundEndpoint>
</definitions>
I was able to successfully test it with Nett client:
C:\work\servers\netty>java -Durl=ws://localhost:9091/websocket -DsubProtocol="synapse(contentType='application/xml')" -cp netty-example-4.1.4.Final.jar;lib/*;. io.netty.example.http.websocketx.client.WebSocketClient
WebSocket Client connected!
However if I try to test it from JavaScript code I am getting error like:
Do you know what is wrong in my code?
This issue occurs because SockJS internally trying to load the URL using XMLHttpRequest, but Chrome does not allow accessing cross origin content unless the protocol is one of the aforementioned protocols (In this case it is ws://). I have tried a similar scenario with Firefox and it works fine since it doesn't have this Chrome specific limitation.
In this scenario since WSO2 ESB exposes a WebSocket interface to invoke the HTTP Endpoint, you can use native HTML5 WebSocket implementation as follows.
var url = 'ws://localhost:9091/websocket';
var ws = new WebSocket(url);
ws.onopen = function() {
// todo
}
ws.onmessage = function(e) {
// todo
}

How can I get a pathname from a groupId? [duplicate]

Is there a simple way of taking the value of a property and then copy it to another property with certain characters replaced?
Say propA=This is a value. I want to replace all the spaces in it into underscores, resulting in propB=This_is_a_value.
Here is the solution without scripting and no external jars like ant-conrib:
The trick is to use ANT's resources:
There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
<propertyresource name="propA"/>
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from=" " to="_"/>
</tokenfilter>
</filterchain>
</loadresource>
This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.
You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html
Use the propertyregex task from Ant Contrib.
I think you want:
<propertyregex property="propB"
input="${propA}"
regexp=" "
replace="_"
global="true" />
Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValue option as well.
If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:
<property name="before" value="This is a value"/>
<script language="javascript">
var before = project.getProperty("before");
project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>
In case you want a solution that does use Ant built-ins only, consider this:
<target name="replace-spaces">
<property name="propA" value="This is a value" />
<echo message="${propA}" file="some.tmp.file" />
<loadfile property="propB" srcFile="some.tmp.file">
<filterchain>
<tokenfilter>
<replaceregex pattern=" " replace="_" flags="g"/>
</tokenfilter>
</filterchain>
</loadfile>
<echo message="$${propB} = "${propB}"" />
</target>
Output is ${propB} = "This_is_a_value"
Use some external app like sed:
<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
<arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>
If you run Windows get it googling for "gnuwin32 sed".
The command s/_/./g replaces every _ with .
This script goes well under windows. Under linux arg may need quoting.
Two possibilities :
via script task and builtin javascript engine (if using jdk >= 1.6)
<project>
<property name="propA" value="This is a value"/>
<script language="javascript">
project.setProperty('propB', project.getProperty('propA').
replace(" ", "_"));
</script>
<echo>$${propB} => ${propB}</echo>
</project>
or using Ant addon Flaka
<project xmlns:fl="antlib:it.haefelinger.flaka">
<property name="propA" value="This is a value"/>
<fl:let> propB := replace('${propA}', '_', ' ')</fl:let>
<echo>$${propB} => ${propB}</echo>
</project>
to overwrite exisiting property propA simply replace propB with propA
Here's a more generalized version of Uwe Schindler's answer:
You can use a macrodef to create a custom task.
<macrodef name="replaceproperty" taskname="#{taskname}">
<attribute name="src" />
<attribute name="dest" default="" />
<attribute name="replace" default="" />
<attribute name="with" default="" />
<sequential>
<loadresource property="#{dest}">
<propertyresource name="#{src}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from="#{replace}" to="#{with}"/>
</tokenfilter>
</filterchain>
</loadresource>
</sequential>
</macrodef>
you can use this as follows:
<replaceproperty src="property1" dest="property2" replace=" " with="_"/>
this will be pretty useful if you are doing this multiple times
Adding an answer more complete example over a previous answer
<property name="propB_" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propB_" />
<filterchain>
<tokenfilter>
<replaceregex pattern="\." replace="/" flags="g"/>
</tokenfilter>
</filterchain>
</loadresource>
Just an FYI for answer Replacing characters in Ant property - if you are trying to use this inside of a maven execution, you can't reference maven variables directly. You will need something like this:
...
<target>
<property name="propATemp" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propATemp" />
...
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${#{varName}}"/>
<property name="fromProp" value = "#{from}"/>
<property name="toProp" value = "#{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="#{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
Or... You can also to try Your Own Task
JAVA CODE:
class CustomString extends Task{
private String type, string, before, after, returnValue;
public void execute() {
if (getType().equals("replace")) {
replace(getString(), getBefore(), getAfter());
}
}
private void replace(String str, String a, String b){
String results = str.replace(a, b);
Project project = getProject();
project.setProperty(getReturnValue(), results);
}
..all getter and setter..
ANT SCRIPT
...
<project name="ant-test" default="build">
<target name="build" depends="compile, run"/>
<target name="clean">
<delete dir="build" />
</target>
<target name="compile" depends="clean">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes" includeantruntime="true"/>
</target>
<target name="declare" depends="compile">
<taskdef name="string" classname="CustomString" classpath="build/classes" />
</target>
<!-- Replacing characters in Ant property -->
<target name="run" depends="declare">
<property name="propA" value="This is a value"/>
<echo message="propA=${propA}" />
<string type="replace" string="${propA}" before=" " after="_" returnvalue="propB"/>
<echo message="propB=${propB}" />
</target>
CONSOLE:
run:
[echo] propA=This is a value
[echo] propB=This_is_a_value

StaxEventItemReader - skip XML fragments processed in previous Job executions

When working with CSV files and restarting a FAILED Job, a StepExecutionListner and associated beforeStep( ....) method can be used to position
the reader within the file. So the code could look something like:
public void beforeStep(StepExecution stepExecution) {
ExecutionContext executionContext = stepExecution.getExecutionContext();
if (executionContext.containsKey(getKey(LINES_READ_COUNT))) {
long lineCount = executionContext.getLong(getKey(LINES_READ_COUNT));
LineReader reader = getReader();
Object record = "";
while (reader.getPosition() < lineCount && record != null) {
record = readLine();
}
}
} // Or something similar
My question is how do you achieve the same thing when working with a StaxEventItemReader?
My batch_step_execution_context looks something like {"string":"StaxEventItemReader.read.count","int":6}. So in my case the
the first 5 XML fragment were successfully processed and upon restarting the Job I would like to start processing from XML fragment number 6 onwards.
Given the config below, how would I position the reader within the XML file?
<batch:job id="reportJob" restartable="true">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="xmlItemReader" writer="cvsFileItemWriter" processor="filterReportProcessor"
commit-interval="1">
</batch:chunk>
<batch:listeners>
<batch:listener ref="step1Listener" />
</batch:listeners>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="step1Listener" class="com.mkyong.listeners.Step1Listener" />
<bean id="filterReportProcessor" class="com.mkyong.processor.FilterReportProcessor" />
<bean id="xmlItemReader" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="fragmentRootElementName" value="record" />
<property name="resource" value="classpath:xml/report.xml" />
<property name="unmarshaller" ref="reportUnmarshaller" />
</bean>
<!-- Read and map values to object, via jaxb2 -->
<bean id="reportUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.mkyong.model.Report</value>
</list>
</property>
</bean>
Environment - spring-batch-core-2.2.0; spring-core-3.2.2
Test Input File
Convert a XML file into a CSV file.
<company>
<record refId="1001">
<name>mkyong</name>
<age>31</age>
<dob>31/8/1982</dob>
<income>200,000</income>
</record>
<record refId="1002">
<name>kkwong</name>
<age>30</age>
<dob>26/7/1983</dob>
<income>100,999</income>
</record>
<record refId="1003">
<name>joel</name>
<age>29</age>
<dob>21/8/1984</dob>
<income>1,000,000</income>
</record>
<record refId="1004">
<name>leeyy</name>
<age>29</age>
<dob>21/3/1984</dob>
<income>80,000.89</income>
</record>
<record refId="1005">
<name>Grant</name>
<age>29</age>
<dob>21/3/1984</dob>
<income>80,000.89</income>
</record>
</company>
Test Run 1
After processing two records in the input file, I forced a RunTimeException.
batch_job_execution --->> "FAILED";"FAILED";"java.lang.RuntimeException: Get me out of here!
batch_step_execution_context --->> {"string":"StaxEventItemReader.read.count","int":2}
Output CSV file --->> 1001,mkyong,31,31/08/1982,200000
1002,kkwong,30,26/07/1983,100999
Test Run 2
Process all "remaining data", so expecting .... refId="1003", refId="1004", refId="1005"
batch_job_execution --->> "COMPLETED";"COMPLETED";"''";"2015-01-25 16:18:08.587"
batch_step_execution_context --->> {"string":"StaxEventItemReader.read.count","int":6}
Output CSV file --->> 1001,mkyong,31,31/08/1982,200000
1002,kkwong,30,26/07/1983,100999
1003,joel,29,21/08/1984,1000000
1004,leeyy,29,21/03/1984,80000.89
1005,Grant,29,21/03/1984,80000.89
Test Result
Unfortunately it looks like the StaxEventItemReader is reading from the beginning of the file, rather than re-positioning itself based on the value of StaxEventItemReader.read.count which is set to 2 after the first test.
You don't need to configure anything, this is already the default behavior of the StaxEventItemReader. When it opens it repositions itself from the read count in the step execution context.

Why are Gdk::Pixbufs not visible in Gtk::TreeView?

After spending a long time searching for an answer, I hope someone can help me with this problem. I'm trying to use gtkmm (version 3.14.0) and glade (version 3.18.3) on a Fedora 21 system to create a Gtk::TreeView/Gtk::ListStore with many small images. I can easily place stock icons in the list, but adding Gdk::Pixbuf objects seems to go wrong. No error or warning messages are shown, but the Gdk::Pixbuf image is not shown.
To show the problem, I've created a minimal working example (the code of the program and the glade file included at the end). Running this program should open a small window with the Gtk::TreeView with two "gtk-apply" icons. In the first column should be the icon added as Gdk::Pixbuf, in the second column should be the stock icon. However, when I run the program, the first column remains empty. There are no compile or run-time errors or warnings.
My final application will display a matrix of about 100 rows and about 35 columns of mostly tiny icons allowing a quick overview of activities done on the different days of a month. None of these icons will be stock icons.
Extra Information: Following the program execution using a debugger, I found that the Gtk::ListStore's first column wants data of type gtkmm__GdkPixbuf. The type of pb in the line row[cols.m_pb] = pb is GdkPixbuf. The type GdkPixbuf cannot be converted to gtkmm__GdkPixbuf automatically, causing the value to be set to 0 (NULL). Obviously this does not solve the problem, but might help to solve the problem.
Thanks for the help and best wishes for 2015,
Wim
This is the file mwe.glade:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
<requires lib="gtk+" version="3.12"/>
<object class="GtkAccelGroup" id="accelgroup1"/>
<object class="GtkApplicationWindow" id="mainwindow">
<property name="can_focus">False</property>
<property name="show_menubar">False</property>
<child>
<object class="GtkGrid" id="mainbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkTreeView" id="treattree">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="vexpand">True</property>
<property name="hscroll_policy">natural</property>
<property name="model">treatstore</property>
<property name="rules_hint">True</property>
<property name="search_column">0</property>
<property name="fixed_height_mode">True</property>
<child internal-child="selection">
<object class="GtkTreeSelection" id="sel1"/>
</child>
<child>
<object class="GtkTreeViewColumn" id="col1">
<property name="sizing">fixed</property>
<property name="fixed_width">32</property>
<property name="title">1</property>
<child>
<object class="GtkCellRendererPixbuf" id="cell1">
<property name="width">16</property>
<property name="height">16</property>
</object>
<attributes>
<attribute name="pixbuf">0</attribute>
</attributes>
</child>
</object>
</child>
<child>
<object class="GtkTreeViewColumn" id="col2">
<property name="sizing">fixed</property>
<property name="fixed_width">32</property>
<property name="title">2</property>
<child>
<object class="GtkCellRendererPixbuf" id="cell2"/>
<attributes>
<attribute name="stock-id">1</attribute>
</attributes>
</child>
</object>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkListStore" id="treatstore">
<columns>
<!-- column-name col1 -->
<column type="GdkPixbuf"/>
<!-- column-name col2 -->
<column type="gchararray"/>
</columns>
</object>
</interface>
The file mwe.cpp:
#include <gtkmm.h>
namespace ws
{
class App : public Gtk::Application
{
protected:
App() : Gtk::Application("nl.mwe.mwe"), m_mainwindow(0)
{
Glib::set_application_name("MWE");
}
public:
static Glib::RefPtr<App> create(int &argc, char **&argv)
{
return Glib::RefPtr<App>(new App());
}
void init(Glib::RefPtr<Gtk::Builder> builder);
int run()
{
return Gtk::Application::run(*m_mainwindow);
}
private:
Gtk::ApplicationWindow *m_mainwindow;
};
// Definition of the column references
class ModelColumns : public Gtk::TreeModelColumnRecord
{
public:
ModelColumns()
{
add(m_pb);
add(m_stock);
}
Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> > m_pb;
Gtk::TreeModelColumn<Glib::ustring> m_stock;
};
static ModelColumns col;
} // End namespace ws
/**
* \brief Initialize the app
* \param[in] builder The builder object
*
* Here is where the list store is populated with the Gdk::Pixbuf
*/
void ws::App::init(Glib::RefPtr<Gtk::Builder> builder)
{
builder->get_widget("mainwindow", m_mainwindow);
m_mainwindow->show();
Glib::RefPtr<Gtk::ListStore> store =
Glib::RefPtr<Gtk::ListStore>::cast_static(
builder->get_object("treatstore"));
Gtk::TreeModel::Row row = *store->append();
// The line below loads the stock icon as a pixbuf.
Glib::RefPtr<Gdk::Pixbuf> pb =
Gtk::IconTheme::get_default()->load_icon("gtk-apply", 16);
row[col.m_pb] = pb;
row[col.m_stock] = "gtk-apply";
}
int main (int argc, char *argv[])
{
Glib::RefPtr<ws::App> myapp = ws::App::create(argc, argv);
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create();
builder->add_from_file("mwe.glade");
myapp->init(builder);
return myapp->run();
}
After finding the problems in the types as shown in the Extra Information
section in the question, I decided to create the store by hand. The definition
of the GtkListStore was removed from the glade file. The ws::App::init()
method was changed to:
void ws::App::init(Glib::RefPtr<Gtk::Builder> builder)
{
builder->get_widget("mainwindow", m_mainwindow);
Gtk::TreeView *treeview = 0;
builder->get_widget("treattree", treeview);
Glib::RefPtr<Gtk::ListStore> store =
Gtk::ListStore::create(col);
treeview->set_model(store);
Gtk::TreeModel::Row row = *store->append();
// The line below loads the stock icon as a pixbuf.
Glib::RefPtr<Gdk::Pixbuf> pb =
Gtk::IconTheme::get_default()->load_icon("gtk-apply", 16);
row[col.m_pb] = pb;
row[col.m_stock] = "gtk-apply";
m_mainwindow->show();
}
Although this is not as flexible as hoped, it does fix the problem.

Resources