Injecting SoyTemplateRenderer in custom Atlassian JIRA plugin - spring

I'm currently trying to develop a custom Jira plugin, which also uses a servlet to render a Soy template.
This is the code of my servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package at.fraiss.plugins.custommenuitem.servlets;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.atlassian.soy.renderer.SoyTemplateRenderer;
import java.util.HashMap;
import java.util.Map;
/**
*
* #author Mario
*/
public class SoyTemplateServlet extends HttpServlet {
private SoyTemplateRenderer soyTemplateRenderer;
public SoyTemplateServlet(SoyTemplateRenderer soyTemplateRenderer)
{
this.soyTemplateRenderer = soyTemplateRenderer;
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
response.getWriter().write(getHtml());
}
public String getHtml()
{
Map<String, Object> data = new HashMap<String,Object>();
data.put("isLocal", true);
data.put("url", "http://www.example.com");
data.put("title", "example");
return this.soyTemplateRenderer.render("jira.webresources:soy-templates", "JIRA.Templates.Links.helpLink", data);
}
}
This is how I defined the soy template files inside the atlassian-plugin.xml descriptor:
<web-resource key="soy-templates">
<dependency>com.atlassian.soy.soy-template-plugin:soy-deps</dependency>
<!-- Available to the server-side only -->
<resource type="soy" name="links" location="links.soy"/>
 
<!-- Make available to the client-side in JS as well... -->
<transformation extension="soy">
<transformer key="soyTransformer"/>
</transformation>
<resource type="download" name="Links.soy.js" location="links.soy"/>
</web-resource>
I have added the following section to my pom.xml:
<dependency>
<groupId>com.atlassian.soy</groupId>
<artifactId>soy-template-renderer-api</artifactId>
<version>4.0.4</version>
<scope>provided</scope>
</dependency>
and always get this error when try to acces the servlet
[INFO] [talledLocalContainer] Caused by: org.springframework.beans.factory.Unsat isfiedDependencyException: Error creating bean with name 'at.fraiss.plugins.cust ommenuitem.servlets.SoyTemplateServlet': Unsatisfied dependency expressed throug h constructor argument with index 0 of type [com.atlassian.soy.renderer.SoyTempl ateRenderer]: : No qualifying bean of type [com.atlassian.soy.renderer.SoyTempla teRenderer] found for dependency: expected at least 1 bean which qualifies as au towire candidate for this dependency. Dependency annotations: {}; nested excepti on is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualif ying bean of type [com.atlassian.soy.renderer.SoyTemplateRenderer] found for dep endency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Con structorResolver.createArgumentArray(ConstructorResolver.java:749) [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Con structorResolver.autowireConstructor(ConstructorResolver.java:185) [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Abs tractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanF actory.java:1139) [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Abs tractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFa ctory.java:1042) [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Abs tractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory. java:504) [INFO] [talledLocalContainer] at org.springframework.beans.factory.support.Abs tractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.ja va:342) [INFO] [talledLocalContainer] ... 2 filtered [INFO] [talledLocalContainer] at java.lang.reflect.Method.invoke(Method.java:4 97) [INFO] [talledLocalContainer] at com.atlassian.plugin.osgi.spring.DefaultSprin gContainerAccessor.createBean(DefaultSpringContainerAccessor.java:112) [INFO] [talledLocalContainer] at com.atlassian.plugin.module.ClassPrefixModule Factory.createModule(ClassPrefixModuleFactory.java:39) [INFO] [talledLocalContainer] at com.atlassian.plugin.module.PrefixDelegatingM oduleFactory.createModule(PrefixDelegatingModuleFactory.java:100) [INFO] [talledLocalContainer] at com.atlassian.plugin.servlet.descriptors.Serv letModuleDescriptor.getModule(ServletModuleDescriptor.java:48) [INFO] [talledLocalContainer] at com.atlassian.plugin.servlet.DelegatingPlugin Servlet.<init>(DelegatingPluginServlet.java:33) [INFO] [talledLocalContainer] at com.atlassian.plugin.servlet.DefaultServletMo duleManager$LazyLoadedServletReference.create(DefaultServletModuleManager.java:5 41) [INFO] [talledLocalContainer] at com.atlassian.plugin.servlet.DefaultServletMo duleManager$LazyLoadedServletReference.create(DefaultServletModuleManager.java:5 21) [INFO] [talledLocalContainer] at com.atlassian.util.concurrent.LazyReference$S ync.run(LazyReference.java:325) [INFO] [talledLocalContainer] at com.atlassian.util.concurrent.LazyReference.g ...

I also had this problem (and lost hours on it).
The Spring scanner apparently only processes classes marked with #Named.
This worked for me:
#Named("MyServlet")
public class MyServlet extends HttpServlet{
#ComponentImport
private final SoyTemplateRenderer soyTemplateRenderer;
#Inject
public MyServlet(#ComponentImport final SoyTemplateRenderer soyTemplateRenderer) {
this.soyTemplateRenderer = soyTemplateRenderer;
}
}

Apparently this has nothing to do with jiira, but in your frustration you seem to be blaming it and its documentation. It's actually a problem with your use of spring, and your apparent inability to read stack traces.
The first entry in the stack trace mentions, in may different ways, No qualif
ying bean of type [com.atlassian.soy.renderer.SoyTemplateRenderer] found. So, you seem to have not provided a bean definition for the SoyTemplateRenderer for spring to find. Rectify this and this particular problem will disappear.

Related

How to convert XML to String with JAXB and spring-boot?

When I run a mvn spring-boot:run on the folder that has the pom.xml file the application starts and serializes a POJO into a XML correctly, but when I do it by going to the target folder and starting it by using java -jar in the jar file I get javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath caused by .java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory.
In my maven I have the following JAXB dependencies:
<!-- JAXB API -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<!-- JAXB Runtime -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.5</version>
<scope>runtime</scope>
</dependency>
Here's the code that serializes a POJO into XML:
private static final Pattern REMOVE_HEADER = Pattern.compile("\\<\\?xml(.+?)\\?\\>");
public static <T> String toXML(final T data) {
try {
final var jaxbMarshaller = JAXBContext.newInstance(data.getClass()).createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
final var sw = new StringWriter();
jaxbMarshaller.marshal(data, sw);
return XMLUtils.REMOVE_HEADER.matcher(sw.toString()).replaceAll("").strip();
} catch (final JAXBException e) {
XMLUtils.LOGGER.error("Error while converting POJO to XML. ERROR: {}.", e.getMessage(), e);
}
return "";
}
Here's the log when I start the application with java -jar:
2021-12-26 21:19:14,526 [ForkJoinPool.commonPool-worker-11] ERROR com.enterprise.system.shared.util.XMLUtils - Error while converting POJO to XML. ERROR: Implementation of JAXB-API has not been found on module path or classpath..
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:232)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:375)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:691)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:632)
at com.enterprise.system.shared.util.XMLUtils.toXML(XMLUtils.java:26)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:720)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:952)
at java.base/java.util.stream.ReduceOps$ReduceTask.doLeaf(ReduceOps.java:926)
at java.base/java.util.stream.AbstractTask.compute(AbstractTask.java:327)
at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:92)
at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:125)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:230)
... 17 more
Here's an image of the generated spring-boot fat jar with the JAXB dependencies:
Here's my dependency tree:
--- maven-dependency-plugin:3.2.0:tree (default-cli) # java-eleven-jaxb-hell ---
com.enterprise.system:java-eleven-jaxb-hell:jar:0.0.1-SNAPSHOT
+- org.slf4j:slf4j-log4j12:jar:1.7.32:compile (optional)
| +- org.slf4j:slf4j-api:jar:1.7.32:compile (optional)
| \- log4j:log4j:jar:1.2.17:compile (optional)
+- org.springframework.boot:spring-boot-autoconfigure:jar:2.6.2:compile
| \- org.springframework.boot:spring-boot:jar:2.6.2:compile
| +- org.springframework:spring-core:jar:5.3.14:compile
| | \- org.springframework:spring-jcl:jar:5.3.14:compile
| \- org.springframework:spring-context:jar:5.3.14:compile
| +- org.springframework:spring-aop:jar:5.3.14:compile
| +- org.springframework:spring-beans:jar:5.3.14:compile
| \- org.springframework:spring-expression:jar:5.3.14:compile
+- org.projectlombok:lombok:jar:1.18.22:provided
+- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.3:compile
| \- jakarta.activation:jakarta.activation-api:jar:1.2.2:compile
\- com.sun.xml.bind:jaxb-impl:jar:2.3.5:runtime
\- com.sun.activation:jakarta.activation:jar:1.2.2:runtime
And finally, here are my model classes:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#XmlRootElement(name = "finans")
#XmlAccessorType(XmlAccessType.FIELD)
#Data
#NoArgsConstructor
#AllArgsConstructor
public class FinanTokenDTO {
#XmlAttribute
private String pln;
#XmlAttribute
private String ope;
#XmlAttribute
private String mod;
#XmlAttribute
private String mis;
#XmlAttribute
private String val;
#XmlAttribute
private String car;
#XmlAttribute
private String dti;
#XmlAttribute
private String dtf;
#XmlAttribute
private String ota;
#XmlElement
private FinanDTO finan;
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#XmlRootElement(name = "finan")
#XmlAccessorType(XmlAccessType.FIELD)
#Data
#NoArgsConstructor
#AllArgsConstructor
public class FinanDTO {
#XmlAttribute
private String prd;
#XmlAttribute
private String pkg;
#XmlAttribute
private String val;
#XmlAttribute
private String fty;
}
I am using java 11 and I am aware that in java 11 JAXB was removed from the SE JDK because it is considered as a EE feature.
I am not able to execute it using mvn spring-boot:run in production environment because of the size of the docker image and security related issues using docker container.
Since Spring Boot generates a fat jar, shouldn't the application run with java -jar applied to the spring boot fat jar generated file the same way as it does with mvn spring-boot:run inside the folder with pom.xml?
EDIT:
After a lot of digging and testing I found that the problem occurs when we try to marshall several valid POJOs using parallel stream instead of stream on the POJOs list. I uploaded the code in java-eleven-jaxb-hell to better understanding, unfortunatelly I cannot change parallelStream to stream because of performance issues. Just to remember, for the problem to happen you have to run java -jar against spring-boot generated fat jar in target folder.
Try adding the next dependency:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.1</version>
</dependency>
I suggest you to replace the JAXB-impl from Sun by the one from Glassfish:
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.5</version>
</dependency>
Generally speaking, Sun does not exists anymore since years, and the package might be there only for compatibility. The recommended JAXB implementation today comes from Glassfish.

How to use #ImportResource annotation import differrent enviroment config file

I'm trying to use #ImportResource annotation import on different environment config files like reported below:
#EnableFeignClients
#EnableAsync
#ImportResource(locations= {"classpath:${dev|sit}/service-applicationContext.xml","classpath:${dev|sit}/client-applicationContext.xml"})
public class DmrEsbService {
}
Or I'm trying to use other ways to import properties like spring.profiles.active=test, as I reported below:
#Value("${spring.profiles.active}")
public String env;
#Autowired
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
synchronized (lock) {
if (null == ESBClientFactory.applicationContext) {
String[] profiles = {"/profiles/" + env + "/client-applicationContext.xml", "/profiles/" + env + "/service-applicationContext.xml"};
ESBClientFactory.applicationContext = new ClassPathXmlApplicationContext(profiles, applicationContext);
}
}
}
but by using this last way to startup the app, it happened like below:
2021-12-10 15:04:16.005 - [<init> 122] - [INFO] - To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2021-12-10 15:04:16.027 - [getInstance 281] - [INFO] - DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration#1fdc92b
2021-12-10 15:04:17.795 - [refresh 554] - [WARN] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'publicQueryService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.CUXESBMASSQUERYPKGPortType' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
2021-12-10 15:04:17.810 - [log 173] - [INFO] - Stopping service [Tomcat]
2021-12-10 15:04:17.917 - [logMessage 142] - [INFO] -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-10 15:04:17.917 - [deregister 65] - [INFO] - Unregistering application xxxx with eureka with status DOWN
2021-12-10 15:04:17.918 - [shutdown 888] - [INFO] - Shutting down DiscoveryClient ...
2021-12-10 15:04:17.925 - [shutdown 911] - [INFO] - Completed shut down of DiscoveryClient
2021-12-10 15:04:18.225 - [report 42] - [ERROR] -
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.xxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.xxx' that could not be found.
Action:
Consider defining a bean of type 'com.xxx.oracle.xmlns.apps.cux.soaprovider.plsql.cux_esb_mass_query_pkg.xxx' in your configuration.
I could not use the command below to package an app:
mvn clean -Dmaven.test.skip=true package -pl xxx -am -Psit
and then I'm using the following:
mvn clean install
could anyone who can tell to how to import different environment in my project?

"Dependency problems found" when `mvn clean install` a che plugin project

I downloaded the che plugin project example che-ide-server-extension. It works when mvn clean install. But when I add a dependency in
che-ide-server-extension/plugins/plugin-serverservice/plugin-serverservice-ide/pom.xml
, it fails to install.
The dependency I added is
<dependency>
<groupId>org.eclipse.che.core</groupId>
<artifactId>che-core-ide-ui</artifactId>
</dependency>
And the error message of mvn clean install -e -X is:
...
[WARNING] Unused declared dependencies found:
[WARNING] org.eclipse.che.core:che-core-ide-ui:jar:6.16.0:compile
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Plugin ServerService :: Parent pom ................. SUCCESS [ 2.174 s]
[INFO] Plugin ServerService :: Plugins :: Parent ......... SUCCESS [ 0.064 s]
[INFO] Plugin ServerService :: Plugin :: Parent ........... SUCCESS [ 1.382 s]
[INFO] Plugin ServerService :: Plugin :: Server ........... SUCCESS [ 3.827 s]
[INFO] Plugin ServerService :: Plugin :: IDE .............. FAILURE [ 4.870 s]
[INFO] Plugin ServerService :: Che Assembly :: Assembly Parent SKIPPED
[INFO] Plugin ServerService :: Che Assembly :: Workspace Agent Assembly SKIPPED
[INFO] Plugin ServerService :: Che Assembly :: Workspace Agent Tomcat Assembly SKIPPED
[INFO] Plugin ServerService :: Che Assembly :: IDE Assembly SKIPPED
[INFO] Plugin ServerService :: Che Assembly :: Assemblies Tomcat SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.925 s
[INFO] Finished at: 2019-07-10T10:48:43+08:00
[INFO] Final Memory: 75M/1321M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-dependency-plugin:3.0.1:analyze-only (analyze) on project plugin-serverservice-ide: Dependency problems found -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-dependency-plugin:3.0.1:analyze-only (analyze) on project plugin-serverservice-ide: Dependency problems found
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Dependency problems found
at org.apache.maven.plugins.dependency.analyze.AbstractAnalyzeMojo.execute(AbstractAnalyzeMojo.java:261)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
... 20 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn <goals> -rf :plugin-serverservice-ide
I don't think I added a wrong dependency. Because when I
import org.eclipse.che.ide.ui.dialogs.DialogFactory;
in my java code, che says
The import org.eclipse.che.ide.ui.dialogs cannot be resolved.
But after I added the dependency, che can recognize it.
I don't know why this happens... The error message says Dependency problems found, but it didn't point out the real problem...
I've just checked and I didn't face any issues you mentioned above.
This my changes for the project:
diff --git a/plugins/plugin-serverservice/plugin-serverservice-ide/pom.xml b/plugins/plugin-serverservice/plugin-serverservice-ide/pom.xml
index 1237c6e..a5eed89 100644
--- a/plugins/plugin-serverservice/plugin-serverservice-ide/pom.xml
+++ b/plugins/plugin-serverservice/plugin-serverservice-ide/pom.xml
## -28,6 +28,10 ##
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
</dependency>
+<dependency>
+ <groupId>org.eclipse.che.core</groupId>
+ <artifactId>che-core-ide-ui</artifactId>
+</dependency>
<dependency>
<groupId>org.eclipse.che.core</groupId>
<artifactId>che-core-commons-gwt</artifactId>
diff --git a/plugins/plugin-serverservice/plugin-serverservice-ide/src/main/java/org/eclipse/che/sample/ide/MyServiceClient.java b/plugins/plugin-serverservice/plugin-serverservice-ide/src/main/java/org/eclipse/che/sample/ide/MyServiceClient.java
index cb1cf58..0def9c2 100644
--- a/plugins/plugin-serverservice/plugin-serverservice-ide/src/main/java/org/eclipse/che/sample/ide/MyServiceClient.java
+++ b/plugins/plugin-serverservice/plugin-serverservice-ide/src/main/java/org/eclipse/che/sample/ide/MyServiceClient.java
## -8,13 +8,15 ##
*/
package org.eclipse.che.sample.ide;
-import javax.inject.Inject;
import org.eclipse.che.api.promises.client.Promise;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.rest.AsyncRequestFactory;
import org.eclipse.che.ide.rest.StringUnmarshaller;
+import org.eclipse.che.ide.ui.dialogs.DialogFactory;
import org.eclipse.che.ide.ui.loaders.request.LoaderFactory;
+import javax.inject.Inject;
+
/**
* Client for consuming the sample server service.
*
## -25,6 +27,7 ## public class MyServiceClient {
private AppContext appContext;
private AsyncRequestFactory asyncRequestFactory;
private LoaderFactory loaderFactory;
+ private DialogFactory dialogFactory;
/**
* Constructor.
## -38,8 +41,10 ## public class MyServiceClient {
public MyServiceClient(
final AppContext appContext,
final AsyncRequestFactory asyncRequestFactory,
- final LoaderFactory loaderFactory) {
+ final LoaderFactory loaderFactory,
+ final DialogFactory dialogFactory) {
+ this.dialogFactory = dialogFactory;
this.appContext = appContext;
this.asyncRequestFactory = asyncRequestFactory;
this.loaderFactory = loaderFactory;
## -52,6 +57,7 ## public class MyServiceClient {
* #return a Promise containing the server response
*/
public Promise<String> getHello(String name) {
+ this.dialogFactory.createChoiceDialog("1", "2", "", "", null, null);
return asyncRequestFactory
.createGetRequest(appContext.getWsAgentServerApiEndpoint() + "/hello/" + name)
.loader(loaderFactory.newLoader("Waiting for hello..."))

ComponentScan and import org.springframework.context.annotation.ComponentScan can not be resolved as a type

I have a problem with my project in Spring. Firstly I couldn't run it on the server but after downloading all resources again it started.
But now I have some imports which Spring can not see
For example:
import org.springframework.context.annotation.ComponentScan can not be resolved as a type.
and autwired value
#ComponentScan can not be resolved as a type.
Because of that hibernate is not creating tables in my database ( I think so )
Also two configuration classes have some errors:
The hierarchy of the type Spring4Initializer is inconsistent
SpringSecurityInitializer
public class Spring4Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { Spring4Configuration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] { characterEncodingFilter };
}
}
SpringSecurityInitializer Multiple markers at this line
- The type org.springframework.web.WebApplicationInitializer cannot be resolved. It is indirectly referenced from
required .class files
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
I've tried maven clean and maven build
[WARNING]
[WARNING] Some problems were encountered while building the effective model for pl.dmcs:eschool:war:1.0.0-BUILD-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework:spring-context:jar -> version ${org.springframework-version} vs 4.3.7.RELEASE # line 74, column 17
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: com.fasterxml.jackson.core:jackson-databind:jar -> version 2.8.8 vs 2.8.3 # line 157, column 15
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: javax.servlet:servlet-api:jar -> version ${servlet-api-version} vs 2.5 # line 254, column 15
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework:spring-context:jar -> version ${org.springframework-version} vs 3.0.5.RELEASE # line 271, column 14
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building E-School 1.0.0-BUILD-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) # eschool ---
[INFO] Deleting C:\Users\Piotr\Desktop\E-School\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
Does anyone know what should I do with it to make hibernate working?
In Outline tree my function GetHibernateProperites() is marked as red
Have you included the spring-context in your maven dependencies? I think you are missing that dependency.

Migrate AbstractLobType to Hibernate 4 and Spring 3.2

I am currently using Hibernate 3 and Spring 3.0. I want to migrate to Hibernate 4 and Spring 3.2. I am using a subclass of AbstractLobType to implement a UserType that maps from an InputStream to the database (MySQL LONGBLOB):
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.orm.hibernate3.support.AbstractLobType;
public class BlobUserType extends AbstractLobType {
public int[] sqlTypes() {
return new int[] { Types.BLOB };
}
public Class returnedClass() {
return InputStream.class;
}
#Override
protected Object nullSafeGetInternal(ResultSet rs, String[] names, Object owner, LobHandler lobHandler)
throws SQLException, HibernateException {
return lobHandler.getBlobAsBinaryStream(rs, names[0]);
}
#Override
protected void nullSafeSetInternal(PreparedStatement ps, int index, Object value, LobCreator lobCreator)
throws SQLException, HibernateException {
if (value != null) {
lobCreator.setBlobAsBinaryStream(ps, index, (InputStream) value, -1);
} else {
lobCreator.setBlobAsBytes(ps, index, null);
}
}
}
Since AbstractLobType is in the hibernate3, I should not use it anymore, but what is the alternative?
I did read this JIRA issue on the spring project, but it does not help me at all.
This is the hibernate mapping:
<class name="SoundNotification" table="SoundNotification" entity-name="SoundNotificationWithData">
<id name="m_id" type="int" column="id" unsaved-value="-1">
<generator class="native"/>
</id>
<property name="m_name" column="name" unique="true" not-null="true"/>
<property name="m_data" column="data"
type="com.mycompany.server.common.service.persistence.impl.hibernate.usertype.BlobUserType"
not-null="true"/>
<property name="m_size" formula="OCTET_LENGTH(data)"/>
<property name="m_inUse"
formula="(select count(1) from EventTypeConfiguration etc where etc.soundNotification=id)"/>
</class>
And the Java class:
public class SoundNotification extends IntegerEntity
{
private String m_name;
private transient InputStream m_data;
private boolean m_inUse;
private long m_size;
// getters and setters ...
}
UPDATE with MaterializedBlobType:
My TrafficMap.hbm.xml:
<class name="TrafficMapImage" table="TrafficMapImage" entity-name="TrafficMapImageWithData">
<id name="m_id" column="id" type="int" unsaved-value="-1">
<generator class="native"/>
</id>
<property name="m_created" column="created" type="org.jadira.usertype.dateandtime.joda.PersistentDateTime"
not-null="true"/>
<property name="m_image" column="image"
type="org.hibernate.type.MaterializedBlobType"
not-null="true"/>
<property name="m_type" column="type" not-null="true">
<type name="com.traficon.tmsng.server.common.service.persistence.impl.hibernate.usertype.EnumUserType">
<param name="enumClass">com.traficon.domain.map.TrafficMapImageType</param>
</type>
</property>
</class>
The sessionFactory bean in my Spring context:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
hibernate.hbm2ddl.auto=${hibernate.hbm2ddl.auto}
hibernate.show_sql=${hibernate.show_sql}
hibernate.jdbc.batch_size=50
hibernate.jdbc.use_streams_for_binary=true
hibernate.current_session_context_class=com.traficon.tmsng.server.common.spring.TransactionAwareSessionContext
</value>
</property>
<property name="mappingResources">
<list>
<value>hibernate/authentication.hbm.xml</value>
<value>hibernate/SystemPrefs.hbm.xml</value>
<value>hibernate/Detector.hbm.xml</value>
<value>hibernate/filters.hbm.xml</value>
<value>hibernate/EventTypeConfiguration.hbm.xml</value>
<value>hibernate/Scenario.hbm.xml</value>
<value>hibernate/RunningScenario.hbm.xml</value>
<value>hibernate/StorePoint.hbm.xml</value>
<value>hibernate/OfflineNetwork.hbm.xml</value>
<value>hibernate/Characteristics.hbm.xml</value>
<value>hibernate/EventType.hbm.xml</value>
<value>hibernate/EventStore.hbm.xml</value>
<value>hibernate/IntervalDataMessage.hbm.xml</value>
<value>hibernate/IntegrationPeriodConstraints.hbm.xml</value>
<value>hibernate/Media.hbm.xml</value>
<value>hibernate/TrafficMap.hbm.xml</value>
<value>hibernate/CommentLibrary.hbm.xml</value>
<value>hibernate/CommentHistory.hbm.xml</value>
<value>hibernate/Dashboard.hbm.xml</value>
</list>
</property>
<property name="entityInterceptor">
<bean class="com.traficon.tmsng.server.common.service.persistence.impl.hibernate.RollbackReintializerInterceptor"
scope="prototype"/>
</property>
</bean>
The logging output:
[WARNING] [talledLocalContainer] INFO: Initializing Spring root WebApplicationContext
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:10,525 [main] INFO hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:10,537 [main] INFO org.hibernate.Version - HHH000412: Hibernate Core {4.2.7.Final}
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:10,544 [main] INFO org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.jdbc.use_streams_for_binary=true, hibernate.bytecode.use_reflection_optimizer=false}
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:10,545 [main] INFO org.hibernate.cfg.Environment - HHH000407: Using java.io streams to persist binary types
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:10,546 [main] INFO org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
[INFO] [talledLocalContainer] 13 Dec 2013 13:54:12,302 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
....
[INFO] [talledLocalContainer] 13 Dec 2013 14:06:12,136 [http-8080-4] INFO hibernate.event.internal.DefaultLoadEventListener - HHH000327: Error performing load command : org.hibernate.PropertyAccessException: could not set a field value by reflection setter of com.traficon.domain.map.TrafficMapImage.m_image
[WARNING] [talledLocalContainer] Dec 13, 2013 2:06:12 PM org.apache.catalina.core.StandardWrapperValve invoke
[WARNING] [talledLocalContainer] SEVERE: Servlet.service() for servlet mediaServlet threw exception
[WARNING] [talledLocalContainer] java.lang.IllegalArgumentException: Can not set java.io.InputStream field com.traficon.domain.map.TrafficMapImage.m_image to [B
[WARNING] [talledLocalContainer] at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
[WARNING] [talledLocalContainer] at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
[WARNING] [talledLocalContainer] at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
[WARNING] [talledLocalContainer] at java.lang.reflect.Field.set(Field.java:741)
[WARNING] [talledLocalContainer] at org.hibernate.property.DirectPropertyAccessor$DirectSetter.set(DirectPropertyAccessor.java:139)
[WARNING] [talledLocalContainer] at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:710)
[WARNING] [talledLocalContainer] at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:379)
[WARNING] [talledLocalContainer] at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4523)
[WARNING] [talledLocalContainer] at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:186)
[WARNING] [talledLocalContainer] at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:137)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1108)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.processResultSet(Loader.java:964)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.doQuery(Loader.java:911)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:312)
[WARNING] [talledLocalContainer] at org.hibernate.loader.Loader.loadEntity(Loader.java:2121)
[WARNING] [talledLocalContainer] at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:82)
[WARNING] [talledLocalContainer] at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:72)
[WARNING] [talledLocalContainer] at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3941)
[WARNING] [talledLocalContainer] at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:460)
[WARNING] [talledLocalContainer] at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:429)
[WARNING] [talledLocalContainer] at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:206)
[WARNING] [talledLocalContainer] at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:246)
[WARNING] [talledLocalContainer] at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
[WARNING] [talledLocalContainer] at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1098)
[WARNING] [talledLocalContainer] at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:175)
[WARNING] [talledLocalContainer] at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2482)
[WARNING] [talledLocalContainer] at org.hibernate.internal.SessionImpl.get(SessionImpl.java:998)
[WARNING] [talledLocalContainer] at com.traficon.tmsng.server.common.service.persistence.impl.hibernate.HibernateTrafficMapRepository.getTrafficMapImageWithData_aroundBody6(HibernateTrafficMapRepository.java:176)
[WARNING] [talledLocalContainer] at com.traficon.tmsng.server.common.service.persistence.impl.hibernate.HibernateTrafficMapRepository$AjcClosure7.run(HibernateTrafficMapRepository.java:1)
[WARNING] [talledLocalContainer] at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:59)
[WARNING] [talledLocalContainer] at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:65)
[WARNING] [talledLocalContainer] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
[WARNING] [talledLocalContainer] at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:63)
[WARNING] [talledLocalContainer] at com.traficon.tmsng.server.common.service.persistence.impl.hibernate.HibernateTrafficMapRepository.getTrafficMapImageWithData(HibernateTrafficMapRepository.java:173)
[WARNING] [talledLocalContainer] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[WARNING] [talledLocalContainer] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[WARNING] [talledLocalContainer] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[WARNING] [talledLocalContainer] at java.lang.reflect.Method.invoke(Method.java:606)
[WARNING] [talledLocalContainer] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
[WARNING] [talledLocalContainer] at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
[WARNING] [talledLocalContainer] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
[WARNING] [talledLocalContainer] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
[WARNING] [talledLocalContainer] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
[WARNING] [talledLocalContainer] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
[WARNING] [talledLocalContainer] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
[WARNING] [talledLocalContainer] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
[WARNING] [talledLocalContainer] at com.sun.proxy.$Proxy39.getTrafficMapImageWithData(Unknown Source)
[WARNING] [talledLocalContainer] at com.traficon.tmsng.server.web.mvc.DownloadTrafficMapImageController.onSubmit(DownloadTrafficMapImageController.java:40)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:268)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
[WARNING] [talledLocalContainer] at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
[WARNING] [talledLocalContainer] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
[WARNING] [talledLocalContainer] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
[WARNING] [talledLocalContainer] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
[WARNING] [talledLocalContainer] at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:568)
[WARNING] [talledLocalContainer] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
[WARNING] [talledLocalContainer] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
[WARNING] [talledLocalContainer] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
[WARNING] [talledLocalContainer] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
[WARNING] [talledLocalContainer] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
[WARNING] [talledLocalContainer] at java.lang.Thread.run(Thread.java:744)
[WARNING] [talledLocalContainer]
In theory you should use the hibernate provided MaterializedBlobType if you want to use InputStreams for your Blob then add the following property to you hibernate configuration
hibernate.jdbc.use_streams_for_binary=true
This will instruct the MaterializedBlobType to use an InputStream instead of a byte[].
I ended up creating my own UserType that converts between Blob and InputStream:
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class BlobUserType implements UserType
{
// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface UserType ---------------------
#Override
public int[] sqlTypes()
{
return new int[]{Types.BLOB};
}
#Override
public Class returnedClass()
{
return InputStream.class;
}
#Override
public boolean equals( Object x, Object y ) throws HibernateException
{
boolean result;
if (x == y)
{
result = true;
}
else if (x == null || y == null)
{
result = false;
}
else
{
result = x.equals( y );
}
return result;
}
#Override
public int hashCode( Object x ) throws HibernateException
{
return x.hashCode();
}
#Override
public Object nullSafeGet( ResultSet rs, String[] names, SessionImplementor session, Object owner ) throws HibernateException, SQLException
{
return rs.getBlob( names[0] ).getBinaryStream();
}
#Override
public void nullSafeSet( PreparedStatement st, Object value, int index, SessionImplementor session ) throws HibernateException, SQLException
{
if( value != null )
{
InputStream inputStream = (InputStream)value;
st.setBlob( index, inputStream );
}
else
{
st.setNull( index, Types.BLOB );
}
}
#Override
public Object deepCopy( Object value ) throws HibernateException
{
return value;
}
#Override
public boolean isMutable()
{
return false;
}
#Override
public Serializable disassemble( Object value ) throws HibernateException
{
return null;
}
#Override
public Object assemble( Serializable cached, Object owner ) throws HibernateException
{
return null;
}
#Override
public Object replace( Object original, Object target, Object owner ) throws HibernateException
{
return original;
}
}
Seems to be working fine loading and saving my entity from/to the database.
You should not use AbstractLobType because it is in the hibernate 3 as you said.
You can create your own UserType to convert between Blob and InputStream. However, if you are migrating existing data from Hibernate 3 to 4, your code will not work:
The format of BlobSerializableType has header's information in addition which is something like this:
’ t{"userServices":[{"accountStatus":"PendingTermsAndConditions","serviceIdentifier":"SNG"}]...}]}
Your code will working (reading, writing) to the format without header:
{"userServices":[{"accountStatus":"PendingTermsAndConditions","serviceIdentifier":"SNG"}]...}]}
My personal solution is to simulate the Hibernate 3 to write and read Blob data as below:
package com.newbay.acs.domain.hibernate;
import org.apache.commons.io.IOUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* Created by qale0001 on 21/06/2016.
*/
public class CustomMaterializedBlobType implements UserType
{
private static final int OUTPUT_BYTE_ARRAY_INITIAL_SIZE = 1024;
#Override
public int[] sqlTypes()
{
return new int[]{Types.BLOB};
}
#Override
public Class returnedClass()
{
return String.class;
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
boolean result;
if (x == y)
{
result = true;
}
else if (x == null || y == null)
{
result = false;
}
else
{
result = x.equals( y );
}
return result;
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
java.sql.Blob blob = rs.getBlob( names[0] );
InputStream is = blob.getBinaryStream();
if (is != null) {
try {
ObjectInputStream ois = new ObjectInputStream(is);
try {
return ois.readObject();
} catch (ClassNotFoundException ex) {
throw new HibernateException("Could not deserialize BLOB contents", ex);
} finally {
ois.close();
}
} catch (IOException ex) {
throw new HibernateException("Could not deserialize BLOB contents", ex);
}
}
else {
return null;
}
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
if( value != null )
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
try {
oos.writeObject(value);
oos.flush();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
st.setBlob(index, is);
}
finally {
oos.close();
}
} catch (IOException ex) {
throw new HibernateException("Could not serialize BLOB contents", ex);
}
}
else
{
st.setNull( index, Types.BLOB );
}
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return null;
}
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return null;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}

Resources