Hibernate get object and save as foreign key - java

How to correctly save new record many to one?
Get object pcKey(one,works fine)
Create new computer object with foreign key (object pcKey)
Send to Dao class
Try to save object
Error
RegisterComputerService
public Boolean registerPc(String cpu, String gpu, String motherBoard,
String hdd, String pcName, String pcKeyString) {
IsPcKeyExistDao IsPcKeyExistDao = new IsPcKeyExistDao();
PcKey pcKey = IsPcKeyExistDao.isKeyExist(pcKeyString);
IsPcWithPcKeyActiveDao isPcWithPcKeyActiveDao = new IsPcWithPcKeyActiveDao();
Boolean isPcExist = isPcWithPcKeyActiveDao.isPcExist(pcKey);
RegisterPcDao registerPcDao = new RegisterPcDao();
Computer computer = new Computer();
computer.setPcKey(pcKey);
computer.setRegDate(new Date());
Boolean result = registerPcDao.registerPc(computer, pcKey);
return result;
}
registerPc
public Boolean registerPc(Computer computer, PcKey pcKey){
Session session = null;
Transaction tx = null;
try {
session = HibernateAnnotationUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
tx.setTimeout(5);
session.save(computer);
tx.commit();
return true;
} catch (RuntimeException e) {
try {
tx.rollback();
} catch (RuntimeException rbe) {
// log.error("Couldn’t roll back transaction", rbe);
return false;
}
throw e;
} finally {
if (session != null) {
session.close();
}
}
}
Stacktrace
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.want.ecdlejb.dao.RegisterPcDao.registerPc(RegisterPcDao.java:22)
at com.want.ecdlejb.services.RegisterComputerService.registerPc(RegisterComputerService.java:40)
at com.want.ecdlwar.computers.RegisterComputer.register(RegisterComputer.java:15)
at com.want.ecdlwar.rest.Rest.registryPc(Rest.java:99)
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:497)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ecdl`.`computers`, CONSTRAINT `computers_ibfk_1` FOREIGN KEY (`pc_key`) REFERENCES `pc_keys` (`pc_key`))
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3249)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
Mapping
PcKeys
#OneToMany(mappedBy="pcKey")
private Set<Computer> computerses;
Computers
#ManyToOne
#JoinColumn(name="pc_key", nullable=false)
private PcKey pcKey;
isPcKeyExist
public PcKey isKeyExist(String pcKeyString) {
Session session = null;
Transaction tx = null;
try {
session = HibernateAnnotationUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
tx.setTimeout(5);
Criteria criteria = session.createCriteria(PcKey.class);
criteria.add(Restrictions.eqOrIsNull("pcKey", pcKeyString));
criteria.add(Restrictions.eqOrIsNull("pcKeyStatus",
ConstantsEjb.ACTIVE_STATUS));
PcKey pcKey = (PcKey) criteria.uniqueResult();
tx.commit();
return pcKey;
} catch (RuntimeException e) {
try {
tx.rollback();
} catch (RuntimeException rbe) {
// log.error("Couldn’t roll back transaction", rbe);
}
throw e;
} finally {
if (session != null) {
session.close();
}
}
Thanks

Related

connection java.sql.SQLNonTransientConnectionException: Could not create connection to database server

I am trying to add some bunch of records in MySQL database usign jdbc in java. This program works absolutely fine for 100 records. But after 100 records i get following error.
Exception occured while obtaining
connectionjava.sql.SQLNonTransientConnectionException: Could not create connection to database server.
java.lang.NullPointerException
at com.rest.EmployeeRest.insertDesigMySQLData(EmployeeRest.java:446)
at com.rest.EmployeeRest.syncDesignation(EmployeeRest.java:188)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
After google about this error, someone tell to use telnet command on localhost 3306(MySQL port). and it gives me "Too many connections" error.
Can anyone help me to solve this issue.
API code to get Data and add to MySQL:
ArrayList<Employee> arrDesig = getAllDesig();
setTotRecords(arrDesig.size());
System.out.println("Oracle TotRecords = "+getTotRecords());
if(arrDesig.size() > 0){
for(int iCnt=0; iCnt<arrDesig.size(); iCnt++){
if(insertDesigMySQLData(arrDesig.get(iCnt)) == 1){
mysqlDat++;
}
System.out.println("MySQL inserted data = "+mysqlDat);
}
if(getTotRecords() == mysqlDat){
retval = 1;
}else{
retval = 0;
}
}else{
retval = 0;
}
MySQL code to add:
int retval = 0;
OracleDataSource objMySQLDataSource = new OracleDataSource("mysql");
try{
Connection connection = objMySQLDataSource.getDbConnection();
CallableStatement pstmt=connection.prepareCall("{call addDesig(?,?,?)}");
pstmt.setString(1,objEmployee.getDesig_id());
System.out.println("getDesig_id() = "+objEmployee.getDesig_id());
pstmt.setString(2,objEmployee.getDesig_nm());
System.out.println("getDesig_nm() = "+objEmployee.getDesig_nm());
pstmt.registerOutParameter(3, Types.NUMERIC);
pstmt.executeUpdate();
retval = pstmt.getInt(3);
pstmt.close();
}catch (Exception e) {
retval = 0;
e.printStackTrace();
}finally{
objMySQLDataSource.connectionClose();
}
return retval;
Oracle Connection
OracleDataSource(){
setUrl("jdbc:oracle:thin:#dburl");
setDriver("oracle.jdbc.OracleDriver");
setUserName("admin");
setPassword("**********");
}
MySQL Connection
OracleDataSource(String mysql){
setUrl("jdbc:mysql://localhost:3306/academicdb?verifyServerCertificate=false&useSSL=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
setDriver("com.mysql.cj.jdbc.Driver");//com.mysql.jdbc.Driver
setUserName("root");
setPassword("");
}
public Connection getDbConnection() {
Connection con = null;
try{
Class.forName(getDriver());
con = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
} catch (Exception se) {
System.out.println("Exception occured while obtaining connection" + se.toString());
}
return con;
}

REST WS (in jersey) reading a JSON from android application

I have reading some questions over this tags, but I can't solve my problem
I have a RESTful Web Service using Jersey 1.X version (1.19 according to Maven repository) in which I try to read a JSON Object from an Android application. The problem is due to when I send a JSON whose fields has any character like:
á
é
í
ö...
I want to repeat I am able to read a JSON without these specials characters. I try adding charset=UTF-8 and setting headers but it doesn't work.
Apache console give this log
com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
GRAVE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22
at [Source: org.apache.catalina.connector.CoyoteInputStream#286c42cb; line: 1, column: 35]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2802)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2809)
at org.codehaus.jackson.impl.Utf8StreamParser._decodeUtf8_3fast(Utf8StreamParser.java:2632)
at org.codehaus.jackson.impl.Utf8StreamParser._finishString2(Utf8StreamParser.java:1950)
at org.codehaus.jackson.impl.Utf8StreamParser._finishString(Utf8StreamParser.java:1899)
at org.codehaus.jackson.impl.Utf8StreamParser.getText(Utf8StreamParser.java:276)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:26)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:13)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2695)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1308)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
ago 27, 2015 1:19:01 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: El Servlet.service() para el servlet [RESTWebServiceAndroid] en el contexto con ruta [/RESTWebServiceAndroid] lanzó la excepción [org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22
at [Source: org.apache.catalina.connector.CoyoteInputStream#286c42cb; line: 1, column: 35]] con causa raíz
org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22
at [Source: org.apache.catalina.connector.CoyoteInputStream#286c42cb; line: 1, column: 35]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1432)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2802)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2809)
at org.codehaus.jackson.impl.Utf8StreamParser._decodeUtf8_3fast(Utf8StreamParser.java:2632)
at org.codehaus.jackson.impl.Utf8StreamParser._finishString2(Utf8StreamParser.java:1950)
at org.codehaus.jackson.impl.Utf8StreamParser._finishString(Utf8StreamParser.java:1899)
at org.codehaus.jackson.impl.Utf8StreamParser.getText(Utf8StreamParser.java:276)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:26)
at org.codehaus.jackson.map.deser.std.StringDeserializer.deserialize(StringDeserializer.java:13)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2695)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1308)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
And android logcat says me
<html><head><title>Apache Tomcat/7.0.63 - Informe de Error</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>Estado HTTP 500 - org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22</h1><HR size="1" noshade="noshade"><p><b>type</b> Informe de Excepción</p><p><b>mensaje</b> <u>org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22</u></p><p><b>descripción</b> <u>El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.</u></p><p><b>excepción</b> <pre>javax.servlet.ServletException: org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x22
My Java Object in WS is:
public class UsuarioDB {
//Atributos del objeto Usuario, para cada usuario registrado en nuestra base de datos
String dni;
String nombre;
String apellidos;
String correo;
String movil;
String username;
String password;
//getters and setters (it hides this part to make this shortest)
}
Web service code
#Path("/ws")
public class PrincipalWS {
#POST
#Path("/newuser")
#Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response createUserInJSON1(UsuarioDB newuser){
System.out.println("Estoy en WS");
String result = "Usuario registrado : " + newuser;
System.out.println(result);
return Response.status(201).entity(result).header("Content-Type", "application/json;charset=UTF-8").build();
}
}
And Finally mi Android client
public boolean registraUsuario(String DNI, String nombre, String apellidos, String email, String movil, String username, String password){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://"+URL_conexion+"/rest/ws/newuser");
post.setHeader("content-type", "application/json");
try {
JSONObject jpost = new JSONObject();
jpost.put("dni", DNI);
jpost.put("nombre", nombre);
jpost.put("apellidos", apellidos);
jpost.put("correo", email);
jpost.put("movil", movil);
jpost.put("username", username);
jpost.put("password", password);
StringEntity entity = new StringEntity(jpost.toString());
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
HttpResponse resp = httpClient.execute(post);
resultado = EntityUtils.toString(resp.getEntity());
} catch (JSONException e) {
e.printStackTrace();
return false;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true; // no ha habido ningun error
}
I have a mess with this. Its driving me crazy.
I hope you can help me. Thanks!

Hibernate AssertionFailure: null id in entry (don't flush the Session after an exception occurs)

AM trying to perform some update operations in a catch block when an org.hibernate.exception.ConstraintViolationException is thrown as below
Am using Hibernate 4.3.6
try {
services.entity.saveInstance(secQuestions)
}
catch(Exception e) {
if(e instanceof org.hibernate.exception.ConstraintViolationException){
userRegistrationRequest.requestProcessed = true
infoMsg = userRegistrationRequest.infoMessage+' Exception: '+e.message
userRegistrationRequest.infoMessage = infoMsg
entityService.update(userRegistrationRequest)
logger.info("Caught BaseApplicationException "+e.message)
return;
}
Here is my UserRegistrationRequest entity
#Audited
#javax.persistence.Entity
class UserRegistrationRequest implements IAmGroovy, Serializable, IVersionable {
#Autowired
protected transient Services services;
protected answerOne;
protected answerTwo;
protected emailAddress;
protected firstName;
protected infoMessage;
protected lastName;
protected requestExpired;
protected requestProcessed;
SecurityQuestion securityQuestionOne;
SecurityQuestion securityQuestionTwo;
UserSecurityQuestions securityQuestions;
}
Here is my UserSecurityQuestions entity
#Entity
#Audited
public class UserSecurityQuestions implements IPersistentEntityInstance {
private Long id;
private User user;
private SecurityQuestion question1;
private SecurityQuestion question2;
private String answer1;
private String answer2;
private String hashString;
private Timestamp validThrough;
private int tries;
}
Am getting the below error when try to perform update in catch block
[Sep 17 11:48:14] ERROR | com.dc.core.common.controller.impl.BaseMultiActionController | null id in com.dc.apps.cp.security.model.UserSecurityQuestionsExt entry (don't flush the Session after an exception occurs) ERROR CODE(-1340973058)
org.hibernate.AssertionFailure: null id in com.dc.apps.cp.security.model.UserSecurityQuestionsExt entry (don't flush the Session after an exception occurs)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:77)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:192)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:152)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at com.dc.core.security.container.SecureSessionProxy.flush(SecureSessionProxy.java:306)
at com.dc.core.operations.service.impl.OperationService.performSingleOperation(OperationService.java:778)
at com.dc.core.presentation.presenter.impl.ScreenPresenter.performSingleOperation(ScreenPresenter.java:1187)
at com.dc.core.presentation.controller.springmvc.impl.ItemScreenRenderController.performOperation(ItemScreenRenderController.java:952)
at com.dc.core.presentation.controller.springmvc.impl.ItemScreenRenderController.performItemScreenOperation(ItemScreenRenderController.java:229)
at com.dc.core.presentation.controller.springmvc.impl.ItemScreenRenderController.performOperation(ItemScreenRenderController.java:433)
at sun.reflect.GeneratedMethodAccessor1397.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.dc.core.common.controller.impl.CustomMultiActionController.invokeNamedMethod(CustomMultiActionController.java:504)
at com.dc.core.common.controller.impl.CustomMultiActionController.handleRequestInternal(CustomMultiActionController.java:430)
at com.dc.core.common.controller.impl.BaseMultiActionController.handleRequestInternal(BaseMultiActionController.java:623)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:154)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
If I catch Exception instead of ConstraintViolationException am seeing the below error
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.dc.core.security.container.SecureSessionProxy.save(SecureSessionProxy.java:685)
at com.dc.core.common.dao.impl.GenericWriteDAO.create(GenericWriteDAO.java:37)
at com.dc.core.entity.dao.impl.EntityInstanceDAO.create(EntityInstanceDAO.java:63)
at com.dc.core.entity.service.impl.EntityService.create(EntityService.java:278)
at com.dc.core.api.EntityAPI.saveInstance(EntityAPI.java:188)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Violation of UNIQUE KEY constraint 'UQ__P_USER_S__B9BE370E29ACF837'. Cannot insert duplicate key in object 'dbo.P_USER_SECURITY_QUESTIONS'. The duplicate key value is (9).
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:314)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 162 more
Can someone help me, is there a better way to perform update operation in catch block?
You can try this:
Keep both the updates in different Transactions. If there is an exception in try, rollback the first Transaction in catch, clear the session and start a new Transaction to update in catch.
Transaction tx = null;
try {
tx = session.beginTransaction();
services.entity.saveInstance(secQuestions);
tx.commit();
}
catch(Exception e) {
tx.rollback();
session.clear();
if(e instanceof org.hibernate.exception.ConstraintViolationException){
Transaction tx1 = session.beginTransaction();
userRegistrationRequest.requestProcessed = true
infoMsg = userRegistrationRequest.infoMessage+' Exception: '+e.message
userRegistrationRequest.infoMessage = infoMsg
entityService.update(userRegistrationRequest);
tx1.commit();
logger.info("Caught BaseApplicationException "+e.message)
return;
}
}

mySql Column not found error occuring from servlet

I query a database to obtain all values from it.The query sometimes executes perfectly but at other times the query fails like this:
select * from myTable where objtype='EQUI' and scnrtype='C'
java.sql.SQLException: Column 'dataType' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1162)
at com.mysql.jdbc.ResultSetImpl.getCharacterStream(ResultSetImpl.java:2056)
at com.hastha.marerp.googlemaps.DBUtils.getScreenFields(DBUtils.java:672)
at com.hastha.marerp.googlemaps.DBUtils.getScreenFieldsJSON(DBUtils.java:754)
at com.hastha.marerp.googlemaps.DynamicMenuItemBuilder.doGet(DynamicMenuItemBuilder.java:67)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEondpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
The column dataType has char(8) as it's data type.
I have tried both rs.getString() and rs.getCharecterStream() where rs is the ResultSet obtained from this query.I think this has no effect on the problem because the error occurs before this line is even reached.
This is a description of myTable
This is my code:
public ArrayList<ScenarioFieldInfo> getScreenFields(String objType, String scenarioType)
{
System.out.println("Input args objType: "+objType+" and scenarioType: "+scenarioType);
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList<ScenarioFieldInfo> scenarioFieldList = new ArrayList<ScenarioFieldInfo>();
try {
String sql = "select * from myTable where objtype='"+objType+"' and scnrtype='"+scenarioType+"'";
System.out.println(sql);
pst = (PreparedStatement) conn.prepareStatement(sql.toString());
rs = pst.executeQuery();
while(rs.next()){
ScenarioFieldInfo fieldInfo = new ScenarioFieldInfo();
fieldInfo.fieldName = rs.getString("fieldName");
fieldInfo.fieldLabel = rs.getString("FieldLabel");
//fieldInfo.sapType=rs.getString("dataType");
BufferedReader reader=new BufferedReader(rs.getCharacterStream("dataType"));
try {
String sapType=reader.readLine();
fieldInfo.sapType=sapType;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fieldInfo.parameter=rs.getString("PARAMETER");
scenarioFieldList.add(fieldInfo);
}
System.out.println("There are "+scenarioFieldList.size()+" screen fields");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
close(rs);
close(pst);
}
return scenarioFieldList;
}
I found that the code was crashing because I had getCharecterStream instead of getString which was causing an error in my case.Modiying the code to:
rs.getString("dataType");
fixed the issue

SchemaExport don't create my tables in the database

I recently add the follow service class to my spring project, which has the function to create databse AND tables for the application use:
#Service
public class InstallService {
#Autowired
UsuarioHome usuario;
#Autowired
AutorizacaoHome autorizacao;
public boolean create_database(String maquina, String usuario, String senha) {
try {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/postgres?user="+usuario+"&password="+senha;
Connection conn = null;
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM pg_database";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
if(rs.getString("datname").equals("horario"))
return false;
}
sql = "CREATE DATABASE horario WITH OWNER = "+usuario+" ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'pt_BR.utf8' LC_CTYPE = 'pt_BR.utf8' CONNECTION LIMIT = -1;";
stmt.executeUpdate(sql);
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.getStackTrace();
} catch (ClassNotFoundException e) {
e.getStackTrace();
}
return create_tables(maquina, usuario, senha);
}
public boolean create_tables(String maquina, String usuario, String senha) {
Configuration config = new Configuration();
config.setProperty("jdbc.Classname", "org.postgresql.Driver");
config.setProperty("jdbc.url", "jdbc:postgresql://"+maquina+"/horario?charSet=LATIN1");
config.setProperty("jdbc.user", usuario);
config.setProperty("jdbc.pass", senha);
config.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
config.setProperty("hibernate.show_sql", "false");
config.setProperty("hibernate.hbm2ddl.auto", "create");
SchemaExport schema = new SchemaExport(config);
schema.create(true, true);
Properties properties = new Properties();
properties.setProperty("jdbc.Classname", "org.postgresql.Driver");
properties.setProperty("jdbc.url", "jdbc:postgresql://"+maquina+"/horario?charSet=LATIN1");
properties.setProperty("jdbc.user", usuario);
properties.setProperty("jdbc.pass", senha);
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.show_sql", "false");
properties.setProperty("hibernate.hbm2ddl.auto", "validate");
try {
File file = new File("database.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "propriedades");
fileOut.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return autorizacao.persist(new Autorizacao("permissao_teste"));
}
public boolean create_user(String login, String senha, String pnome, String unome) {
Usuario novo = new Usuario(login, senha, pnome, unome);
novo.setAutorizacao(autorizacao.findALL());
return usuario.persist(novo);
}
}
When I run the application, and the method create_database is called, this error happens:
ERROR: HHH000231: Schema export unsuccessful
java.lang.UnsupportedOperationException: The application must supply JDBC connections
at org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl.getConnection(UserSuppliedConnectionProviderImpl.java:62)
at org.hibernate.tool.hbm2ddl.ManagedProviderConnectionHelper.prepare(ManagedProviderConnectionHelper.java:55)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
at com.horariolivre.service.InstallService.create_tables(InstallService.java:71)
at com.horariolivre.service.InstallService.create_database(InstallService.java:57)
at com.horariolivre.controller.InstallController.createdb(InstallController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Mai 09, 2014 10:02:29 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Mai 09, 2014 10:02:29 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: null
Mai 09, 2014 10:02:29 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot create PoolableConnectionFactory (FATAL: database "horario" does not exist)
Mai 09, 2014 10:02:29 AM org.apache.catalina.core.StandardWrapperValve invoke
Grave: Servlet.service() for servlet [dispatcher] in context with path [/HorarioLivre2] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection] with root cause
org.postgresql.util.PSQLException: FATAL: database "horario" does not exist
at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:572)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:177)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc3g.Jdbc3gConnection.<init>(Jdbc3gConnection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:410)
at org.postgresql.Driver.connect(Driver.java:280)
at org.apache.tomcat.dbcp.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:549)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:428)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:417)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:255)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.horariolivre.dao.AutorizacaoHome$$EnhancerByCGLIB$$b21c029b.persist(<generated>)
at com.horariolivre.service.InstallService.create_tables(InstallService.java:93)
at com.horariolivre.service.InstallService.create_database(InstallService.java:57)
at com.horariolivre.controller.InstallController.createdb(InstallController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Anyone knows how to solve this?
UPDATE
My current code is that:
#Service
public class InstallService {
#Autowired
private UsuarioHome usuario;
#Autowired
private AutorizacaoHome autorizacao;
public boolean create_database(String maquina, String usuario, String senha) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("ClassNotFoundException");
}
try {
String url = "jdbc:postgresql://"+maquina+"/postgres";
System.out.println("url = "+url);
System.out.println("usuario = "+usuario);
System.out.println("senha = "+senha);
Connection conn = DriverManager.getConnection(url,usuario,senha);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM pg_catalog.pg_database WHERE datname = 'horario';");
rs.next();
int counter = rs.getInt(1);
System.out.println("counter = "+counter);
if(counter > 0) {
System.out.println("calling_create_tables");
create_tables(maquina, usuario, senha);
rs.close();
stmt.close();
conn.close();
return true;
}
int result = stmt.executeUpdate("CREATE DATABASE horario WITH OWNER "+usuario+";");
System.out.println("result = "+result);
if(result > 0) {
System.out.println("calling_create_tables");
create_tables(maquina, usuario, senha);
rs.close();
stmt.close();
conn.close();
return true;
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQLException");
return false;
}
System.out.println("retornando false");
return false;
}
public void create_tables(String maquina, String usuario, String senha) {
System.out.println("create_tables");
create_properties(maquina, usuario, senha);
Configuration config = new Configuration();
Properties props = new Properties();
FileInputStream fos;
try {
fos = new FileInputStream( "database.properties" );
props.load(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
config.setProperties(props);
try {
String url = props.getProperty("jdbc.url");
Connection conn = DriverManager.getConnection(url,usuario,senha);
SchemaExport schema = new SchemaExport(config, conn);
schema.create(true, true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
insert_default_values();
}
public void insert_default_values() {
System.out.println("insert_default_values");
String [] autorizacoes = {"cad_evento", "lista_evento", "cad_horario", "lista_horario", "cad_usuario", "lista_usuario", "cad_campo", "cad_tipo", "cad_permissao"};
for(int i=0; i<autorizacoes.length; i++) {
autorizacao.persist(new Autorizacao(autorizacoes[i]));
}
}
public void create_properties(String maquina, String usuario, String senha) {
System.out.println("create_properties");
Properties props = new Properties();
props.setProperty("jdbc.Classname", "org.postgresql.Driver");
props.setProperty("jdbc.url", "jdbc:postgresql://"+maquina+"/horario" );
props.setProperty("jdbc.user", usuario );
props.setProperty("jdbc.pass", senha );
props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.hbm2ddl.auto", "update");
FileOutputStream fos;
try {
fos = new FileOutputStream( "database.properties" );
props.store( fos, "propriedades" );
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean create_user(String login, String senha, String pnome, String unome) {
System.out.println("create_user");
Usuario novo = new Usuario(login, senha, pnome, unome);
if(usuario.persist(novo))
novo.setAutorizacao(autorizacao.findALL());
else
return false;
if(usuario.merge(novo) != null)
return true;
else
return false;
}
}
I don't receive any error when the method create_tables is executed, but none table is create in the database, causing an error when I try insert data in the tables.
Anyone can tell me what's wrong? I can't see nothing that right now.
#kleber mota it seems that the schema is created from the log file content org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete and i guess since there is no access or grants or privileges provided to that user hibernate could not connect. check using the postgres sql whether the schema is created as a root/admin.
Ok, I finally acomplish my objective, and now both database and tables are being created. The final code for the method create_table(0 is:
public void create_tables(String maquina, String usuario, String senha) {
System.out.println("create_tables");
create_properties(maquina, usuario, senha);
Configuration config = new Configuration();
Properties props = new Properties();
FileInputStream fos;
try {
fos = new FileInputStream( "database.properties" );
props.load(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
config.setProperties(props);
config.addAnnotatedClass(com.horariolivre.entity.Atributo.class);
config.addAnnotatedClass(com.horariolivre.entity.ConfigHorarioLivre.class);
config.addAnnotatedClass(com.horariolivre.entity.Evento.class);
config.addAnnotatedClass(com.horariolivre.entity.HorarioLivre.class);
config.addAnnotatedClass(com.horariolivre.entity.Key.class);
config.addAnnotatedClass(com.horariolivre.entity.Tipo.class);
config.addAnnotatedClass(com.horariolivre.entity.Value.class);
config.addAnnotatedClass(com.horariolivre.entity.Autorizacao.class);
config.addAnnotatedClass(com.horariolivre.entity.Usuario.class);
try {
String url = props.getProperty("jdbc.url");
Connection conn = DriverManager.getConnection(url,usuario,senha);
SchemaExport schema = new SchemaExport(config, conn);
schema.create(true, true);
} catch (SQLException e) {
e.printStackTrace();
}
insert_default_values();
}
Basicly, I include in the method a group of lines with the instruction:
config.addAnnotatedClass(com.horariolivre.entity.Atributo.class);
where I tell to program what entity classes should be created in the database. That do the job.

Categories