Problem to add new User Spring-Boot / Postman - postgresql

Can you help me? I have a problem adding a new client to my database.
I have three classes: User, Role, Center
my user class contains:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String login;
private String password;
private String nom;
private String prenom;
private String telephone;
private String email;
private long idCCMS;
private String matricule;
#ManyToOne
#JoinColumn(name = "Code_Role")
private Role role;
#ManyToOne
#JoinColumn(name = "Code_Centre")
private Centre centre;
my method:
#PostMapping(value = "/add")
public Utilisateur save(#RequestBody Utilisateur user) {
return userRepo.save(user);
}
How I can affect the addition of a new user by assigning him a role and a center.
I tried this solution with postman :
{
"login": "med",
"password": "123456789",
"nom": "AOUIDIDI",
"prenom": "MOHAMED WALID",
"telephone": "(+222) 22-222-222",
"email": "aaa#aaa.com",
"idccms": 08318915,
"matricule": "431908",
"code_role":"3",
"code_centre":"3"
}
I got this result:
"timestamp": "2020-02-06T13:15:41.496+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Invalid numeric value: Leading zeroes not allowed; nested exception is com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed\n at [Source: (PushbackInputStream); line: 8, column: 16]",
"trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid numeric value: Leading zeroes not allowed; nested exception is com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed\n at [Source: (PushbackInputStream); line: 8, column: 16]\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:245)\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:205)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Unknown Source)\r\nCaused by: com.fasterxml.jackson.core.JsonParseException: Invalid numeric value: Leading zeroes not allowed\n at [Source: (PushbackInputStream); line: 8, column: 16]\r\n\tat com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1840)\r\n\tat com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:712)\r\n\tat com.fasterxml.jackson.core.base.ParserMinimalBase.reportInvalidNumber(ParserMinimalBase.java:551)\r\n\tat com.fasterxml.jackson.core.json.UTF8StreamJsonParser._verifyNoLeadingZeroes(UTF8StreamJsonParser.java:1519)\r\n\tat com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parsePosNumber(UTF8StreamJsonParser.java:1371)\r\n\tat com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextFieldName(UTF8StreamJsonParser.java:1055)\r\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:376)\r\n\tat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)\r\n\tat com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)\r\n\tat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3258)\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239)\r\n\t... 51 more\r\n",
"path": "/utilisateurs/add"
}
can you help me solve this problem please ?

As your response says:
...line: 8, column: 16 ... Invalid numeric value: Leading zeroes not allowed
"idccms": 08318915 can not be parsed to private long idCCMS;
Either get rid of the 0 in the beginning or make idCCMS a type of String and everything will be just fine.

Related

DB2 not accepting UUID

I am using UUID datatype for generating alpha numeric primary key. Following is the code:
public class Example {
private UUID id;
#Id
#Column(name = "ID", nullable = false, length = 36)
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
}
The Java code is generating the uuid something like - c70e22b4-d2a8-11ea-87d0-0242ac130003.
But on saving the values in a DB2 table, in UUID column(which is of VARCHAR(25) type in DB2), I am getting values as in table as:
<failed to load>
com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][4.23.42] Caught java.io.CharConversionException. See attached Throwable for details. ERRORCODE=-4220, SQLSTATE=null
at com.ibm.db2.jcc.am.ld.a(ld.java:794)
at com.ibm.db2.jcc.am.ld.a(ld.java:66)
at com.ibm.db2.jcc.am.ld.a(ld.java:125)
at com.ibm.db2.jcc.am.mc.a(mc.java:2963)
at com.ibm.db2.jcc.am.mc.p(mc.java:575)
at com.ibm.db2.jcc.am.mc.P(mc.java:1656)
at com.ibm.db2.jcc.am.ResultSet.getStringX(ResultSet.java:1223)
at com.ibm.db2.jcc.am.ResultSet.getString(ResultSet.java:1192)
at com.intellij.database.remote.jdbc.impl.RemoteResultSetImpl.tryGetObject(RemoteResultSetImpl.java:1289)
at com.intellij.database.remote.jdbc.impl.RemoteResultSetImpl.getObject(RemoteResultSetImpl.java:1272)
at com.intellij.database.remote.jdbc.impl.RemoteResultSetImpl.getCurrentRow(RemoteResultSetImpl.java:1249)
at com.intellij.database.remote.jdbc.impl.RemoteResultSetImpl.getObjects(RemoteResultSetImpl.java:1229)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at com.ibm.db2.jcc.am.r.a(r.java:52)
at com.ibm.db2.jcc.am.mc.a(mc.java:2952)
... 25 more
Looks like I can not map UUID to Varchar, but not able to find the alternative.
Any help would be appreciated.
Not sure where you got a length of 25 from....
c70e22b4-d2a8-11ea-87d0-0242ac130003 is 36 characters...
if you want to store the binary value, you only need 16 bytes, but they must for CHAR(16) FOR BIT DATA
You can convert text UUID stings in Db2 to binary with the [VARCHAR_BIT_FORMAT][1] function
CREATE TABLE UUID(U BINARY(16) NOT NULL PRIMARY KEY)
;
INSERT INTO UUID
VALUES VARCHAR_BIT_FORMAT(
'c70e22b4-d2a8-11ea-87d0-0242ac130003'
, 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
)

Format Date in response of POST rest API

I create a POST API in spring boot + kotlin. I create a LocalDate object but response is something not desired. I have used
org.springframework.format.annotation.DateTimeFormat
What I get is something like:
<user>
<email>a#mail.com</email>
<lname></lname>
<fname></fname>
<birthday>
<year>2000</year>
<month>JANUARY</month>
<chronology>
<id>ISO</id>
<calendarType>iso8601</calendarType>
</chronology>
<dayOfMonth>1</dayOfMonth>
<dayOfWeek>SATURDAY</dayOfWeek>
<era>CE</era>
<dayOfYear>1</dayOfYear>
<leapYear>true</leapYear>
<monthValue>1</monthValue>
</birthday>
</user>
What I want is something like (specifically birthDay tag):
<user>
<email>a#mail.com</email>
<lname></lname>
<fname></fname>
<birthday>2000-01-01</birthday>
</user>
Here is the code:
dto class:
import org.springframework.format.annotation.DateTimeFormat
import java.time.LocalDate
#JacksonXmlRootElement
data class User (var email: String? = "",
var lname: String = "",
var fname: String = "",
#DateTimeFormat(pattern = "yyyy-MM-dd")
var birthday: LocalDate? = null)
controller class:
#RestController
#RequestMapping("/")
class Controller {
#PostMapping("/post")
fun registerByMail(#Valid body: User) : ResponseEntity<Any> {
.
.
.
var user = User(birthDay = body.birthDay)
return ResponseEntity.ok(user)
Please let me know where I doing wrong. I am making POST request using postman.
Edit : I have also tried solution mentioned here : JSON Java 8 LocalDateTime format in Spring Boot but that also doesn't worked for me.
When I use com.fasterxml.jackson.annotation.JsonFormat annotation and required dependency, I got following error:
<defaultMessage>Failed to convert value of type 'java.lang.String[]' to
required type 'java.time.LocalDate'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type
[#com.fasterxml.jackson.annotation.JsonFormat java.time.LocalDate] for value
'2000-01-01'; nested exception is java.lang.IllegalArgumentException: Parse
attempt failed for value [2000-01-01]</defaultMessage>
You have to annotate the field #field:JsonSerialize and not the property.
Beside this you have to use #JsonFormat
#JacksonXmlRootElement
data class User(
var email: String? = "",
var lname: String = "",
var fname: String = "",
#field:JsonFormat(pattern = "yyyy-MM-dd")
#field:JsonSerialize(using = LocalDateSerializer::class)
#field:JsonDeserialize(using = LocalDateDeserializer::class)
var birthday: LocalDate? = null
)
My small test:
val mapper = XmlMapper()
val xml = mapper.writeValueAsString(User(birthday = LocalDate.now()))
println(xml)
Generates the following output:
<User><email></email><lname></lname><fname></fname><birthday>2018-10-19</birthday></User>

primary key ID gives me repeated " 0 " value with android app

I try to make contactsApp with android , when I debug it the primary key repeat its value which is zero
AND HERE IS THE SQLiteOpenHelper class :
// get all Contacts
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
at first the error was NonNullException at this line
contact.setId(Integer.parseInt(cursor.getString(0)));
so I surround it with try catch then the app debug correctly but still gives wrong value for the INTEGER PRIMARY KEY id
the final result should be like
ID: 1, Name 1 , 111111111
ID: 2, Name 2 , 22222222
ID: 3, Name 3 , 33333333
ID: 4, Name 4 , 444444444
But I get this result..
ID: 0, Name 1 , 111111111
ID: 0, Name 2 , 22222222
ID: 0, Name 3 , 33333333
ID: 0, Name 4 , 444444444
after some searches I did not find any solution for that!
So what should I do to fix it ??
Thanks in advance!
EDIT
The stack-trace :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muhamad_galal.databaseintro, PID: 3947
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.muhamad_galal.databaseintro/com.example.muhamad_galal.databaseintro.MainActivity}: java.lang.NumberFormatException: Invalid int: "null"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: "null"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at Data.DataBaseHandler$override.getAllContact(DataBaseHandler.java:141)
at Data.DataBaseHandler$override.access$dispatch(DataBaseHandler.java)
at Data.DataBaseHandler.getAllContact(DataBaseHandler.java)
at com.example.muhamad_galal.databaseintro.MainActivity$override.onCreate(MainActivity.java:29)
at com.example.muhamad_galal.databaseintro.MainActivity$override.access$dispatch(MainActivity.java)
at com.example.muhamad_galal.databaseintro.MainActivity.onCreate(MainActivity.java)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077) 
at android.app.ActivityThread.-wrap15(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What the message is saying is that you've passed a null to the Integer's parseInt method. as per :-
Caused by: java.lang.NumberFormatException: Invalid int: "null"
Thus it appears that the first column of the table has nulls.
At a guess you have not defined the column to be an alias of rowid and thus the column hasn't been given a unique integer value.
To be an alias of rowid it must be defined as INTEGER PRIMARY KEY or INTEGER PRIMARY KEY AUTOINCREMENT (the latter is not recommended).
If you changed :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
// HERE is where the error come...
try{
if (cursor.getString(0) != null)
contact.setId(Integer.parseInt(cursor.getString(0)));
}catch (Exception e){e.printStackTrace();}
contact.setName(cursor.getString(1) );
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
to (see the comments at the end of lines that start with //<<<<) :-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT rowid,* FROM " + Util.TABLE_NAME; //<<<< CHANGED
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0)); //<<<< CHANGED to use getInt
contact.setName(cursor.getString(2)); //<<<< CHANGED to skip first column
contact.setPhoneNumber(cursor.getString(3)); //<<<< CHANGED to skip first column
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
Then I suspect that you would get the expected results.
This gets the normally hidden actual rowid column as well as all the other columns; so there is an extra column at the start.
Note this assumes that you haven't defined the table using WITHOUT ROWID
Really you should consider the id/rowid as a long but int will work as long as there aren't too many rows.
However, this should only be a temporary fix.
The full/permanent fix should be
Code the first column so that it is defined as an alias of rowid e.g. using CREATE TABLE you_table_name (ID INTEGER PRIMARY KEY, the_other_columns...... (this assumes that the column name is ID).
Delete the database by either uninstalling the App or by deleting the App's data.
This assumes that you do not require the current data.
Change the contact class so that the Id member is long not int.
Change the getters and setters in the contact class (setId and I assume getId) so that the methods use long rather than int
Change any other uses of the Id member of the contact class to use long.
Change the getAllContact method to be
:-
public List<Contact> getAllContact(){
SQLiteDatabase db = this.getReadableDatabase();
List<Contact> contactList = new ArrayList<>();
String selectAll = "SELECT * FROM " + Util.TABLE_NAME;
Cursor cursor = db.rawQuery(selectAll , null);
if (cursor.moveToFirst()){
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while (cursor.moveToNext());
}
return contactList;
}
delete the App's Data or uninstall the App.
rerun the App

Comparing dates in jpa

I am trying to find results in a postgresql database between two dates (field described in ddbb as timestamp).
I have these three records which must meet target:
2016-03-04 00:00:00
2016-03-04 14:00:00
2016-03-04 10:56:00
final Calendar fechaMinima = Calendar.getInstance();
and set the parameters I want.
the jpa column is defined:
#Column(name = "tim_ofrecim")
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(style = "M-")
private Date Tewslofr.timOfrecim;
With JPA I try to find them with the following code:
#NamedQuery(name = "ofr_query2", query = "SELECT COUNT (*) FROM Tewslofr ofr "
+ "WHERE ofr.id.codIdprodto =:codIdprodto "
+ "AND ofr.codUser =:codUser "
+ "AND ofr.timOfrecim BETWEEN :timMinimo AND :timMaximo")
public static Long getMethod(final String codProducto,
final String codUser, final Calendar fechaMinima,
final Calendar fechaMaxima) {
return entityManager().createNamedQuery("ofr_query2", Long.class)
.setParameter("codIdprodto", codProducto)
.setParameter("codUser", codUser)
.setParameter("timMinimo", fechaMinima, TemporalType.TIMESTAMP)
.setParameter("timMaximo", fechaMaxima, TemporalType.TIMESTAMP)
.getSingleResult();
}
and obtain this exception:
Caused by: java.lang.IllegalArgumentException: Parameter value [java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=1,DAY_OF_YEAR=67,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=8,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=434,ZONE_OFFSET=3600000,DST_OFFSET=0]] was not matching type [java.util.Date]
The stack trace to this is:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=1,DAY_OF_YEAR=67,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=9,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=170,ZONE_OFFSET=3600000,DST_OFFSET=0]] was not matching type [java.util.Date]; nested exception is java.lang.IllegalArgumentException: Parameter value [java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=1,DAY_OF_YEAR=67,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=9,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=170,ZONE_OFFSET=3600000,DST_OFFSET=0]] was not matching type [java.util.Date]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:301)
at org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect.ajc$afterThrowing$org_springframework_orm_jpa_aspectj_JpaExceptionTranslatorAspect$1$18a1ac9(JpaExceptionTranslatorAspect.aj:15)
at com.bbva.arq.front.spring.ewsl.ofrecimientos.api.v1.domain.Tewslofr.getCuentaOfrecimientosAgente_aroundBody2(Tewslofr.java:49)
at com.bbva.arq.front.spring.ewsl.ofrecimientos.api.v1.domain.Tewslofr.getCuentaOfrecimientosAgente(Tewslofr.java:1)
at com.bbva.arq.front.spring.ewsl.ofrecimientos.api.v1.daos.ofrecimientos.impl.OfrecimientosDAOImpl.getMethod(OfrecimientosDAOImpl.java:52)...
Caused by: java.lang.IllegalArgumentException: Parameter value [java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=2,WEEK_OF_YEAR=10,WEEK_OF_MONTH=2,DAY_OF_MONTH=1,DAY_OF_YEAR=67,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=9,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=170,ZONE_OFFSET=3600000,DST_OFFSET=0]] was not matching type [java.util.Date]
at org.hibernate.ejb.AbstractQueryImpl.registerParameterBinding(AbstractQueryImpl.java:360)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:414)
If I change to DATE instead of TIMESTAMP:
public static Long getMethod(final String codProducto,
final String codUser, final Calendar fechaMinima,
final Calendar fechaMaxima) {
return entityManager().createNamedQuery("ofr_query2", Long.class)
.setParameter("codIdprodto", codProducto)
.setParameter("codUser", codUser)
.setParameter("timMinimo", fechaMinima.getTime(), TemporalType.DATE)
.setParameter("timMaximo", fechaMaxima.getTime(), TemporalType.DATE)
.getSingleResult();
}
the code returns 0.
Any help will be appreciated.
kindest regards
I still don't know why the first option does not work, but I have made it work with the option of Date. This option was correct but was returning 0 because of de codIdprodto, not because of the dates.

How to encrypt password while saving Users in Liferay 6.1?

I am trying to consume Liferay's User entity to add users by writing code. The password is not encrypting, so log in is failing. The code is pasting below.
int countOfUsr = UserLocalServiceUtil.getUsersCount();
User user = UserLocalServiceUtil.createUser(countOfUsr + 1);
Date date = new Date();
user.setCompanyId(countOfUsr + 1);
user.setCreateDate(date);
user.setModifiedDate(date);
user.setDefaultUser(false);
user.setContactId(countOfUsr + 1);
user.setPasswordEncrypted(true);
user.setAgreedToTermsOfUse(true);
user.setPassword("123");
user.setPasswordReset(false);
user.setPasswordModifiedDate(date);
user.setReminderQueryQuestion("what-is-your-father's-middle-name");
user.setReminderQueryAnswer("daddad");
user.setGraceLoginCount(0);
user.setScreenName("shibu");
user.setFirstName("SHIBU");
user.setEmailAddress("shibu#liferay.com");
user.setFacebookId(0);
user.setOpenId("");
user.setPortraitId(0);
user.setLanguageId("en_US");
user.setTimeZoneId("GMT");
UserLocalServiceUtil.addUser(user);
How to modify the code to save the user properly?
What to do for pssword encryption?
How to give value for user.setDigest(arg)?
Specify the encryption algorithm to encrypt passwords in portal-ext.properties file.
For eg.,
passwords.encryption.algorithm=SHA //Check out different algorithms in portal.properties
I think you should use UserLocalServiceUtil.addUser(whole bunch of arguments) instead of UserLocalServiceUtil.addUser(User).
It will do what you want : create your user and encrypt the password.
The method signature is :
public User addUser(
long creatorUserId, long companyId, boolean autoPassword,
String password1, String password2, boolean autoScreenName,
String screenName, String emailAddress, long facebookId,
String openId, Locale locale, String firstName, String middleName,
String lastName, int prefixId, int suffixId, boolean male,
int birthdayMonth, int birthdayDay, int birthdayYear,
String jobTitle, long[] groupIds, long[] organizationIds,
long[] roleIds, long[] userGroupIds, boolean sendEmail,
ServiceContext serviceContext)
throws PortalException, SystemException
Beware : if your password do not validate the password policie, it will throw a UserPasswordException