How get VelocityEngine with Velocity Tools in Spring 3 - java

How get VelocityEngine with Velocity Tools in Spring 3?
I need a method in the controller to process a template Velocity, but need to have Velocity Tools that are available to initialize the Spring 3.
Now I'm doing it like this.
Spring Config:
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="false"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity/config/toolbox.xml"/>
<property name="viewClass" value="my.tools.VelocityToolsView"/>
</bean>
In controller class:
#Autowired
private VelocityConfigurer configurer;
private VelocityEngine velocityEngine;
private ToolContext toolContext;
#PostConstruct
public void init() {
velocityEngine = configurer.getVelocityEngine();
ToolManager toolManager = new ToolManager();
toolManager.configure("fuulPath/WEB-INF/velocity/config/toolbox.xml");
toolContext = toolManager.createContext();
}
In method:
VelocityContext velocityContext = new VelocityContext(map, toolContext);
StringWriter writer = new StringWriter();
velocityEngine.mergeTemplate("myTeplate.html", "UTF-8", velocityContext, writer);
String templateString = writer.toString();

The above method to get velocity is good when you don't use Spring configuration.When you use Spring you don't need this much complexity.
Define this bean in your spring.xml
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
and In your java class Autowire this bean
#Component
public class Sample {
private VelocityEngine velocityEngine;
public VelocityEngine getVelocityEngine() {
return velocityEngine;
}
#Autowired
#Required
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public String getSomething(Object variable) {
Map model = new HashMap();
model.put("variable",variable);
return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/templates/sometemp.vm", model);
}
}

There is a simpler way to do it in Spring 3
add toolbox.xml to WEB-INF/velocity
<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
<xhtml>true</xhtml>
<tool>
<key>date</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.DateTool</class>
<parameter name="format" value="dd/MM/yyyy" />
</tool>
<tool>
<key>display</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.DisplayTool</class>
</tool>
<tool>
<key>math</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.MathTool</class>
</tool>
<tool>
<key>iter</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.IteratorTool</class>
</tool>
<tool>
<key>sort</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.SortTool</class>
</tool>
<tool>
<key>esc</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.EscapeTool</class>
</tool>
</toolbox>
Then add this path to your APPNAME-servlet.xml file
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver" p:cache="false" p:order="1">
<property name="prefix" value="/com/aol/dragon/template/"/>
<property name="suffix" value=".vm"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity/toolbox.xml" />
</bean>
Then update you pom.xml dependency
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
save, update project, and run the server. You should be now able to use all tools stuff in vm's.

Related

Ignite c++ client for cassandra integration

I am developing an application for data communication in that i want to communicate to cassandra through ignite c++. when i try to put data to cassandra its works fine. but i can't get the data from the same.
here is my code.
test.h
namespace ignite
{
namespace examples
{
struct Test
{
Test()
{
// No-op.
}
Test(const std::string& assetid, const std::string& asset_desc, const std::string& groupid) :
assetid (assetid), asset_desc (asset_desc), groupid (groupid)
{
// No-op.
}
std::string ToString()
{
std::ostringstream oss;
oss << "Address [street=" << assetid << ", zip=" << asset_desc<< "]";
return oss.str();
}
std::string assetid;
std::string asset_desc;
std::string groupid;
};
}
}
cassandra-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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Cassandra connection settings -->
<import resource="file:connection-settings.xml" />
<!-- Persistence settings for 'cache1' -->
<bean id="cache1_persistence_settings" class="org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings">
<constructor-arg type="org.springframework.core.io.Resource" value="file:persistence-settings-1.xml" />
</bean>
<!-- Persistence settings for 'cache2'
<bean id="cache2_persistence_settings" class="org.apache.ignite.cache.store.cassandra.persistence.KeyValuePersistenceSettings">
<constructor-arg type="org.springframework.core.io.Resource" value="classpath:org/apache/ignite/tests/persistence/blob/persistence-settings-3.xml" />
</bean>-->
<!-- Ignite configuration -->
<bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
<property name="cacheConfiguration">
<list>
<!-- Configuring persistence for "cache1" cache -->
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<property name="name" value="cache1"/>
<property name="queryEntities">
<list>
<bean class="org.apache.ignite.cache.QueryEntity">
<property name="keyType" value="Test"/>
<property name="valueType" value="Test"/>
<property name="fields">
<map>
<!--entry key="assetid" value="assetid"/-->
<entry key="asset_desc" value="asset_desc"/>
<entry key="groupid" value="groupid"/>
</map>
</property>
</bean>
</list>
</property>
<property name="readThrough" value="true"/>
<property name="writeThrough" value="true"/>
<property name="storeKeepBinary" value="true"/>
<property name="cacheStoreFactory">
<bean class="org.apache.ignite.cache.store.cassandra.CassandraCacheStoreFactory">
<property name="dataSourceBean" value="cassandraAdminDataSource"/>
<property name="persistenceSettingsBean" value="cache1_persistence_settings"/>
</bean>
</property>
</bean>
<!-- Configuring persistence for "cache2" cache
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<property name="name" value="cache2"/>
<property name="readThrough" value="true"/>
<property name="writeThrough" value="true"/>
<property name="cacheStoreFactory">
<bean class="org.apache.ignite.cache.store.cassandra.CassandraCacheStoreFactory">
<property name="dataSourceBean" value="cassandraAdminDataSource"/>
<property name="persistenceSettingsBean" value="cache2_persistence_settings"/>
</bean>
</property>
</bean>
-->
</list>
</property>
<!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. -->
<property name="discoverySpi">
<bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
<property name="ipFinder">
<!--
Ignite provides several options for automatic discovery that can be used
instead os static IP based discovery. For information on all options refer
to our documentation: http://apacheignite.readme.io/docs/cluster-config
-->
<!-- Uncomment static IP finder to enable static-based discovery of initial nodes. -->
<!--<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">-->
<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
<property name="addresses">
<list>
<!-- In distributed environment, replace with actual host IP address. -->
<value>127.0.0.1:47500..47509</value>
</list>
</property>
</bean>
</property>
</bean>
</property>
</bean>
</beans>
connection-settings.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="loadBalancingPolicy" class="com.datastax.driver.core.policies.TokenAwarePolicy">
<constructor-arg type="com.datastax.driver.core.policies.LoadBalancingPolicy">
<bean class="com.datastax.driver.core.policies.RoundRobinPolicy"/>
</constructor-arg>
</bean>
<util:list id="contactPoints" value-type="java.lang.String">
<value>127.0.0.1</value>
</util:list>
<bean id="cassandraAdminDataSource" class="org.apache.ignite.cache.store.cassandra.datasource.DataSource">
<property name="contactPoints" ref="contactPoints"/>
<!-- <property name="user" value="user"/>
<property name="password" value="p#ssw0rd"/> -->
<property name="readConsistency" value="ONE"/>
<property name="writeConsistency" value="ONE"/>
<property name="loadBalancingPolicy" ref="loadBalancingPolicy"/>
</bean>
</beans>
persistance-settings.xml
<persistence keyspace="sam" table="user_permission">
<keyPersistence class="com.test.Test" strategy="POJO">
<partitionKey>
<!-- Mapping from POJO field to Cassandra table column -->
<field name="assetid" column="assetid" />
</partitionKey>
</keyPersistence>
<valuePersistence class="com.test.Test" strategy="POJO">
<!-- Mapping from POJO field to Cassandra table column -->
<!-- field name="companyid" column="companyid" />
<field name="company_name" column="company_name" /-->>
<field name="assetid" column="assetid"/>
<field name="asset_desc" column="asset_desc"/>
<field name="groupid" column="groupid"/>
</valuePersistence>
</persistence>
main
int main()
{
IgniteConfiguration cfg;
cfg.springCfgPath = "apache-ignite-fabric-2.0.0-bin/cassandra-config.xml";
Ignite grid = Ignition::Start(cfg);
Cache<Test, Test> cache = grid.GetCache<Test, Test>("cache1");
Test test;
test.assetid = "456dsfds";
Test obj;
obj.asset_desc = "wdsdfsf";
obj.groupid = "sddvwfsf";
cache.Put (test, obj,err);
Test get = cache.Get (test, err);
cout << "Error Found" << err.GetText () << endl;
cout << "Ignite \t" << "\t" << get.asset_desc << "\t" << get.groupid;
}
Test.jar
package com.test;
import java.io.Serializable;
import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.binary.BinaryReader;
import org.apache.ignite.binary.BinaryWriter;
import org.apache.ignite.binary.Binarylizable;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
public class Test implements Binarylizable ,Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String assetid;
#QuerySqlField(index = true)
String asset_desc;
String groupid;
public String getGroupId() {
return groupid;
}
public void setGroupId(String groupId) {
this.groupid = groupId;
}
public String getAssetid() {
return assetid;
}
public void setAssetid(String assetid) {
this.assetid = assetid;
}
public String getAsset_desc() {
return asset_desc;
}
public void setAsset_desc(String asset_desc) {
this.asset_desc = asset_desc;
}
#Override
public void readBinary(BinaryReader reader) throws BinaryObjectException {
assetid = reader.readString("assetid");
asset_desc = reader.readString("asset_desc");
groupid = reader.readString("groupid");
}
#Override
public void writeBinary(BinaryWriter writer) throws BinaryObjectException {
writer.writeString("assetid", assetid);
writer.writeString("asset_desc", asset_desc);
writer.writeString("groupid", groupid);
}
}
it shows the error like this
Topology snapshot [ver=1, servers=1, clients=0, CPUs=1, heap=0.97GB]
[16:14:20,834][ERROR][sys-#29%null%][CassandraCacheStore] Failed to execute Cassandra CQL statement: select "assetid", "asset_desc", "groupid" from "sam"."user_permission" where "assetid"=? and "asset_desc"=? and "groupid"=?;
class org.apache.ignite.IgniteException: Failed to execute Cassandra CQL statement: select "assetid", "asset_desc", "groupid" from "sam"."user_permission" where "assetid"=? and "asset_desc"=? and "groupid"=?;
I assume that's because you are using this:
<property name="storeKeepBinary" value="true"/>
Current implementation supports only BLOB serialization for binary objects. There is a ticket for this: https://issues.apache.org/jira/browse/IGNITE-5270
As far as you are using C++ to work with Ignite, you are also utilizing BinaryObjects. Current implementation of Cassandra store doesn't support BinaryObjects as cache keys and values.
Because of this, from Ignite C++ client you can't use Cassandra table with 1 partiton key ,3 clustering keys. You can only do it from java client configuring POJO persistence strategy and avoiding BinaryObjects.
There is also a ticket in Ignite JIRA to implement BinaryObjects support in Cassandra store: https://issues.apache.org/jira/browse/IGNITE-5270

Bean Velocity Config from xml to java

I'd like convert xml bean with velocity to config java class
This is old xml config:
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/view/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
</bean>
And this is new java class config:
#Bean
public ViewResolver viewResolver()
{
VelocityViewResolver viewResolver= new VelocityViewResolver();
viewResolver.setPrefix("");
viewResolver.setSuffix(".html");
viewResolver.setCache(true);
return viewResolver;
}
#Bean
public VelocityConfigurer velocityConfig()
{
VelocityConfigurer velocityConfig = new VelocityConfigurer();
// ???????????
return velocityConfig;
}
How to do it?
VelocityConfig extends VelocityEngineFactory, so you can use the method setResourceLoaderPath:
velocityConfig.setResourceLoaderPath("/WEB-INF/View/");

Spring resource found but no beans are loaded

I am importing a spring xml configuration file from another project using import resource. The resource is apparently found since there is no error message saying it isn't, but none of the beans get loaded. Is there something I'm doing wrong here? I should note that when I run my integration tests from within eclipse it all works fine, but it blows up when running the same integration test from within a maven build.
applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<import resource="classpath*:httpclient-4x.xml" />
<context:component-scan base-package="com.mycompany.data" />
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:properties/client.${deployment.env}.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="false" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
</beans>
httpclient-4x.xml
<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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="secureRestTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<ref bean="secureClientHttpRequestFactory" />
</constructor-arg>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_XML" />
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_JSON" />
<util:constant static-field="org.springframework.http.MediaType.TEXT_PLAIN" />
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.FormHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<util:constant static-field="org.springframework.http.MediaType.MULTIPART_FORM_DATA" />
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="secureClientHttpRequestFactory" class="com.cobalt.inventory.security.PreemptiveBasicAuthClientHttpRequestFactory">
<constructor-arg>
<ref bean="secureCloseableHttpClient" />
</constructor-arg>
</bean>
<bean id="secureCloseableHttpClient" factory-bean="secureHttpClientBuilder" factory-method="build" />
<bean id="secureHttpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="defaultCredentialsProvider" ref="credentialsProvider" />
<property name="defaultSocketConfig" ref="socketConfig" />
<property name="defaultRequestConfig" ref="requestConfig" />
<property name="userAgent" value="${http.user.agent: CDK Cobalt invJava}" />
<property name="maxConnPerRoute" value="${http.max.connections.per.route:100}" />
<property name="maxConnTotal" value="${http.max.connections:100}" />
</bean>
<bean id="credentialsProvider" class="org.apache.http.impl.client.BasicCredentialsProvider" />
<bean id="credentials" class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg index="0" name="userName" value="validUsername" />
<constructor-arg index="1" name="password" value="validPassword" />
</bean>
<bean id="socketConfigBuilder" class="org.apache.http.config.SocketConfig.Builder">
<property name="soKeepAlive" value="true" />
<property name="soTimeout" value="${http.socket.timeout:10000}" />
</bean>
<bean id="socketConfig" factory-bean="socketConfigBuilder" factory-method="build" />
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<property name="connectTimeout" value="${http.connection.timeout:10000}" />
<property name="socketTimeout" value="${http.socket.timeout:10000}" />
<property name="cookieSpec">
<util:constant static-field="org.apache.http.client.config.CookieSpecs.IGNORE_COOKIES" />
</property>
</bean>
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
<!-- For accessing common authorization service -->
<bean id="commonAuthzSecureRestTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<ref bean="commonAuthzSecureClientHttpRequestFactory" />
</constructor-arg>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_XML" />
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_JSON" />
<util:constant static-field="org.springframework.http.MediaType.TEXT_PLAIN" />
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.FormHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<util:constant static-field="org.springframework.http.MediaType.MULTIPART_FORM_DATA" />
</list>
</property>
</bean>
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter ">
<property name="supportedMediaTypes">
<list>
<bean id="jsonMediaTypeApplicationJson" class="org.springframework.http.MediaType">
<constructor-arg value="application" />
<constructor-arg value="json" />
</bean>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="commonAuthzSecureClientHttpRequestFactory" class="com.mycompany.security.PreemptiveBasicAuthClientHttpRequestFactory">
<constructor-arg>
<ref bean="commonAuthzSecureCloseableHttpClient" />
</constructor-arg>
</bean>
<bean id="commonAuthzSecureCloseableHttpClient" factory-bean="commonAuthzSecureHttpClientBuilder" factory-method="build" />
<bean id="commonAuthzSecureHttpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="defaultCredentialsProvider" ref="commonAuthzCredentialsProvider" />
<property name="defaultSocketConfig" ref="commonAuthzSocketConfig" />
<property name="defaultRequestConfig" ref="commonAuthzRequestConfig" />
<property name="userAgent" value="${http.user.agent: userAgent}" />
<property name="maxConnPerRoute" value="${http.max.connections.per.route:100}" />
<property name="maxConnTotal" value="${http.max.connections:100}" />
</bean>
<bean id="commonAuthzCredentialsProvider" class="org.apache.http.impl.client.BasicCredentialsProvider" />
<bean id="commonAuthzCredentials" class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg index="0" name="userName" value="${common_services.iam.remoting.user:user" />
<constructor-arg index="1" name="password" value="${common_services.iam.remoting.password:password}" />
</bean>
<bean id="commonAuthzSocketConfigBuilder" class="org.apache.http.config.SocketConfig.Builder">
<property name="soKeepAlive" value="true" />
<property name="soTimeout" value="${http.socket.timeout:10000}" />
</bean>
<bean id="commonAuthzSocketConfig" factory-bean="commonAuthzSocketConfigBuilder" factory-method="build" />
<bean id="commonAuthzRequestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<property name="connectTimeout" value="${http.connection.timeout:10000}" />
<property name="socketTimeout" value="${http.socket.timeout:10000}" />
<property name="cookieSpec">
<util:constant static-field="org.apache.http.client.config.CookieSpecs.IGNORE_COOKIES" />
</property>
</bean>
<bean id="commonAuthzRequestConfig" factory-bean="commonAuthzRequestConfigBuilder" factory-method="build" />
<util:list id="spel-configuration">
<value>#{credentialsProvider.setCredentials(T(org.apache.http.auth.AuthScope).ANY, credentials)}</value>
<value>#{commonAuthzCredentialsProvider.setCredentials(T(org.apache.http.auth.AuthScope).ANY, commonAuthzCredentials)} </value>
</util:list>
</beans>
I turned debug logging on for Spring and found the following log entries:
[2015-04-13 10:46:56,818][DEBUG][org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loaded 0 bean definitions from location pattern [classpath*:httpclient-4x.xml]
[2015-04-13 10:46:56,818][DEBUG][org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader] - Imported 0 bean definitions from URL location [classpath*:httpclient-4x.xml]
I do not have control of the content of httpclient-4x.xml I just reference it.
By request, here is CvsDataClientImpl:
package com.mycompany.data;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.mycompany.utility.ConditionalUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
#Component
public class CvsDataClientImpl implements CvsDataClient<JsonNode> {
private static final int MAX_PAGE_SIZE = 100;
private static final String V1 = "/rest/v1.0/vehicles";
#Resource(name = "secureRestTemplate")
private RestTemplate restTemplate;
#Resource(name = "jsonVehiclesNodeMerger")
private JsonVehiclesNodeMerger nodeMerger;
#Value("${inv.vehicle-app.context:inventoryWebApp}")
private String vehicleAppContextPath;
#Value("${services.remoting.url:http://localhost:10080}")
private String remotingUrl;
#Override
public JsonNode read(String urlParameters) {
validateUrlParameters(urlParameters);
ResponseEntity<JsonNode> response = restTemplate.getForEntity(buildBaseRestUrl() + "?" + urlParameters, JsonNode.class);
return response.getBody();
}
#Override
public JsonNode readAll(String urlParameters) {
return readAll(urlParameters, null);
}
public JsonNode readAll(String urlParameters, Integer pageSize) {
int offset = 0;
int actualPageSize = pageSize != null ? pageSize : MAX_PAGE_SIZE;
JsonNode latestResult = null;
JsonNode baseResult = null;
do {
String extendedUrlParameters = buildUrlParameters(urlParameters, offset, actualPageSize);
latestResult = read(extendedUrlParameters);
baseResult = merge(latestResult, baseResult);
offset += actualPageSize;
} while (latestResult.get("searchResult").get("vehicles") != null);
return baseResult;
}
private JsonNode merge(JsonNode latestResult, JsonNode baseResult) {
JsonNode merged = null;
if (baseResult == null) {
merged = latestResult;
} else {
merged = nodeMerger.merge(latestResult, baseResult);
}
JsonNode searchResult = merged.get("searchResult");
((ObjectNode) searchResult).remove("summary");
return merged;
}
private String buildUrlParameters(String urlParameters, int offset, int pageSize) {
String parameters = urlParameters;
parameters += "&limit=" + pageSize + "&offset=" + offset;
return parameters;
}
private String buildBaseRestUrl() {
return remotingUrl + vehicleAppContextPath + V1;
}
private void validateUrlParameters(String urlParameters) {
if (ConditionalUtils.isNullOrEmpty(urlParameters) || urlParameters.indexOf("inventoryOwner") < 0 && urlParameters.indexOf("storeId") < 0) {
throw new IllegalArgumentException("Must provide at least an inventory owner or store ID");
}
}
void setVehicleAppContextPath(String contextPath) {
vehicleAppContextPath = contextPath;
}
void setRemotingUrl(String remotingUrl) {
this.remotingUrl = remotingUrl;
}
}
After some discussion on chat, minion and I found that httpclient-4x.xml is not included in the external project's build jar for some reason. Now I need to investigate that, but it's another story. :-)

Spring XML View Resolver not working

Using Spring MVC i want to create a PDF from the model.
I have created a controller as below
#Controller
#RequestMapping("en/pdfdoc.gov")
#Transactional(propagation=Propagation.SUPPORTS)
public class PDFDocumentController extends SecurityController {
#RequestMapping(method = RequestMethod.GET,params="action=allAssociations",headers="Accept=*/*")
public ModelAndView getAllassociations(HttpServletRequest request, HttpServletResponse response){
Map<String, Object> revenueData= new HashMap<String, Object>();
revenueData.put("1/20/2010", "$100,000");
revenueData.put("1/21/2010", "$200,000");
revenueData.put("1/22/2010", "$300,000");
revenueData.put("1/23/2010", "$400,000");
revenueData.put("1/24/2010", "$500,000");
return new ModelAndView("PdfRevenueSummary","revenueData",revenueData);
}
}
and the view
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
public class PdfRevenueReportView extends AbstractPdfView{
#Override
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
Table table= new Table(2);
#SuppressWarnings("unchecked")
Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
table.addCell("Month");
table.addCell("Revenue");
for (Map.Entry<String, String> entry : revenueData.entrySet()) {
table.addCell(entry.getKey());
table.addCell(entry.getValue());
}
document.add(table);
}
}
the dispatcher-servlet.xml
<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"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<bean id="pdfview" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="0"/>
<property name="location">
<value>/WEB-INF/spring-pdf-views.xml</value>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
spring-pdf-views.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="PdfRevenueSummary"
class="in.subrat.nayak.view.PdfRevenueReportView">
</bean>
</beans>
since the tiles.xml is working fine so i have not posted the code part.
the Issue in the above code is that when i return the view from controller by
return new ModelAndView("PdfRevenueSummary","revenueData",revenueData);
it is not getting redirected to the class PdfRevenueReportView as given in the spring-pdf-views.xml
so plz help me to get out of this problem
Hopes the above question is clear....
after 2 days, i found what i needed
the issue was simple just made the class PDFDocumentController to extend the Class AbstractController
just made
public class PDFDocumentController extends AbstractController
instead of
public class PDFDocumentController extends SecurityController

hibernate always deletes all data from a table on its own

Hi i am developing a spring mvc app thats using hibernate to connect to a mysql database that stores files.
I have two methods. one that adds all files from a specific file path of my choosing and another method that invokes a query to return me a list of the files stored from mysql.
The issue is this. When i execute the first method on its own ie populating the database, it works fine i can see the contents of that table from mysql command line. however, when i then execute the query method right after populating it, the contents of that said table is completely gone instantly. Its as if hibernate only stored the data in the mysql temporarily or somewhere in mysql, it deleted data imediatly and doesnt keep it their.
this is the method that populated the table:
/**
* Test Method: ideal for another class to do this kind of work and this
* pass the FileObject into this class
*/
public void addSomeFiles() {
System.out.println("addSomeFiles");
File dir = new File(picturesPath);
String[] fileNames = dir.list();
for (int i = 0; i < fileNames.length; i++) {
System.out.println(fileNames[i]);
File file = new File(picturesPath + "\\" + fileNames[i]);
if (file.isFile()) {
FileObject fileO = contstructFileObject(file);
if (fileO == null) {
System.out.println("fileO is null!!!!!");
} else {
// addFile(fileO);
dbFileHelper.addFile(fileO);
}
}
}
System.out.println("//////////////");
// File file;
}
.........Hibernate template class........
public class DbFileHelper implements DbFileWrapper {
private HibernateTemplate hbTemplate;
//private static final String SQL_GET_FILE_LIST = "select filename, size, id, type from fileobject";
private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";
public DbFileHelper() {
}
public void setHbTemplate(HibernateTemplate hbTemplate) {
System.out.println("setHbTemplate");
System.out.println("///////////////////");
System.out.println("///////////////////");
System.out.println("///////////////////");
this.hbTemplate = hbTemplate;
}
// ////////////////////////////////////////////////
#Override
public String addFile(FileObject file) {
// TODO Auto-generated method stub
System.out.println("addFile using hibernate");
if (hbTemplate == null) {
System.out.println("hbTemplate is null!! why?");
}
hbTemplate.saveOrUpdate(file);
hbTemplate.flush();
return "added succesfuly";
}
And here is the other method that makes the query:
........................
public JSONArray getFileList(String type){
return constructJsonArray(dbFileHelper.getFileList(ALL));
}
private JSONArray constructJsonArray(List<FileObject> fileList ){
JSONArray mJsonArray = new JSONArray();
for (int i = 0; i < fileList.size(); i++) {
System.out.println("fileName = " + fileList.get(i).getFilename() );
//mJson.put("Filename", fileList.get(i).getFileName() );
mJsonArray.add( new JSONObject().put("File ID", fileList.get(i).getId() ));
mJsonArray.add( new JSONObject().put("Filename", fileList.get(i).getFilename() ));
mJsonArray.add( new JSONObject().put("File type", fileList.get(i).getType()));
mJsonArray.add( new JSONObject().put("File Size", fileList.get(i).getSize()));
}
return mJsonArray;
}
..........hibernate Template class.......
private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";
#Override
public List<FileObject> getFileList(String type) {
// TODO Auto-generated method stub
List<FileObject> files = hbTemplate.find(SQL_GET_FILE_LIST);
//hbTemplate.flush();
return files;
}
..........
Finally here is a print screen of what i originaly put inside my table but dissapears on its own:
http://img411.imageshack.us/img411/9553/filelisti.jpg
Am i missing something here?
edit: additional info.
my hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.kc.models.FileObject" >
<class name="com.kc.models.FileObject" table="fileobject">
<id name="id" column="ID">
<generator class="native" />
</id>
<property name="filename" type="string" column="FILENAME" />
<property name="type" type="string" column="TYPE" />
<property name="size" type="double" column="SIZE" />
<property name="file" type="blob" length="1000000000" column="FILE" />
</class>
</hibernate-mapping>
my controller:
#Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList() );
}
private void testAddingSomeFilesToDb() {
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
file.addSomeFiles();
}
/**
* Get file list from sql server based on type
* #return file list in json
*/
private JSONArray getFileList() {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList("all");
}
Another edit:
my .xml file configuring the session factory and hibernate template
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!-- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd -->
<!-- Config properties files -->
<!-- Hibernate database stuff -->
<!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <list> <value>/properties/jdbc.properties</value>
</list> </property> </bean> -->
<!-- <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" /> <property
name="url" value="${database.url}" /> <property name="username" value="${database.user}"
/> <property name="password" value="${database.password}" /> </bean> -->
<bean id="dataSource1"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/zangshop" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<!-- LocalSessionFactoryBean u need to put the hbm files in the WEB-INF/classes
root director -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource1"></property>
<property name="mappingResources">
<list>
<value>FileObject.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="hbTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dbFileHelper" class="com.kc.models.DbFileHelper">
<property name="hbTemplate" ref="hbTemplate"></property>
</bean>
<bean id="fileHelper" class="com.kc.models.FileHelper">
<property name="dbFileHelper" ref="dbFileHelper"></property>
</bean>
</beans>
i have fixed the problem
i changed <prop key="hibernate.hbm2ddl.auto">create</prop>
to <prop key="hibernate.hbm2ddl.auto">update</prop> and it worked
Are you creating/destroying the SessionFactory between calls? Could you have the hbm2ddl.auto property set to create-drop?
Actually, can you show the Hibernate settings?
Reference
Hibernate Core Reference Guide
Table 3.7. Miscellaneous Properties
In my case also table was getting deleted automatically, following solution worked for me:
org.hibernate.dialect.MySQL8Dialect
Appending the version number with the MySQL Dialect.
Because commit was not getting executed earlier with org.hibernate.dialect.MySQLDialect.

Categories