POST data with retrofit2, Bearer token Unauthorized android - java

I want to post new data to server with this JSON:
{
"tgl_Lahir": "1990-12-18 00:00:00",
"nama": "Joe",
"keterangan": "Employee",
"tempatLahir": "Los Angeles",
"noPegawai": "111111",
"golDarah": "0",
"statusNikah": "0",
"hubungans": {
"id": "10"
},
"agama": {
"id_Agama": "1"
},
"jeniskelamin": {
"jenisKelamin": "1"
}
}
Here's my ApiClientPOST.java:
public class ApiClientPOST {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Here's my APIUtils.java:
public class APIUtils {
private APIUtils(){
};
public static final String API_URL = "IPAddress/employee/family/add";
public static MainInterface getUserService(){
return ApiClientPOST.getClient(API_URL).create(MainInterface.class);
}
}
Here's my familylistresponsePOST.java:
public class familylistresponsePOST {
#SerializedName("noPegawai")
private String noPegawai;
#SerializedName("date_otor")
private Object dateOtor;
#SerializedName("jeniskelamin")
private Jeniskelamin jeniskelamin;
#SerializedName("keterangan")
private String keterangan;
#SerializedName("hubungans")
private Hubungans hubungans;
#SerializedName("tgl_Lahir")
private String tglLahir;
#SerializedName("nama")
private String nama;
#SerializedName("agama")
private Agama agama;
#SerializedName("statusNikah")
private String statusNikah;
#SerializedName("tempatLahir")
private String tempatLahir;
#SerializedName("id")
private int id;
#SerializedName("golDarah")
private String golDarah;
public void setNoPegawai(String noPegawai){
this.noPegawai = noPegawai;
}
public String getNoPegawai(){
return noPegawai;
}
public void setDateOtor(Object dateOtor){
this.dateOtor = dateOtor;
}
public Object getDateOtor(){
return dateOtor;
}
public void setJeniskelamin(Jeniskelamin jeniskelamin){
this.jeniskelamin = jeniskelamin;
}
public Jeniskelamin getJeniskelamin(){
return jeniskelamin;
}
public void setKeterangan(String keterangan){
this.keterangan = keterangan;
}
public String getKeterangan(){
return keterangan;
}
public void setHubungans(Hubungans hubungans){
this.hubungans = hubungans;
}
public Hubungans getHubungans(){
return hubungans;
}
public void setTglLahir(String tglLahir){
this.tglLahir = tglLahir;
}
public String getTglLahir(){
return tglLahir;
}
public void setNama(String nama){
this.nama = nama;
}
public String getNama(){
return nama;
}
public void setAgama(Agama agama){
this.agama = agama;
}
public Agama getAgama(){
return agama;
}
public void setStatusNikah(String statusNikah){
this.statusNikah = statusNikah;
}
public String getStatusNikah(){
return statusNikah;
}
public void setTempatLahir(String tempatLahir){
this.tempatLahir = tempatLahir;
}
public String getTempatLahir(){
return tempatLahir;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setGolDarah(String golDarah){
this.golDarah = golDarah;
}
public String getGolDarah(){
return golDarah;
}
#Override
public String toString(){
return
"ListUserResponse2{" +
"noPegawai = '" + noPegawai + '\'' +
",date_otor = '" + dateOtor + '\'' +
",jeniskelamin = '" + jeniskelamin + '\'' +
",keterangan = '" + keterangan + '\'' +
",hubungans = '" + hubungans + '\'' +
",tgl_Lahir = '" + tglLahir + '\'' +
",nama = '" + nama + '\'' +
",agama = '" + agama + '\'' +
",statusNikah = '" + statusNikah + '\'' +
",tempatLahir = '" + tempatLahir + '\'' +
",id = '" + id + '\'' +
",golDarah = '" + golDarah + '\'' +
"}";
}
}
I've tried to create this method and use it on my Button.setOnClickListener:
public void addFamily(String noPegawai,String agama, String hubungan, String jenisKelamins, String tgl_Lahir, String nama, String keterangan, String tempatLahir, String golDarah, String statusNikah){
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String tokens = preferences.getString("userToken",null);
Call<familylistresponse> call = apiService.addFams(noPegawai,agama, hubungan, jenisKelamins, tgl_Lahir , nama, keterangan, tempatLahir, golDarah, statusNikah, "Bearer" + tokens);
call.enqueue(new Callback<familylistresponse>() {
#Override
public void onResponse(Call<familylistresponse> call, Response<familylistresponse> response) {
// if (response.isSuccessful()){
familylistresponse resultsData = new familylistresponse();
resultsData= response.body();
Toast.makeText(TambahDataKeluarga.this,"Data Berhasil Ditambahkan!" + resultsData, Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onFailure(Call<familylistresponse> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
This one is my tambah Button:
tambah.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String noPegawai = preferences.getString("noPegawai",null);
String snopeg = etNoPegawai.getText().toString().trim();
String snama = etNama.getText().toString().trim();
String stmpLahir = etTmptLahir.getText().toString().trim();
String stglLahir = etTglLahir.getText().toString().trim();
String sketerangan = etKeterangan.getText().toString().trim();
String sgoldar = etGoldar.getText().toString().trim();
String sstatusnikah = etStatusNikah.getText().toString().trim();
valueJenisKelamin = jeniskelamin.getSelectedItem().toString();
valueHubungan = spHubungans.getSelectedItem().toString();
valueAgama = spAgama.getSelectedItem().toString();
familylistresponse f = new familylistresponse();
f.setNoPegawai(snopeg);
agamas.setAgama(spAgama.getSelectedItem().toString().trim());
jks.setJenisKelamin(jeniskelamin.getSelectedItem().toString().trim());
hubungans.setHubungan(spHubungans.getSelectedItem().toString().trim());
addFamily(snopeg, valueAgama, valueHubungan, valueJenisKelamin, stglLahir, snama, sketerangan, stmpLahir, sgoldar, sstatusnikah);
Log.d(f.getNama(),f.getGolDarah());
Toast.makeText(TambahDataKeluarga.this,"No pegawai "+ noPegawai + " Nama Pegawai "+ snama+ " Tgl Lahir "+ stglLahir
+ " Agama " + valueAgama
+ " Hubungan " + valueHubungan
+ " Jenis Kelamin " + valueJenisKelamin
+ " Tgl Lahir " + stglLahir
+ " Keterangan " + sketerangan
+ " Tempat Lahir " + stmpLahir
+ " Goldar " + sgoldar
+ " Status Nikah " + sstatusnikah,Toast.LENGTH_LONG).show();
});
The toast says that the data is successfully stored but in fact, it isn't. The toast also says that response.body() is null and there is no error in logcat even in the debugger. Please kindly help me. Thanks in advance for any help

I do not see where you are defining Hubungans, Agama and Jeniskelamin classes although you are using it as datatype inside your familylistresponsePOST.java
After creating these three classes, I hope your issue will be solved.

Related

OpenCSV with Java spring boot can't read values of first column

I am trying to read values from csv file with Java spring boot with dependency of opencsv. But the values of first column are not geting readed while other columns are fine. It returns them as null.
Reader reader = Files.newBufferedReader(Paths.get(path));
CsvToBean<CsvBikeTrips> csvToBean = new CsvToBeanBuilder(reader)
.withType(CsvBikeTrips.class)
.withIgnoreLeadingWhiteSpace(false)
.build();
List<CsvBikeTrips> csvBikeTrips = csvToBean.parse();
public class CsvBikeTrips {
#CsvBindByName(column = "Departure")
private String departureTimestamp;
#CsvBindByName(column = "Return")
private String returnTimestamp;
#CsvBindByName(column = "Departure station id")
private String departureStationId;
#CsvBindByName(column = "Return station id")
private String returnStationId;
#CsvBindByName(column = "Departure station name")
private String departureStationName;
#CsvBindByName(column = "Return station name")
private String returnStationName;
#CsvBindByName(column = "Covered distance (m)")
private String coveredDistance;
#CsvBindByName(column = "Duration (sec.)")
private String duration;
public String getDepartureTimestamp() {
return departureTimestamp;
}
public void setDepartureTimestamp(String departureTimestamp) {
this.departureTimestamp = departureTimestamp;
}
public String getReturnTimestamp() {
return returnTimestamp;
}
public void setReturnTimestamp(String returnTimestamp) {
this.returnTimestamp = returnTimestamp;
}
public String getDepartureStationId() {
return departureStationId;
}
public void setDepartureStationId(String departureStationId) {
this.departureStationId = departureStationId;
}
public String getReturnStationId() {
return returnStationId;
}
public void setReturnStationId(String returnStationId) {
this.returnStationId = returnStationId;
}
public String getDepartureStationName() {
return departureStationName;
}
public void setDepartureStationName(String departureStationName) {
this.departureStationName = departureStationName;
}
public String getReturnStationName() {
return returnStationName;
}
public void setReturnStationName(String returnStationName) {
this.returnStationName = returnStationName;
}
public String getCoveredDistance() {
return coveredDistance;
}
public void setCoveredDistance(String coveredDistance) {
this.coveredDistance = coveredDistance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
#Override
public String toString() {
return "CsvBikeTrips{" +
"departureTimestamp='" + departureTimestamp + '\'' +
", returnTimestamp='" + returnTimestamp + '\'' +
", departureStationId='" + departureStationId + '\'' +
", returnStationId='" + returnStationId + '\'' +
", departureStationName='" + departureStationName + '\'' +
", returnStationName='" + returnStationName + '\'' +
", coveredDistance='" + coveredDistance + '\'' +
", duration='" + duration + '\'' +
'}';
}
}
And the row of csv files look like this:
Departure,Return,Departure station id,Departure station name,Return station id,Return station name,Covered distance (m),Duration (sec.)
2021-05-31T23:57:25,2021-06-01T00:05:46,094,Laajalahden aukio,100,Teljäntie,2043,500
2021-05-31T23:56:59,2021-06-01T00:07:14,082,Töölöntulli,113,Pasilan asema,1870,611
Ive tried something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(path), "UTF-8"));
And also to save the file in different txt editors but no success.
It happens that the file, in the beginning, had something like : ZWNBSP
Intelli J editor couldn't see that easily. It seems that it is related to BOM.
Unicode of that is \uFEFF
Fix:
InputStream input = new FileInputStream(path);
Reader reader = new InputStreamReader(new BOMInputStream(input), StandardCharsets.UTF_8);

Gson to parse string of arrays

I need to parse the below JSON content. Currently I have stored it inflat file and reading it. I have given the sample POJO classes which are created and the code which I tried below.
Tried two different approach and both are giving the following error
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $
Json file
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
POJO classes:
Note: I have mentioned only two classes here.
package com.As.jsonmodel.configrequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class ConfigurationRequest
{
private DeviceList[] DeviceList;
private DeviceCommon DeviceCommon;
public DeviceList[] getDeviceList ()
{
return DeviceList;
}
public void setDeviceList (DeviceList[] DeviceList)
{
this.DeviceList = DeviceList;
}
public DeviceCommon getDeviceCommon ()
{
return DeviceCommon;
}
public void setDeviceCommon (DeviceCommon DeviceCommon)
{
this.DeviceCommon = DeviceCommon;
}
#Override
public String toString()
{
return "ClassPojo [DeviceList = "+DeviceList+", DeviceCommon = "+DeviceCommon+"]";
}
}
package com.As.jsonmodel.configrequest;
public class DeviceList
{
private MobileOriginatorCallbackReference MobileOriginatorCallbackReference;
private String NIDDduration;
private String ASreferenceID;
private String senderName;
private String ExternalIdentifer;
private String msisdn;
private ConfigurationResultCallbackReference ConfigurationResultCallbackReference;
public MobileOriginatorCallbackReference getMobileOriginatorCallbackReference ()
{
return MobileOriginatorCallbackReference;
}
public void setMobileOriginatorCallbackReference (MobileOriginatorCallbackReference MobileOriginatorCallbackReference)
{
this.MobileOriginatorCallbackReference = MobileOriginatorCallbackReference;
}
public String getNIDDduration ()
{
return NIDDduration;
}
public void setNIDDduration (String NIDDduration)
{
this.NIDDduration = NIDDduration;
}
public String getASreferenceID ()
{
return ASreferenceID;
}
public void setASreferenceID (String ASreferenceID)
{
this.ASreferenceID = ASreferenceID;
}
public String getSenderName ()
{
return senderName;
}
public void setSenderName (String senderName)
{
this.senderName = senderName;
}
public String getExternalIdentifer ()
{
return ExternalIdentifer;
}
public void setExternalIdentifer (String ExternalIdentifer)
{
this.ExternalIdentifer = ExternalIdentifer;
}
public String getMsisdn ()
{
return msisdn;
}
public void setMsisdn (String msisdn)
{
this.msisdn = msisdn;
}
public ConfigurationResultCallbackReference getConfigurationResultCallbackReference ()
{
return ConfigurationResultCallbackReference;
}
public void setConfigurationResultCallbackReference (ConfigurationResultCallbackReference ConfigurationResultCallbackReference)
{
this.ConfigurationResultCallbackReference = ConfigurationResultCallbackReference;
}
#Override
public String toString()
{
return "ClassPojo [MobileOriginatorCallbackReference = "+MobileOriginatorCallbackReference+", NIDD duration = "+NIDDduration+", AS referenceID = "+ASreferenceID+", senderName = "+senderName+", ExternalIdentifer = "+ExternalIdentifer+", msisdn = "+msisdn+", ConfigurationResultCallbackReference = "+ConfigurationResultCallbackReference+"]";
}
}
Json Reader
Approach1:
BufferedReader br = null;
try {
br = new BufferedReader(
new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonReader jsonReader = new JsonReader(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("DeviceCommon")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("ASIdentifier")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("MobileOriginatorCallbackReference")){
System.out.println(jsonReader.nextString());
}
if (n.equals("AccessiblityCallbackReference")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("DeviceList")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
// TODO Auto-generated method stub
Aproach2:
Gson gson = new Gson();
DeviceList [] myTypes = gson.fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), DeviceList[].class);
System.out.println(gson.toJson(myTypes));
Any pointers on how to parse this file will be helpful.
Here's how to do it with Gson:
import java.io.FileReader;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class Main {
public static void main(String[] args) throws Exception {
Data data = new Gson().fromJson(new FileReader("data.json"), Data.class);
System.out.println(data);
}
}
class Data {
#SerializedName("DeviceCommon")
DeviceCommon deviceCommon;
#SerializedName("DeviceList")
DeviceListEntry[] deviceList;
#Override
public String toString() {
return "Data{" +
"\n deviceCommon=" + deviceCommon +
"\n deviceList=" + Arrays.toString(deviceList) +
"\n}";
}
}
class DeviceCommon {
#SerializedName("ASIdentifier")
String asIdentifier;
#SerializedName("DatadeliveyMechanism")
String datadeliveyMechanism;
#SerializedName("MobileOriginatorCallbackReference")
Url mobileOriginatorCallbackReference;
#SerializedName("AccessiblityCallbackReference")
Url accessiblityCallbackReference;
#Override
public String toString() {
return "DeviceCommon{" +
"\n asIdentifier='" + asIdentifier + '\'' +
"\n datadeliveyMechanism='" + datadeliveyMechanism + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n accessiblityCallbackReference=" + accessiblityCallbackReference +
"\n }";
}
}
class DeviceListEntry {
#SerializedName("ExternalIdentifer")
String externalIdentifer;
String msisdn;
String senderName;
#SerializedName("MobileOriginatorCallbackReference")
NotifyUrl mobileOriginatorCallbackReference;
#SerializedName("ConfigurationResultCallbackReference")
NotifyUrl configurationResultCallbackReference;
#SerializedName("ASreferenceID")
String asReferenceID;
#SerializedName("NIDDduration")
String nidDduration;
#Override
public String toString() {
return "DeviceListEntry{" +
"\n externalIdentifer='" + externalIdentifer + '\'' +
"\n msisdn='" + msisdn + '\'' +
"\n senderName='" + senderName + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n configurationResultCallbackReference=" + configurationResultCallbackReference +
"\n asReferenceID='" + asReferenceID + '\'' +
"\n nidDduration='" + nidDduration + '\'' +
"\n }";
}
}
class Url {
String url;
#Override
public String toString() {
return url;
}
}
class NotifyUrl {
String notifyURL;
#Override
public String toString() {
return notifyURL;
}
}
Running Main will result in the following output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}

Database returning indecipherable code

I have encountered a problem in my Android application. The problem is that when I try to retrieve data from my database, I get code that I cannot read. I am an amateur programmer and don't know too much about Android programming. Here is my output:
[com.example.foodsaver2.Food#42ae3420,
com.example.foodsaver2.Food#42ae3720,
com.example.foodsaver2.Food#42ae3968,
com.example.foodsaver2.Food#42ae3bd0,
com.example.foodsaver2.Food#42ae3e18,
com.example.foodsaver2.Food#42ae4060,
com.example.foodsaver2.Food#42ae42a8, com.example.foodsaver2.Food#42ae4510, com.example.foodsaver2.Food#42ae4758, com.example.foodsaver2.Food#42ae49a0, com.example.foodsaver2.Food#42ae4c08, com.example.foodsaver2.Food#42ae4e50, com.example.foodsaver2.Food#42ae50b8, com.example.foodsaver2.Food#42ae5360, com.example.foodsaver2.Food#42ae55a8, com.example.foodsaver2.Food#42ae5810, com.example.foodsaver2.Food#42ae5a58, com.example.foodsaver2.Food#42ae5ca0, com.example.foodsaver2.Food#42ae5ee8, com.example.foodsaver2.Food#42ae61d0, com.example.foodsaver2.Food#42ae6418, com.example.foodsaver2.Food#42ae6660, com.example.foodsaver2.Food#42ae68c8, com.example.foodsaver2.Food#42ae6b10, com.example.foodsaver2.Food#42ae6d58, com.example.foodsaver2.Food#42ae6fa0, com.example.foodsaver2.Food#42ae7208, com.example.foodsaver2.Food#42ae7450, com.example.foodsaver2.Food#42ae7790, com.example.foodsaver2.Food#42ae79d8, com.example.foodsaver2.Food#42ae7c60, com.example.foodsaver2.Food#42ae7ea8, com.example.foodsaver2.Food#42ae8130, com.example.foodsaver2.Food#42ae8378, com.example.foodsaver2.Food#42ae85e0, com.example.foodsaver2.Food#42ae8848, com.example.foodsaver2.Food#42ae8ab0, com.example.foodsaver2.Food#42ae8d18, com.example.foodsaver2.Food#42ae8f80, com.example.foodsaver2.Food#42ae91e8, com.example.foodsaver2.Food#42ae9450, com.example.foodsaver2.Food#42ae97c0, com.example.foodsaver2.Food#42ae9a28, com.example.foodsaver2.Food#42ae9c70, com.example.foodsaver2.Food#42ae9ee0, com.example.foodsaver2.Food#42aea128, com.example.foodsaver2.Food#42aea370, com.example.foodsaver2.Food#42aea5d8, com.example.foodsaver2.Food#42aea820, com.example.foodsaver2.Food#42aeaa88, com.example.foodsaver2.Food#42aeacd0, com.example.foodsaver2.Food#42aeaf38, com.example.foodsaver2.Food#42aeb180, com.example.foodsaver2.Food#42aeb3e8, com.example.foodsaver2.Food#42aeb630, com.example.foodsaver2.Food#42aeb878, com.example.foodsaver2.Food#42aebae0, com.example.foodsaver2.Food#42aebd28, com.example.foodsaver2.Food#42aebf90, com.example.foodsaver2.Food#42aec1d8, com.example.foodsaver2.Food#42aec440, com.example.foodsaver2.Food#42aec808, com.example.foodsaver2.Food#42aeca70, com.example.foodsaver2.Food#42aeccb8, com.example.foodsaver2.Food#42aecf00, com.example.foodsaver2.Food#42aed168, com.example.foodsaver2.Food#42aed3b0, com.example.foodsaver2.Food#42aed618, com.example.foodsaver2.Food#42aed860, com.example.foodsaver2.Food#42aedaa8, com.example.foodsaver2.Food#42aedd10, com.example.foodsaver2.Food#42aedf58, com.example.foodsaver2.Food#42aee1a0, com.example.foodsaver2.Food#42aee408, com.example.foodsaver2.Food#42aee650, com.example.foodsaver2.Food#42aee8b8, com.example.foodsaver2.Food#42aeeb00, com.example.foodsaver2.Food#42aeed68, com.example.foodsaver2.Food#42aeefb0, com.example.foodsaver2.Food#42aef218, com.example.foodsaver2.Food#42aef460, com.example.foodsaver2.Food#42aef6c8, com.example.foodsaver2.Food#42aef910, com.example.foodsaver2.Food#42aefb58, com.example.foodsaver2.Food#42aefdc0, com.example.foodsaver2.Food#42af0008, com.example.foodsaver2.Food#42af0250, com.example.foodsaver2.Food#42af04b8, com.example.foodsaver2.Food#42af0700, com.example.foodsaver2.Food#42af0948, com.example.foodsaver2.Food#42af0bb0, com.example.foodsaver2.Food#42af1028, com.example.foodsaver2.Food#42af1270, com.example.foodsaver2.Food#42af14d8, com.example.foodsaver2.Food#42af1720, com.example.foodsaver2.Food#42af1968, com.example.foodsaver2.Food#42af1bd0, com.example.foodsaver2.Food#42af1e18, com.example.foodsaver2.Food#42af2060, com.example.foodsaver2.Food#42af22c8, com.example.foodsaver2.Food#42af2510, com.example.foodsaver2.Food#42af2778, com.example.foodsaver2.Food#42af29c0, com.example.foodsaver2.Food#42af2c08, com.example.foodsaver2.Food#42af2e70, com.example.foodsaver2.Food#42af30b8, com.example.foodsaver2.Food#42af3300, com.example.foodsaver2.Food#42af3568]
Here is what I did:
public void send (View v) {
List<String> strlist = new ArrayList<String>();
strlist = mDbHelper.getAllComments();
GmailSender sender = new GmailSender("omitted", "omitted");
try {
sender.sendMail("DietWatcher Feedback",
strlist + "",
"ommited",
"omitted");
Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
}
}
Here is some of my database code:
public List getAllComments() {
List customers = new ArrayList();
String inputText = "";
String query =
KEY_CUSTOMER + /*"INTEGER," + */ "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
KEY_SEARCH + "," +
TOTAL_CARB + "," +
FIBER +
SUGAR +
PROTEIN+
SODIUM +
TOTALCALORIES +
FTS_VIRTUAL_TABLE +
KEY_SEARCH;
Log.w(TAG, query);
//Cursor mCursor = mDb.rawQuery(query,null);
Cursor cursor = mDb.query(FTS_VIRTUAL_TABLE, new String[]{KEY_CUSTOMER + "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
TOTAL_CARB /*+
FIBER +
SUGAR +
PROTEIN+
SODIUM +
TOTALCALORIES +
FTS_VIRTUAL_TABLE +
KEY_SEARCH */}, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Food customer = cursorToCustomer(cursor);
customers.add(customer);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return customers;
}
private Food cursorToCustomer(Cursor cursor) {
Food customer = new Food();
customer.setCustomer(cursor.getString(0));
customer.setName(cursor.getString(1));
customer.setAddress1(cursor.getString(2));
customer.setAddress2(cursor.getString(3));
customer.setCity(cursor.getString(4));
customer.setState(cursor.getString(5));
customer.setZipCode(cursor.getString(6));
return customer;
}
Here is Food.java:
package com.example.foodsaver2;
public class Food {
String customer = null;
String name = null;
String address1 = null;
String address2 = null;
String city = null;
String state = null;
String zipCode = null;
String carb = null;
String fiber = null;
String sugar = null;
String protein = null;
String sodium = null;
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCarb() {return carb;}
public void setCarb(String carb) {this.carb = carb;}
public String getFiber() {return fiber;}
public void setFiber() {this.fiber = fiber;}
public String getSugar() {return sugar;}
public void setSugar() {this.sugar = sugar;}
public String getProtein() {return protein;}
public void setProtein() {this.protein = protein;}
public String getSodium() {return sodium;}
public void setSodium() {this.sodium = sodium;}
}
So what did I do wrong here? Any help regarding this problem would be greatly appreciated.
mDbHelper.getAllComments() return List of Food class object's instead of String so response is not readable format. if you want to pass details from strlist to sender.sendMail then you will need to prepare another List which Store values from strlist as String. try is as:
ArrayList<Food> arrallcomments = mDbHelper.getAllComments();
List<String> strlist = new ArrayList<String>();
for(Food object: list){
strlist.add("Name : "+object.getName() +
" Customer :"+object.getCustomer()+...);
}
now use strlist for sending ArrayList with Mail.

Unit-testing methods secured with Securesocial annotation

I'm trying to make some functional tests for my webapplication that is using Play 2.1.4 and Socialsecure. Before using securesocial the tests where pretty straight forward but now im having troubles figuering out how i can make tests on the secured actions.
#Test
public void createNewNote() {
Result result;
// Should return bad request if no data is given
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "", "text",
"")));
assertThat(status(result)).isEqualTo(BAD_REQUEST);
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "My note title", "text",
"My note content")));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/notes");
Note newNote = Note.find.where().eq("title", "My note title")
.findUnique();
// Should be saved to DB
assertNotNull(newNote);
assertEquals("My note title", newNote.title);
assertEquals("My note content", newNote.text);
}
As of right now i got a user in the test yml file:
- !!models.User
id: 1234567890
username: Pingu
provider: Twitter
firstName: Pingu
lastName: Pingusson
email: pingu#note.com
password: password
My user is pretty straight forward...:
#Table(
uniqueConstraints=
#UniqueConstraint(columnNames={"username"}))
#Entity
public class User extends Model {
private static final long serialVersionUID = 1L;
#Id
public String id;
public String provider;
public String firstName;
public String lastName;
public String email;
public String password;
#MinLength(5)
#MaxLength(20)
public String username;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public static User findById(String id) {
return find.where().eq("id", id).findUnique();
}
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
#Override
public String toString() {
return this.id + " - " + this.firstName;
}
}
and the UserService:
public class UserService extends BaseUserService {
public UserService(Application application) {
super(application);
}
#Override
public void doDeleteExpiredTokens() {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteExpiredTokens...");
}
List<LocalToken> list = LocalToken.find.where().lt("expireAt", new DateTime().toString()).findList();
for(LocalToken localToken : list) {
localToken.delete();
}
}
#Override
public void doDeleteToken(String uuid) {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteToken...");
Logger.debug(String.format("uuid = %s", uuid));
}
LocalToken localToken = LocalToken.find.byId(uuid);
if(localToken != null) {
localToken.delete();
}
}
#Override
//public Identity doFind(UserId userId) {
public Identity doFind(IdentityId identityId){
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("finding by Id = %s", identityId.userId()));
}
User localUser = User.find.byId(identityId.userId());
Logger.debug(String.format("localUser = " + localUser));
if(localUser == null) return null;
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("socialUser = %s", socialUser));
}
return socialUser;
}
#Override
public Identity doFindByEmailAndProvider(String email, String providerId) {
List<User> list = User.find.where().eq("email", email).eq("provider", providerId).findList();
if(list.size() != 1){
Logger.debug("found a null in findByEmailAndProvider...");
return null;
}
User localUser = list.get(0);
SocialUser socialUser =
new SocialUser(new IdentityId(localUser.email, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
return socialUser;
}
#Override
public Token doFindToken(String token) {
if (Logger.isDebugEnabled()) {
Logger.debug("findToken...");
Logger.debug(String.format("token = %s", token));
}
LocalToken localToken = LocalToken.find.byId(token);
if(localToken == null) return null;
Token result = new Token();
result.uuid = localToken.uuid;
result.creationTime = new DateTime(localToken.createdAt);
result.email = localToken.email;
result.expirationTime = new DateTime(localToken.expireAt);
result.isSignUp = localToken.isSignUp;
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("foundToken = %s", result));
}
return result;
}
#Override
public Identity doSave(Identity user) {
if (Logger.isDebugEnabled()) {
Logger.debug("save...!_!");
Logger.debug(String.format("user = %s", user));
}
User localUser = null;
localUser = User.find.byId(user.identityId().userId());
Logger.debug("id = " + user.identityId().userId());
Logger.debug("provider = " + user.identityId().providerId());
Logger.debug("firstName = " + user.firstName());
Logger.debug("lastName = " + user.lastName());
Logger.debug(user.fullName() + "");
Logger.debug("email = " + user.email());
Logger.debug(user.email().getClass() + "");
if (localUser == null) {
Logger.debug("adding new...");
localUser = new User();
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.save();
} else {
Logger.debug("existing one...");
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.update();
}
return user;
}
#Override
public void doSave(Token token) {
LocalToken localToken = new LocalToken();
localToken.uuid = token.uuid;
localToken.email = token.email;
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localToken.createdAt = df.parse(token.creationTime.toString("yyyy-MM-dd HH:mm:ss"));
localToken.expireAt = df.parse(token.expirationTime.toString("yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
Logger.error("UserService.doSave(): ", e);
}
localToken.isSignUp = token.isSignUp;
localToken.save();
}
}
As of my understanding i should in someway set the session so the user is logged in by using the .withsession method on the fakerequest and maybe also set some value on the serverside.
Tried searching the web for examples using securesocial and play but found no tests at all.
How can i login in my user so i can preform the tests?
Best regards
Rawa
Thanks to David Weinbergs comment i was able to solve this after some trail and error. (:
I started out my LocalUser implementation from this reply:
https://stackoverflow.com/a/18589402/1724097
This is how i solved it:
To make unit tests i created a local user in the database, using the test-data.yml file:
- !!models.LocalUser
id: 1234567890
username: Username
provider: userpass
firstName: firstName
lastName: lastName
email: user#example.com
#hash for "password"
password: $2a$10$.VE.rwJFMblRv2HIqhZM5.CiqzYOhhJyLYrKpMmwXar6Vp58U7flW
Then i made a test utils class that create my fakeCookie.
import models.LocalUser;
import play.Logger;
import securesocial.core.Authenticator;
import securesocial.core.IdentityId;
import securesocial.core.SocialUser;
import securesocial.core.PasswordInfo;
import scala.Some;
import securesocial.core.AuthenticationMethod;
import scala.Option;
import scala.util.Right;
import scala.util.Either;
import play.mvc.Http.Cookie;
public class Utils {
public static Cookie fakeCookie(String user){
LocalUser localUser = LocalUser.findByEmail(user);
Logger.debug("Username: " + localUser.username +" - ID: " + localUser.id);
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
Either either = Authenticator.create(socialUser);
Authenticator auth = (Authenticator) either.right().get();
play.api.mvc.Cookie scalaCookie = auth.toCookie();
//debug loggig
Logger.debug("Cookie data:");
Logger.debug("Name: " + "Value: " + auth.cookieName() + " | Class: " + auth.cookieName().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Value: " + "Value: " + scalaCookie.value() + " | Class: " + scalaCookie.value().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("MaxAge: " + "Value: " + scalaCookie.maxAge() + " | Class: " + scalaCookie.maxAge().getClass() + " | Should be type: " + "int");
Logger.debug("Path: " + "Value: " + scalaCookie.path() + " | Class: " + scalaCookie.path().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Domain: " + "Value: " + scalaCookie.domain() + " | Class: " + auth.cookieDomain().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Secure: " + "Value: " + auth.cookieSecure() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
Logger.debug("HttpOnly: " + "Value: " + auth.cookieHttpOnly() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
// secureSocial doesnt seem to set a maxAge or Domain so i set them myself.
Cookie fakeCookie = new Cookie(auth.cookieName(), scalaCookie.value(), 120, scalaCookie.path(), "None", auth.cookieSecure(), auth.cookieHttpOnly());
return fakeCookie;
}
}
And then i simply use my cookie to in the fakeRequest so im logged in:
Cookie cookie = Utils.fakeCookie("user#example.com");
Result result = callAction(
controllers.routes.ref.yourSampleClass.yourSecuredFucntion(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("Value", "Some input value")).withCookies(cookie));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/yourWantedResult");
Hope this helps others!

Parse List of JSON objects using GSON

I have a JSON object like this:
{
"user1": {
"timeSpent": "20.533333333333335h",
"worklog": [
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-2",
"comment": "\ncccccc",
"timeSpent": "20.533333333333335h"
}
],
"dayTotal": "20.533333333333335h"
}
]
},
"admin": {
"timeSpent": "601.1h",
"worklog": [
{
"date": "06/25/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "113.1h"
}
],
"dayTotal": "113.1h"
},
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "8h"
},
{
"issueCode": "COC-2",
"comment": "",
"timeSpent": "480h"
}
],
"dayTotal": "488h"
}
]
}
}
and trying to parse it with Gson:
Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);
But the 'responceBean' is always 'null'
Here are all the other classes:
public class Book {
private List<User> user = new LinkedList<User>();
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new LinkedList<WorkLog>();;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklogs(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
}
public class WorkLog{
private String date;
private String dayTotal;
private List<Issues> issues;
public String getDate(){
return this.date;
}
public void setDate(String date){
this.date = date;
}
public String getDayTotal(){
return this.dayTotal;
}
public void setDayTotal(String dayTotal){
this.dayTotal = dayTotal;
}
public List<Issues> getIssues(){
return this.issues;
}
public void setIssues(List<Issues> issues){
this.issues = issues;
}
}
public class Issues{
private String comment;
private String issueCode;
private String timeSpent;
public String getComment(){
return this.comment;
}
public void setComment(String comment){
this.comment = comment;
}
public String getIssueCode(){
return this.issueCode;
}
public void setIssueCode(String issueCode){
this.issueCode = issueCode;
}
public String getTimeSpent(){
return this.timeSpent;
}
public void setTimeSpent(String timeSpent){
this.timeSpent = timeSpent;
}
}
This is my latest attempt. Somehow I cannot figure out the right way. Will be very appreciative for any help.
Your JSON model does not match your object model.
You need an intermediate layer to fill the gap: a TypeAdapter.
Moreover there is no naming information for the user.
And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is a fixed version:
Java model:
class User {
private String timeSpent;
#SerializedName("worklog")
private List<WorkLog> worklogs = new LinkedList<WorkLog>();
private String name;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklog(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The plumbing to fill the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book>
{
Gson gson = new Gson();
public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context)
{
JsonObject json = new JsonObject();
for (User user : book.getUser())
{
json.addProperty(user.getName(), gson.toJson(user));
}
return json;
}
public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject json = element.getAsJsonObject();
Book book = new Book();
for (Entry<String, JsonElement> entry : json.entrySet())
{
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(), User.class);
user.setName(name);
book.getUser().add(user);
}
return book;
}
}
And a roundtrip:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTypeAdapter());
Gson gson = builder.create();
Book book = gson.fromJson("{" +
" \"user1\": {" +
" \"timeSpent\": \"20.533333333333335h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\ncccccc\"," +
" \"timeSpent\": \"20.533333333333335h\"" +
" }" +
" ]," +
" \"dayTotal\": \"20.533333333333335h\"" +
" }" +
" ]" +
" }," +
" \"admin\": {" +
" \"timeSpent\": \"601.1h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/25/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"113.1h\"" +
" }" +
" ]," +
" \"dayTotal\": \"113.1h\"" +
" }," +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"8h\"" +
" }," +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"480h\"" +
" }" +
" ]," +
" \"dayTotal\": \"488h\"" +
" }" +
" ]" +
" }" +
"}", Book.class);
String json = gson.toJson(book);
Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson
Enjoy! :)
I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new List < WorkLog >();
}
Try this and I hope that it will help.
P.S.
Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.

Categories

Resources