Passing dataSet to SubReport in Jasper - jasper-reports

I have a Student object contain a list of Courses and i need to display Student List with the list of courses of each student in a report.
Student Class
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Student {
private String name;
private String email;
private List<Course> courseList;
}
Course class
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Course {
private String name;
private String location;
private BigDecimal price;
}
StudentGenerator To generate PDF
#Component
public class StudentGenerator {
public ResponseEntity<byte[]> getMyPdf() throws ParseException, FileNotFoundException, JRException {
List<Student> students = getStudents(); // Student Factory
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "MY REPORT");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(students, false);
JasperReport compileReport = JasperCompileManager.compileReport(
new FileInputStream("myFile.jrxml"));
JasperPrint jasperPrint = JasperFillManager.fillReport(compileReport, parameters, beanCollectionDataSource);
byte data[] = JasperExportManager.exportReportToPdf(jasperPrint);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "inline; filename=my_pdf.pdf");
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_PDF).body(data);
}
}
In Jasper I create My Main Report
To Link My SubReport to Main Report, I added In SubReport Data Source Expression the expression :
And Finally, i added course fields in SubReport :
But When i run the project, i got this error that i don't understand:
java.lang.ClassNotFoundException: net.sf.jasperreports.compilers.ReportExpressionEvaluationData
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]
at java.base/java.lang.Class.forName0(Native Method) ~[na:na]
at java.base/java.lang.Class.forName(Class.java:467) ~[na:na]
at java.base/java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:778) ~[na:na]
at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.resolveClass(ContextClassLoaderObjectInputStream.java:89) ~[jasperreports-6.7.0.jar:6.6.0]
at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:2045) ~[na:na]
I got the error only when i add the SubReport !
Many Thanks for any help

this error is happening because you are passing the subreport to the TITLE variable.
The most common way to pass a subreport via java to jasper is by variable, so I recommend doing it this way.
JasperReport jasperMasterReport = JasperCompileManager.compileReport(master);
JasperReport jasperSubReport = JasperCompileManager.compileReport(sub);
Map<String, Object> map = new HashMap<String, Object>();
map.put("SUBREPORT_DIR", jasperSubReport);
JasperPrint print = JasperFillManager.fillReport(jasperMasterReport,map, buildDatasource(data));
in your jasper wait the sub this way
<parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false"/>
<subreport>
<reportElement positionType="Float" x="1" y="0" width="553" height="20" uuid="dcb4de43-b64f-4e50-a4b1-5ad31a1cd9a2"/>
<dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("carga.ordens")]]></dataSourceExpression>
<subreportExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportExpression>
</subreport>
this way the map will send its jasper (already compiled) to the variable SUBREPORT_DIR
how your expression editor will look
how your datasource
in my case i use jsondatasource, but you can adapt to your demand

Related

java.sql.SQLSyntaxErrorException in mybatis

The phenomenon and background of the problem encountered
Problems encountered when configuring mybatis and writing tests, an error will be reported as soon as you click to run
problem related code,
#Test
public void findmany() throws IOException
{
InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession =sqlSessionFactory.openSession();
Map<String,Object> params = new HashMap<>();
params.put("name", "sam");
params.put("major", "");
List<Student> student=sqlSession.selectList("com.javaee.pojo.Student.findmany",params);
System.out.println(student);
Map<String,Object> params2 = new HashMap<>();
params2.put("name", "");
params2.put("major", "math");
student=sqlSession.selectList("com.javaee.pojo.Student.findmany",params2);
System.out.println(student);
Map<String,Object> params3 = new HashMap<>();
params3.put("name", "");
params3.put("major", "");
student=sqlSession.selectList("com.javaee.pojo.Student.findmany",params3);
System.out.println(student);
sqlSession.close();
}
mapper
<select id="findmany"
parameterType="map"
resultType="com.javaee.pojo.Student">
select * from students where name like concat('%',#{name},'%') major like concat('%',#{major},'%')
</select>
Student Class
public class Student {
private int id;
private String name;
private String major;
private String sno;
public String toString()
{
return "Student{"+"id="+id+",sno='"+sno+'\''+",name='"+name+'\''+",major='"+major+'\''+'}';
}
Running results and error content
enter image description here
Missing an AND in your select, try this way:
select * from students where name like concat('%',#{name},'%') AND major like concat('%',#{major},'%')

Eclipse JPA project (eclipselink, derby) -- "create tables from entities" produces tables in schema. yet not for SELECT * FROM TABLE_NAME;

I'm using eclipse JPA project to create entities in Apache Derby. I'm using the JPA Tools:
"generate tables from entities.."
command. When I use this command, the tables are put into the database. I can see the tables, and that they have columns from the Eclipse "Data Source Explorer". When I log in to Derby through ij.
I type:
'show tables in schema x';
I get a list of the table names that correspond to the entities.
I type:
'select * from <table in x>'
I get:
ERROR 42X05: Table/View 'ADDRESS' does not exist.
Why do my tables not stick..? When I use the CREATE TABLE commands that are being entered in during use of the "generate tables from entities.." command, they produce tables there. When I type 'select * .." I get a table.
Second, probably related problem. I have a class. I use the following commands to obtain an entity manager:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
If I run a test on my entities, such as this:
public void runTest()
{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
System.out.println(emf == null);
Address address = new Address();
address.setAddressID("1");
address.setAddressNumber(1746);
address.setStreetName("Howard");
address.setStreetType("Court");
address.setCity("Lennyville");
address.setState("CT");
address.setZipcode(73625);
em.persist(address);
em.close();
emf.close();
// reassign:
emf = Persistence.createEntityManagerFactory("DataModelAccess");
em = emf.createEntityManager();
Address address2 = em.find(Address.class, "1");
System.out.println(address2.getCity());
I get a NullPointerException on the last line.
If I do not re-assign to emf and em, It will print the city to the console.
So,
1. Why do tables not appear for SELECT * FROM <TABLE_NAME>?
But do appear for SHOW TABLES IN <SCHEMA>?
2. Why is my data not persistent across sessions?
I'm running this in Eclipse, from a plain old Java SE object. There is no Java EE container. It's an Eclipse JPA project. There is a persistence.xml file. There is a connection called 'derby' that is managed by eclipse. Maybe I have a persistence.xml file problem? Maybe this is a common problem for everyone. Maybe JPA and eclipselink do this by default because of some differing access protocol? Maybe not having a Java EE Container is making it difficult?
========
As requested:
the address class is totally irrelevant. I've tried both field and property based access also. It makes no difference to IJ. Both attempts fail equally well. This is a summary:
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
...
#Id
public String getAddressID()
every thing else is fields, constructor, getters and setters. No annotations. I just added a new JPA entity by right-clicking on my package and selecting
New --> JPA Entity
I put the fields in it using the eclipse wizard. I made it property-based. I thought maybe field-based access would change things, so I tried field-based, but it made no difference.
where you see this: address.setStreetName("Howard");
there is the field:
private String streetName;
and two corresponding methods
setStreetName(String x);
and
String getStreetName();
The same formula exists for all fields in the class. Each field has a getter and a setter. There are no more methods than the getters and the setters. 1 field per each getter/setter method pair. There are no more annotations than I mentioned.
Just for information: I do not set all of the properties for the Address class. The fields in the table were all entered into the database as NULLABLE. Yet, IJ does not find any TABLE. – user1405870 11 hours ago
=========
Here's the Address and Address_ classes:
package dataAccess.customer;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="Dali", date="2012-05-18T21:44:02.229-0500")
#StaticMetamodel(Address.class)
public class Address_
{
public static volatile SingularAttribute<Address, String> addressID;
public static volatile SingularAttribute<Address, Integer> addressNumber;
public static volatile SingularAttribute<Address, String> streetName;
public static volatile SingularAttribute<Address, String> streetType;
public static volatile SingularAttribute<Address, String> building;
public static volatile SingularAttribute<Address, String> floor;
public static volatile SingularAttribute<Address, String> unit;
public static volatile SingularAttribute<Address, String> landmarkName;
public static volatile SingularAttribute<Address, String> city;
public static volatile SingularAttribute<Address, String> state;
public static volatile SingularAttribute<Address, Integer> zipcode;
}
package dataAccess.customer;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Address
*
*/
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
{
private String addressID;
private Integer addressNumber;
private String streetName;
private String streetType;
private String building;
private String floor;
private String unit;
private String landmarkName;
private String city;
private String state;
private Integer zipcode;
private static final long serialVersionUID = 1L;
public Address()
{
}
#Id
public String getAddressID()
{
return addressID;
}
public void setAddressID(String addressID)
{
this.addressID = addressID;
}
public Integer getAddressNumber()
{
return this.addressNumber;
}
public void setAddressNumber(Integer addressNumber)
{
this.addressNumber = addressNumber;
}
public String getStreetName()
{
return this.streetName;
}
public void setStreetName(String streetName)
{
this.streetName = streetName;
}
public String getStreetType()
{
return this.streetType;
}
public void setStreetType(String streetType)
{
this.streetType = streetType;
}
public String getBuilding()
{
return this.building;
}
public void setBuilding(String building)
{
this.building = building;
}
public String getFloor()
{
return this.floor;
}
public void setFloor(String floor)
{
this.floor = floor;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
public String getLandmarkName()
{
return this.landmarkName;
}
public void setLandmarkName(String landmarkName)
{
this.landmarkName = landmarkName;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return this.state;
}
public void setState(String state)
{
this.state = state;
}
public Integer getZipcode()
{
return this.zipcode;
}
public void setZipcode(Integer zipcode)
{
this.zipcode = zipcode;
}
}
Here's the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="DataModelAccess" transaction-type="RESOURCE_LOCAL">
<class>dataAccess.customer.Person</class>
<class>dataAccess.customer.Address</class>
<class>dataAccess.customer.PhoneNumber</class>
<class>dataAccess.customer.Customer</class>
<class>dataAccess.customer.TwoFieldTest</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation.output-mode" value="database"></property>
<property name="eclipselink.target-database" value="derby"/>
<property name="eclipselink.target-server" value="None"/>
<property name="eclipselink.exclude-eclipselink-orm" value="true"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/sample;create=true"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.bind-parameters" value="false"/>
<property name="eclipselink.jdbc.exclusive-connection.mode" value="Transactional"/>
<property name="eclipselink.orm.validate.schema" value="true"/>
<property name="eclipselink.orm.throw.exceptions" value="true"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Comments:
calling
em.flush();
is exactly what I did, in order to check if the data was persisting across sessions (which it does not). In other words, when I run the method "runTest()" I get the correct print statements, under the original runTest() method. I have posted the altered "runTest()" method (see the: //reassign "comment"). Now, when I have a customer, which I build out of three entities: address, phoneNumber, and, person, the customer can instantiated through finding the other three entities "in the database", with the entity manager. However, if I comment out everything, except for the code that looks up the three entities in the database and creates a new customer, then I find that I cannot get the data out of the database.
that looks like this:
Customer c = new Customer();
c.setAddress(em.find(Address.class, "1"));
c.setPhoneNumber(em.find(PhoneNumber.class, "1"));
c.setName(em.find(Person.class, "1"));
c.setCustomerID("123");
em.persist(c);
*/
Customer actual = em.find(Customer.class, "123");
and when I comment out everything until after em.persist(c), I do not get any Customer actual.
normally, I get this:
Customer:
Name:
Mr. Howard T Stewart III
Address:
1746 Howard Court
Lennyville, CT 73625
Phone:
(215) 256-4563
But when I comment out everything until
Customer actual = em.find(Customer.class, "123");
(now.. I instantiated the em in a previous line, but I did not now create person, phone_number, or address.)
Then, .. I get,
(actual == null)
evaluates to true.
Am I misusing the "find()" command? Am I supposed to do something else to load a current connection to the database or something (in terms of commands through em (em.method())?
Remember that there is no Java EE container here. I'm just doing this in eclipse, running main methods in j2se programs, in a JPA project in eclipse, using eclipselink 2.3. But this is not EJB, nor is it ManagedBeans or etc.
So..
I found this:
#Resource
UserTransaction utx;
...
try {
utx.begin();
bookDBAO.buyBooks(cart);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception exe) {
System.out.println("Rollback failed: "+exe.getMessage());
}
...
Unfortunately, I didn't find anything about UserTransaction until I got to the Web portion of the java ee tutorial, so, as such, I was unable to find the sentence that said "user transaction" amidst all the implication that em.persist() is all that it takes. Also, #Resource might not work outside of a Java EE Container.
Daniel: thank you for the comment, it gave me the answer that I needed.
Even though I had found the above items, and although I was doing this:
em.getTransaction().begin();
// .. set fields of address ..
em.persist(address);
em.getTransaction().commit();
em.close();
It still wasn't working. When I changed the persistence.xml file to only CREATE tables, the test method runs correctly, and, when I comment out everything but retrieve the customer from the database, that returns correctly as well.
I have also tried:
SELECT * FROM <SCHEMA>.ADDRESS;
and that works fine as well. Thank you so much, as finding out what the entity manager is actually doing because of the "DROP AND CREATE TABLES" directive would likely be a very hard thing to track down amongst tutorials.
In your persistence.xml you have,
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
This means every time you create a new EntityManagerFactory you will recreate your database, loosing all of the data.
Either remove this, or change it to "create-tables" to only create.
For your first issue, try ., i.e. x.address
since you are using Eclipselink JPA, it will not follow standard syntax of SQL query if you are using standard "createQuery" method
You need to use this:
select t from table1 t
instead of
select * from table1
It follows syntax of JPQL. See this link for more info.
But if you want to use native sql method, use "createNativeMethod" from manager instance

exception in gwt hibernate program

I am trying to make a simple GWT RPC Hibernate program that adds a user to MySQL database. I am using Eclipse EE. The application is successfully adding user to database but it raises exception when compiled.
Here is the exception & source of my application.
exception:
Exception in thread "UnitCacheLoader" java.lang.RuntimeException: Unable to read from byte cache
at com.google.gwt.dev.util.DiskCache.transferFromStream(DiskCache.java:166)
at com.google.gwt.dev.util.DiskCacheToken.readObject(DiskCacheToken.java:87)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.google.gwt.dev.javac.PersistentUnitCache.loadUnitMap(PersistentUnitCache.java:493)
at com.google.gwt.dev.javac.PersistentUnitCache.access$000(PersistentUnitCache.java:92)
at com.google.gwt.dev.javac.PersistentUnitCache$UnitCacheMapLoader.run(PersistentUnitCache.java:122)
Caused by: java.io.StreamCorruptedException: unexpected EOF in middle of data block
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.read(Unknown Source)
at java.io.ObjectInputStream.read(Unknown Source)
at java.io.InputStream.read(Unknown Source)
at com.google.gwt.dev.util.DiskCache.transferFromStream(DiskCache.java:154)
... 16 more
entrypoint class:
package rpctest.client;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
final Label label1 = new Label("First Name");
final Label label2 = new Label("Last Name");
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync calNumbers = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
addpanel1.add(label1);
addpanel1.add(firstName);
addpanel2.add(label2);
addpanel2.add(lastName);
mainpanel.add(addpanel1);
mainpanel.add(addpanel2);
mainpanel.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String name1 = firstName.getValue();
String name2 = lastName.getValue();
calNumbers.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
Window.alert("User is ->"+result);
}
});}
});
// We can add style names to widgets
//sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
/*RootPanel.get("nameFieldContainer").add(nameField);
*
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);*/
RootPanel.get().add(mainpanel);
}
}
interfaces:
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("testService")
public interface RpctestService extends RemoteService {
String addUser(String firstName,String lastName) throws IllegalArgumentException;
}
package rpctest.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RpctestServiceAsync {
void addUser(String firstName, String lastName,
AsyncCallback<String> callback);
}
service Implementation class:
package rpctest.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
import rpctest.client.RpctestService;
public class RpctestServiceImpl extends RemoteServiceServlet implements RpctestService {
public String addUser(String name1, String name2)
throws IllegalArgumentException {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
User user = new User();
user.setFirstName(name1);
user.setLastName(name2);
session.save(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
return name1;
}
}
pojo class:
package hibDomain;
public class User {
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
mapping file:
<?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>
<class name="hibDomain.User" table="users" >
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="firstName">
<column name="first_name" />
</property>
<property name="lastName">
<column name="last_name"/>
</property>
</class>
</hibernate-mapping>
cfg file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/userdata</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Util class:
package rpctest.server;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
This unlikely to be related to running out of disk space.
Much more likely you either built as a different user or for some other reason there are existing, invalid, temporary files which are causing the problem.
Look in your GWT dir for the directories "gwt-unitCache", and "reports". Delete them. Then run ant clean, ant test; that should solve the problem~
Almost certainly the reason it 'suddenly started worked' was you did something like a fresh git clone or cleared out the directory, deleting these files. :)
Delete ./src/main/gwt-unitCache.
You ran out of disk space.
GWT compiler could not find temp space.

SOAP security in Salesforce

I am trying to change the wsdl2apex code for a web service call header that currently looks like this:
<env:Header>
<Security xmlns="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd">
<UsernameToken Id="UsernameToken-4">
<Username>test</Username>
<Password>test</Password>
</UsernameToken>
</Security>
</env:Header>
to look like this:
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-4" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>Test</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">Test</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
One problem is that I can't work out how to change the namespaces for elements (or even if it matters what name they have). A secondary problem is putting the Type attribute onto the Password element.
Can any provide any information that might help?
Thanks
I was having a similar issue. I was able to generate the following SOAP Header which worked for my implementation:
<env:Header>
<Security xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<UsernameToken>
<Username>aaaaaa</Username>
<Password>xxxxxx</Password>
<Nonce>MzI3MTUzODg0MjQy</Nonce>
<wsu:Created>2013-04-23T16:09:00.701Z</wsu:Created>
</UsernameToken>
</Security>
</env:Header>
Security Class:
public class OasisOpenOrgWssSecuritySecext
{
// UserToken Class
public class UsernameToken
{
// Constructor for UsernameToken used to pass in username and password parameters
public UsernameToken(String username, String password)
{
this.Username = username;
this.Password = password;
this.Nonce = generateNounce();
this.Created = generateTimestamp();
}
public String Username;
public String Password;
public String Nonce;
public String Created;
private String[] Username_type_info = new String[]{'Username','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Password_type_info = new String[]{'Password','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Nonce_type_info = new String[]{'Nonce','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] Created_type_info = new String[]{'wsu:Created','http://www.w3.org/2001/XMLSchema','string','0','1','false'};
private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
private String[] field_order_type_info = new String[]{'Username','Password','Nonce','Created'};
// Generate Nounce, random number base64 encoded
public String generateNounce()
{
Long randomLong = Crypto.getRandomLong();
return EncodingUtil.base64Encode(Blob.valueOf(String.valueOf(randomLong)));
}
// Generate timestamp in GMT
public String generateTimestamp()
{
return Datetime.now().formatGmt('yyyy-MM-dd\'T\'hh:mm:ss\'Z\'');
}
}
// SecurityHeaderType Class
public class SecurityHeaderType
{
// Constructor for SecurityHeaderType used to pass in username and password parameters and instantiate the UsernameToken object
public SecurityHeaderType(String username, String password)
{
this.UsernameToken = new OasisOpenOrgWssSecuritySecext.UsernameToken(username, password);
}
public String wsuNamespace = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd';
public OasisOpenOrgWssSecuritySecext.UsernameToken UsernameToken;
private String[] UsernameToken_type_info = new String[]{'UsernameToken','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','UsernameToken','1','1','false'};
private String[] wsuNamespace_att_info = new String[]{'xmlns:wsu'};
private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
private String[] field_order_type_info = new String[]{'UsernameToken'};
}
}
Add the lines between the comments to your class generated by wsdl2apex:
public class XyzWebService {
public String endpoint_x = 'https://webservice/'
// ADDITION TO WSDL
public OasisOpenOrgWssSecuritySecext.SecurityHeaderType Security = new OasisOpenOrgWssSecuritySecext.SecurityHeaderType( 'aaaaaa', 'xxxxxx');
private String Security_hns = 'Security=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';**
// END ADDITION TO WSDL
public Map<String,String> inputHttpHeaders_x;
public Map<String,String> outputHttpHeaders_x;
public String clientCertName_x;
public String clientCert_x;
public String clientCertPasswd_x;
public Integer timeout_x;
I had a similar problem. I manually created a class to create the basic structure. Fortunately, the service I was consuming either assumed or was able to determine that the type was text without the type parameter being explicitly set, so you may want to try that and see if it works.
For the namespaces I set those up as attributes:
private String[] wsu_att_info = new String[] {'xmlns:wsu'};
This question may also be helpful: What are the parameters for the Salesforce WebServiceCallout.invoke method?
Might not be possible for everyone, but we managed to solve the problem by using XSLT to transform the SOAP we had into the SOAP we wanted.

JPA Entity not using #Column annotation

I have the following simple entity:
package net.plus.msodb.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(schema="msodb", name="mso")
public class Mso implements Serializable {
#Id
private Integer incidentReference;
private String detectedDate;
private String detectedTime;
private String startDate;
private String startTime;
private String anticipatedClearDate;
private String anticipatedClearTime;
private String actualClearDate;
private String actualClearTime;
private String headline;
private String progress;
private String details;
private String servicesType;
private String servicesCount;
public Mso() {
}
#Column(name="detectedDate")
public String getDetectedDate() {
if(detectedDate == "") {
return null;
}
return detectedDate + " " + detectedTime;
}
/*
* Getters & Setters removed to save space
*/
#Column(name="detectedDate")
public void setDetectedDate(String detectedDate) {
this.detectedDate = detectedDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public void setAnticipatedClearDate(String anticipatedClearDate) {
this.anticipatedClearDate = anticipatedClearDate;
}
public void setActualClearDate(String actualClearDate) {
this.actualClearDate = actualClearDate;
}
}
and this is Smooks the config I'm using:
<?xml version="1.0" encoding="UTF-8"?><smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd">
<params>
<param name="stream.filter.type">SAX</param>
<param name="inputType">input.xml</param>
<param name="input.xml" type="input.type.actived">Workspace://MSODBActions/src/test/resources/msos.xml</param>
</params>
<jb:bean beanId="Mso" class="net.plus.msodb.model.Mso" createOnElement="/msos/mso">
<jb:value data="/msos/mso/#actualClearDate" property="actualClearDate"/>
<jb:value data="/msos/mso/#actualClearTime" property="actualClearTime"/>
<jb:value data="/msos/mso/#anticipatedClearDate" property="anticipatedClearDate"/>
<jb:value data="/msos/mso/#anticipatedClearTime" property="anticipatedClearTime"/>
<jb:value data="/msos/mso/#details" property="details"/>
<jb:value data="/msos/mso/#detectedDate" property="detectedDate"/>
<jb:value data="/msos/mso/#detectedTime" property="detectedTime"/>
<jb:value data="/msos/mso/#headline" property="headline"/>
<jb:value data="/msos/mso/#incidentReference" decoder="Integer" property="incidentReference"/>
<jb:value data="/msos/mso/#progress" property="progress"/>
<jb:value data="/msos/mso/#servicesCount" property="servicesCount"/>
<jb:value data="/msos/mso/#servicesType" property="servicesType"/>
<jb:value data="/msos/mso/#startDate" property="startDate"/>
<jb:value data="/msos/mso/#startTime" property="startTime"/>
</jb:bean>
</smooks-resource-list>
When I try and save the entity, I get the following error:
Data truncation: Incorrect datetime value: '' for column 'detectedDate' at row 1
You can see from the getter for detectedDate that if the detectedDate is an empty string (which it is if that attribute is missing from the source XML for the Smooks transformation) then the getter should return null.
Debugging this part of the code it does indeed return null.
It's almost like the getter isn't being used to get the value for detectedDate. If it were it would either be null, or at least a single space string.
In answer to my own question, the problem comes from the fact you can only annotate the member definitions or the methods, but not both. Notice I had annotated the #Id member variable & put the other annotations on the methods.
Move the #Id annotation to the getter for that field to solve the problem.