Checkstyle doesn't work with SuppressionCommentFilter - checkstyle

Below is my code around check style - but it doesnt seem to suppress the audits between the suppression comment lines. I also tried with inline comment // instead of /* */
Please help. I have trying a lot of ways - permutation/combinations of those to get this fixed. Thank you.
Please let me know if you need more info.
/* CHECKSTYLE:OFF */
private abc createTimerChart(String title, String yAxisLabel, XYDataset dataset) {
final abc chart = ChartFactory.createXYLineChart(title, // chart title
"Time Elapsed (" + pollUnit.toString() + ")", // x axis label
yAxisLabel, // y axis label
dataset, // data
PlotOrientation.VERTICAL, true, // include legend
true, // tooltips
false // urls
);
/* CHECKSTYLE:ON */
CONFIG.XML reads:
<module name="FileContentsHolder">
<module name="SuppressionCommentFilter">
<property name="checkFormat" value="IndentationCheck"/>
</module>
</module>
AFTER MOVING SuppressionCommentFilter UNDER CHECKER:
<module name="Checker">
<!-- setting the default severity to warning -->
<property name="severity" value="warning" />
<module name="SuppressionCommentFilter">
<property name="checkFormat" value="Indentation"/>
</module>
<!-- No TAB characters in the source code -->
<module name="FileTabCharacter" />
<!-- List of files to ignore . -->
<!-- TODO Add all auto-generated files to this file -->
<module name="SuppressionFilter">
<property name="file" value="checkstyle/kepler-checkstyle-suppressions.xml"/>
</module>
<module name="TreeWalker">
..
..
..

The indentation check is called Indentation. It shold work if you change the checkFormat property to just Indentation:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="severity" value="warning" />
<module name="TreeWalker">
<module name="JavadocType" />
<module name="Indentation" />
<module name="FileContentsHolder"/>
</module>
<module name="SuppressionCommentFilter">
<property name="checkFormat" value="Indentation" />
</module>
</module>
Or, more generally, I would recommend not setting the checkFormat property at all, which will make the suppression comment suppress all warnings for that block of code.

Related

Camel DataFormat Jackson using blueprint XML DSL throws context exception

No matter where I place the dataformats in XML DSL blueprint, I get this error just starting at different places. if I remove it, it works but of course I can't convert JSON to POJO. ??? any help or tell me what I'm doing wrong, what i'm missing. thanks!
Error
Unable to start blueprint container for bundle passthrumt1.core/1.0.1.SNAPSHOT
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'endpoint'. One of '{"http://camel.apache.org/schema/blueprint":redeliveryPolicyProfile, "http://camel.apache.org/schema/blueprint":onException, "http://camel.apache.org/schema/blueprint":onCompletion, "http://camel.apache.org/schema/blueprint":intercept, "http://camel.apache.org/schema/blueprint":interceptFrom, "http://camel.apache.org/schema/blueprint":interceptSendToEndpoint, "http://camel.apache.org/schema/blueprint":restConfiguration, "http://camel.apache.org/schema/blueprint":rest, "http://camel.apache.org/schema/blueprint":route}' is expected.
XML DSL
<camelContext
id="com.passthru.coreCamelContext"
trace="true"
xmlns="http://camel.apache.org/schema/blueprint"
allowUseOriginalMessage="false"
streamCache="true"
errorHandlerRef="deadLetterErrorHandler" >
<properties>
<property key="http.proxyHost" value="PITC-Zscaler-Americas.proxy.corporate.com"/>
<property key="http.proxyPort" value="80"/>
</properties>
<streamCaching id="CacheConfig"
spoolUsedHeapMemoryThreshold="70"
anySpoolRules="true"/>
<!-- -->
<dataFormats>
<json id="Json2Pojo" library="Jackson" unmarshalTypeName="com.passthru.core.entities.TokenEntities">
</json>
</dataFormats>
<endpoint id="predixConsumer" uri="direct:preConsumer" />
<endpoint id="predixProducer" uri="direct:preProducer" />
<endpoint id="getToken" uri="direct:getToken" />
<onException>
<exception>com.passthru.dataservice.PDXDataServiceInvalidDataException</exception>
<redeliveryPolicy maximumRedeliveries="3" />
<handled>
<constant>true</constant>
</handled>
<log
message="Invalid Data From Data Service"
loggingLevel="ERROR" />
<setBody>
<simple>${body.toString}</simple>
</setBody>
<to uri="file:{{errorArchive}}" />
</onException>
If I place the dataformats above properties, it complains, I have to remove properties and streamcache statements in order for it to work. but I need the proxy properties. any suggestions??? thanks again
If the
<camelContext
id="com.ge.digital.passthru.coreCamelContext"
trace="true"
xmlns="http://camel.apache.org/schema/blueprint"
allowUseOriginalMessage="false"
streamCache="true"
errorHandlerRef="deadLetterErrorHandler" >
<dataFormats>
<json id="Json2Pojo" library="Jackson" unmarshalTypeName="com.passthru.core.entities.TokenEntities"/>
</dataFormats>
<properties>
<property key="http.proxyHost" value="PITC-Zscaler-Americas-Cincinnati3PR.proxy.corporate.com"/>
<property key="http.proxyPort" value="80"/>
</properties>
i get this
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'properties'. One of '{"http://camel.apache.org/schema/blueprint":redeliveryPolicyProfile, "http://camel.apache.org/schema/blueprint":onException, "http://camel.apache.org/schema/blueprint":onCompletion, "http://camel.apache.org/schema/blueprint":intercept, "http://camel.apache.org/schema/blueprint":interceptFrom, "http://camel.apache.org/schema/blueprint":interceptSendToEndpoint, "http://camel.apache.org/schema/blueprint":restConfiguration, "http://camel.apache.org/schema/blueprint":rest, "http://camel.apache.org/schema/blueprint":route}' is expected.
what am I missing?
Camel blueprint XML is validated against camel-blueprint.xsd.
You are interested in complex type with name camelContextFactoryBean which contains sequence of available elements with fixed order.
Correct order of camelContext elements defined in this sequence is:
properties
globalOptions
propertyPlaceholder
package
packageScan
contextScan
jmxAgent
streamCaching
export
defaultServiceCallConfiguration
serviceCallConfiguration
defaultHystrixConfiguration
hystrixConfiguration
routeBuilder
routeContextRef
restContextRef
threadPoolProfile
threadPool
endpoint
dataFormats
transformers
validators
redeliveryPolicyProfile
onException
onCompletion
intercept
interceptFrom
interceptSendToEndpoint
restConfiguration
rest
route
To solve your problem move all endpoint declarations right above dataFormats.

Duplicate record errors in Hibernate Search backed by Infinispan in an EC2 cluster

We have an application that works in an EC2 cluster (2 nodes currently for testing). For searching domain models we use Hibernate Search, and since the application runs on a cluster we use Infinispan as the Lucene Directory. To survive restarts we use a JDBC cache store on MySQL, both nodes accessing the same MySQL tables. To account for adding and removing nodes, we use the "jgroups" backend for Hibernate Search worker configuration.
Our problem is about duplicate records exceptions we receive when we try to rebuild the whole entity index. We get errors with similar stacktraces as this:
ERROR [AsyncStoreProcessor-LuceneIndexesData-0] [2016-06-21 17:01:59] org.infinispan.persistence.jdbc.stringbased.JdbcStringBasedStore - ISPN008024: Error while storing string key to database; key: '_d.fdt|0|1048576|com.model.SomeModel'
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '_d.fdt|0|1048576|com.model.SomeModel' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1399)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:857)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361)
at com.zaxxer.hikari.proxy.PreparedStatementJavassistProxy.executeUpdate(PreparedStatementJavassistProxy.java)
at org.infinispan.persistence.jdbc.stringbased.JdbcStringBasedStore.write(JdbcStringBasedStore.java:174)
at org.infinispan.persistence.async.AsyncCacheWriter.applyModificationsSync(AsyncCacheWriter.java:158)
at org.infinispan.persistence.async.AsyncCacheWriter$AsyncStoreProcessor.retryWork(AsyncCacheWriter.java:330)
at org.infinispan.persistence.async.AsyncCacheWriter$AsyncStoreProcessor.run(AsyncCacheWriter.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
When we check the DB, there is an entry with this ID. When we try it with a single node there are no errors. So our guess is both nodes are trying to write the cache entry to DB. What may be causing this problem? AFAIK the jgroups backend should be preventing it.
We use hibernate 4.3.9.Final, hibernate-search 5.2.1.Final, infinispan 7.2.5.Final and jgroups 3.6.8.Final. Infinispan configuration is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns="urn:infinispan:config:7.2"
xmlns:jdbc="urn:infinispan:config:store:jdbc:7.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
urn:infinispan:config:7.2 http://www.infinispan.org/schemas/infinispan-config-7.2.xsd
urn:infinispan:config:store:jdbc:7.2 http://www.infinispan.org/schemas/infinispan-cachestore-jdbc-config-7.2.xsd">
<jgroups>
<stack-file name="tcp" path="default-configs/default-jgroups-tcp.xml"/>
<stack-file name="ec2" path="search/infinispan-jgroups-ec2.xml"/>
</jgroups>
<cache-container name="HibernateSearch" default-cache="default" statistics="false" shutdown-hook="DONT_REGISTER">
<transport stack="${infinispan.transport:tcp}"/>
<!-- Duplicate domains are allowed so that multiple deployments with default configuration
of Hibernate Search applications work - if possible it would be better to use JNDI to share
the CacheManager across applications -->
<jmx duplicate-domains="true"/>
<!-- *************************************** -->
<!-- Cache to store Lucene's file metadata -->
<!-- *************************************** -->
<replicated-cache name="LuceneIndexesMetadata" mode="SYNC" remote-timeout="25000">
<transaction mode="NONE"/>
<state-transfer enabled="true" timeout="480000" await-initial-transfer="true"/>
<indexing index="NONE"/>
<locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false"/>
<eviction max-entries="-1" strategy="NONE"/>
<expiration max-idle="-1"/>
<persistence passivation="false">
<jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
<jdbc:data-source jndi-url="java:comp/env/jdbc/..."/>
<jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
<jdbc:id-column name="ID" type="VARCHAR(255)"/>
<jdbc:data-column name="METADATA" type="BLOB"/>
<jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
</jdbc:string-keyed-table>
<property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
<write-behind/>
</jdbc:string-keyed-jdbc-store>
</persistence>
</replicated-cache>
<!-- **************************** -->
<!-- Cache to store Lucene data -->
<!-- **************************** -->
<distributed-cache name="LuceneIndexesData" mode="SYNC" remote-timeout="25000">
<transaction mode="NONE"/>
<state-transfer enabled="true" timeout="480000" await-initial-transfer="true"/>
<indexing index="NONE"/>
<locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false"/>
<eviction max-entries="-1" strategy="NONE"/>
<expiration max-idle="-1"/>
<persistence passivation="false">
<jdbc:string-keyed-jdbc-store preload="true" fetch-state="true" read-only="false" purge="false">
<jdbc:data-source jndi-url="java:comp/env/jdbc/..."/>
<jdbc:string-keyed-table drop-on-exit="false" create-on-start="true" prefix="ISPN_STRING_TABLE">
<jdbc:id-column name="ID" type="VARCHAR(255)"/>
<jdbc:data-column name="DATA" type="MEDIUMBLOB"/>
<jdbc:timestamp-column name="TIMESTAMP" type="BIGINT"/>
</jdbc:string-keyed-table>
<property name="key2StringMapper">org.infinispan.lucene.LuceneKey2StringMapper</property>
<write-behind/>
</jdbc:string-keyed-jdbc-store>
</persistence>
</distributed-cache>
<!-- ***************************** -->
<!-- Cache to store Lucene locks -->
<!-- ***************************** -->
<replicated-cache name="LuceneIndexesLocking" mode="SYNC" remote-timeout="25000">
<transaction mode="NONE"/>
<state-transfer enabled="true" timeout="480000" await-initial-transfer="true"/>
<indexing index="NONE"/>
<locking striping="false" acquire-timeout="10000" concurrency-level="500" write-skew="false"/>
<eviction max-entries="-1" strategy="NONE"/>
<expiration max-idle="-1"/>
</replicated-cache>
</cache-container>
</infinispan>
Respective Hibernate configuration is as follows (which is done via Spring):
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="..."/>
<property name="packagesToScan" value="com...."/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false"/>
<property name="showSql" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="database" value="MYSQL"/>
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.default_batch_fetch_size" value="50"/>
<entry key="hibernate.multiTenancy" value="SCHEMA"/>
<entry key="hibernate.multi_tenant_connection_provider" value-ref="connectionProvider"/>
<entry key="hibernate.tenant_identifier_resolver" value-ref="tenantIdentifierResolver"/>
<entry key="hibernate.cache.use_second_level_cache" value="true"/>
<entry key="hibernate.cache.region.factory_class" value="com.hazelcast.hibernate.HazelcastCacheRegionFactory"/>
<entry key="hibernate.cache.hazelcast.use_native_client" value="true"/>
<entry key="hibernate.cache.hazelcast.native_client_address" value="127.0.0.1"/>
<entry key="hibernate.cache.hazelcast.native_client_group" value="dev"/>
<entry key="hibernate.cache.hazelcast.native_client_password" value="dev-pass"/>
<entry key="hibernate.connection.characterEncoding" value="UTF-8"/>
<entry key="hibernate.connection.useUnicode" value="true"/>
<entry key="hibernate.search.default.directory_provider" value="infinispan"/>
<entry key="hibernate.search.default.locking_cachename" value="LuceneIndexesLocking"/>
<entry key="hibernate.search.default.data_cachename" value="LuceneIndexesData"/>
<entry key="hibernate.search.default.metadata_cachename" value="LuceneIndexesMetadata"/>
<entry key="hibernate.search.default.chunk_size" value="1048576"/>
<entry key="hibernate.search.infinispan.configuration_resourcename" value="search/hibernatesearch-infinispan.xml"/>
<entry key="hibernate.search.default.worker.backend" value="jgroups"/>
<entry key="hibernate.search.services.jgroups.configurationFile" value="search/infinispan-jgroups-ec2.xml"/>
</map>
</property>
</bean>
You are correct on the purpose of the JGroups Backend and your configuration of Hibernate looks like correct.
The problem is on the configuration of the CacheStore component in Infinispan, these have a "shared" attribute, whose default is false.
<jdbc:string-keyed-jdbc-store
preload="true"
fetch-state="true"
read-only="false"
purge="false"
shared="true" <!-- FIX
As you suspected, each Infinispan node was going to re-write the same entry on "each" CacheStore instance, as it didn't guess that each of your nodes are actually connecting to the same database.
Setting the shared attribute to true should ensure that Infinispan's core will coordinate among nodes so that one (and only one) node will write the entry.

Spring 4 Controller not converting JSON to Java class

I'm tryng to convert JSON into a java class using Spring.
When I execute the code I get 400 bad request.
If I replace User java object (#RequestBody final **User** user) with generic java Oject (#RequestBody final **Object** user), I get the json string as parameter.
Here's my code.
Javascript:
register : function(usr,pwd) {
var user = {username : usr, password: pwd}
return $http({
method: 'POST',
url: '/SpringSecurityRememberMeAnnotationExample/newuser',
contentType: "application/json",
data:user
});
/*
return $http.post('/SpringSecurityRememberMeAnnotationExample/newuser', user).then(function(response) {
return response.data;
});
*/
},
Controller:
#Controller
#Scope("request")
public class HomeController {
#RequestMapping(value = "/newuser", method = RequestMethod.POST)
#ResponseBody public User SaveUser(#RequestBody final User user){
System.out.println("username: ");// + user.username);
System.out.println("password: ");// + user.password);
return null;
}
spring-mvc.xml
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!-- Login Interceptor -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.websystique.springsecurity.interceptor.LoginInterceptor"/>
</mvc:interceptor>
<!-- workaround to fix IE8 problem -->
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>
<!-- i18n -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="useCodeAsDefaultMessage" value="true"/>
<property name="basename" value="WEB-INF/i18n"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="fileEncodings" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="it"/>
<property name="useCodeAsDefaultMessage" value="true"/>
</bean>
<!-- Exception handler -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="LoginRequiredException">
public/loginRequired
</prop>
<prop key="ResourceNotFoundException">
public/notFound
</prop>
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
<!-- View Handler -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="order" value="0" />
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
Thank you!
Adding POM.XML config, json part
<!-- JSon -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Recheck the setters/getters for the fields and make sure there is a no-argument constructor. (If you have no constructor, Java will generate a default no-arg one, but if you have added a constructor with arguments yourself, you must take care to implement a no-arg one as well).
Main Problem was on the User class embedded on the controller code. Once I created User.java file on it's own package all goes smoothly.
You are passing malformed json object i guess. you should pass user json data like below.
var user = {"username" : "<username>", "password": "<password>"};
And makes sure User.java has setters/getters for the fields and default constructor.
Please make sure following two jars are present in your application
1. Jackson - core
2. Jackson - mapper
Both Java API are used by spring for XML/JSON processing.
put var user = {"username" : usr, "password": pwd}; in java script,
and do confirm that your User class is right having proper setter getter and proper access to your calling class.

error in hibernate query

my hibernate.cfg.xml is this :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/****</property>
<property name="hibernate.connection.username">***</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactor y</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">create</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<mapping class="entities.MisurazioneOraria"/>
<mapping class=....
....>
<listener type="post-insert" class="MisurazioneOrariaInsertListener"/>
</session-factory>
</hibernate-configuration>
i try to do query from this line code that is the listener :
ArrayList<MisurazioneOraria> mis = (ArrayList<MisurazioneOraria>) session.createQuery("from (misurazione_oraria) where sensore_idsensore = :idsensore").setParameter("idsensore", m.getSensore().getIdSensore()).list();
and the error is that :
mag 27, 2012 6:30:33 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
Grave: Could not synchronize database state with session
org.hibernate.QueryException: in expected: misurazione_oraria [from (misurazione_oraria) where sensore_idsensore = :idsensore]
my mysql version is 5.5.23. thanks for the help.
Your entity class is named MisurazioneOraria, not misurazione_oraria. HQL uses entities and fields/properties. It doesn't use table and column names.
Read the HQL documentation.
Moreover, Query.list() returns a List, and not necessarily an ArrayList. You shouldn't cast the result of the query to ArrayList.
change it to
List<MisurazioneOraria> mis = session.createQuery("from MisurazioneOraria where idSensore = :idsensore").setParameter("idsensore", m.getSensore().getIdSensore()).list();

how to configure spring mvc 3 to not return "null" object in json response?

a sample of json response looks like this:
{"publicId":"123","status":null,"partner":null,"description":null}
It would be nice to truncate out all null objects in the response. In this case, the response would become {"publicId":"123"}.
Any advice? Thanks!
P.S: I think I can do that in Jersey. Also I believe they both use Jackson as the JSON processer.
Added Later:
My configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.SomeCompany.web" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!-- Configures Spring MVC -->
<import resource="mvc-config.xml" />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<!--<mvc:view-controller path="/" view-name="welcome"/>-->
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="text/xml"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView" >
<property name="marshaller">
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
</bean>
-->
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
My code:
#Controller
public class SomeController {
#RequestMapping(value = "/xyz", method = {RequestMethod.GET, RequestMethod.HEAD},
headers = {"x-requested-with=XMLHttpRequest","Accept=application/json"}, params = "!closed")
public #ResponseBody
List<AbcTO> getStuff(
.......
}
}
Yes, you can do this for individual classes by annotating them with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.
Here is some info from the Jackson FAQ: http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls.
Annotating the classes is straightforward, but configuring the ObjectMapper serialization config slightly trickier. There is some specific info on doing the latter here.
Doesn't answer the question but this is the second google result.
If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation
#JsonInclude(Include.NON_NULL)
on the returning class.
As mentioned in the comments, and in case anyone is confused, the annotation should be used in the class that will be converted to JSON.
If using Spring Boot for REST, you can do it in application.properties:
spring.jackson.serialization-inclusion=NON_NULL
source
Java configuration for the above. Just place the below in your #Configuration class.
#Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
return builder;
}