Gson to parse string of arrays - java

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'
}]
}

Related

Actual and formal argument lists differ in length error in main

Im working on a project where I have 3 text files with data of doctors, patients and home visits. When Im trying to upload the doctors file, upload all the data to a new object I get an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Id_pacjenta Nazwisko Imie PESEL Data_urodzenia"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.company.Main.main(Main.java:40)
Below I'll paste my main as well as the classes & a snapshot of the text file used for imports:
Could anyone advise how to avoid this issue? Thanks!
public class Main {
public static void main(String[] args) {
List<Lekarz> lekarz = new ArrayList<>();
try{
File fileLekarze = new File("src/com/company/lekarze.txt");
Scanner readerLekarze = new Scanner(fileLekarze);
while(readerLekarze.hasNextLine()){
String[] data =readerLekarze.nextLine().split(" ");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
readerLekarze.close();
} catch (FileNotFoundException e) {
System.out.println("Error File Lekarze");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
List<Pacjenci> pacjent = new ArrayList<>();
try{
File pacjenciFile = new File("src/com/company/pacjenci.txt");
Scanner readerPacjenci = new Scanner(pacjenciFile);
while(readerPacjenci.hasNextLine()){
String[] data = readerPacjenci.nextLine().split(" ");
pacjent.add(new Pacjenci(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}
readerPacjenci.close();
}catch (FileNotFoundException e) {
System.out.println("Error File Pacjenci");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
}
}
public class Pacjenci {
private int idPacjenta;
private String nazwisko;
private String imie;
private String pesel;
private Date dataUrodzenia;
public Pacjenci(int idPacjenta, String nazwisko, String imie, String pesel, Date dataUrodzenia) {
this.idPacjenta = idPacjenta;
this.nazwisko = nazwisko;
this.imie = imie;
this.pesel = pesel;
this.dataUrodzenia = dataUrodzenia;
}
public int getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(int idPacjenta) {
this.idPacjenta = idPacjenta;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public Date getDataUrodzenia() {
return dataUrodzenia;
}
public void setDataUrodzenia(Date dataUrodzenia) {
this.dataUrodzenia = dataUrodzenia;
}
#Override
public String toString() {
return "Pacjenci{" +
"idPacjenta=" + idPacjenta +
", nazwisko='" + nazwisko + '\'' +
", imie='" + imie + '\'' +
", pesel='" + pesel + '\'' +
", dataUrodzenia=" + dataUrodzenia +
", wizyty=" +
", lekarze=" +
'}';
}
}
public class Wizyty {
private Lekarz idLekarza;
private Pacjenci idPacjenta;
private Date dataWizyty;
public Wizyty(Lekarz idLekarza, Pacjenci idPacjenta, Date dataWizyty) {
this.idLekarza = idLekarza;
this.idPacjenta = idPacjenta;
this.dataWizyty = dataWizyty;
}
public Lekarz getIdLekarza() {
return idLekarza;
}
public void setIdLekarza(Lekarz idLekarza) {
this.idLekarza = idLekarza;
}
public Pacjenci getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(Pacjenci idPacjenta) {
this.idPacjenta = idPacjenta;
}
public Date getDataWizyty() {
return dataWizyty;
}
public void setDataWizyty(Date dataWizyty) {
this.dataWizyty = dataWizyty;
}
#Override
public String toString() {
return "Wizyty{" +
"idLekarza=" + idLekarza +
", idPacjenta=" + idPacjenta +
", dataWizyty=" + dataWizyty +
'}';
}
}
Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
100 Kowal Waldemar 01211309876 2001-1-13
Because of the data spacing in the file, try this:
while(readerLekarze.hasNextLine()){
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim()
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
You could also just do:
String[] data = readerLekarze.nextLine().trim().split("\\s+");
As a complement to the #DevilsHnd, you only need to add a code to avoid the first line, because the first line is the "header information" of your file.
boolean headerRead = false;
while(readerLekarze.hasNextLine()) {
if (!headerRead) {
// extract the first line -> Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
readerLekarze.nextLine();
headerRead = true;
continue;
}
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim();
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(
Integer.parseInt(data[0]),
data[1],
data[2],
data[3],
new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}

POST data with retrofit2, Bearer token Unauthorized android

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.

Printing textdata from toString - Java

I am working on a personal Java project and learning how to print out data from a text file. My code (as you can see below) prints out the userNameGenerator and personName data perfectly fine but I want it to be printed out from the toString in my Java Class. How can I change my code to print it out from there?
This is how my toString looks like:
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
Full code:
import java.util.*;
import java.io.*;
public class Codes {
public static void main(String[] args) {
List<Codes2> personFile = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
String fileRead = br.readLine();
while (fileRead != null) {
String[] personData = fileRead.split(":");
String personName = personData[0];
String userNameGenerator = personData[1];
Codes2 personObj = new Codes2(personName, userNameGenerator);
personFile.add(personObj);
fileRead = br.readLine();
}
br.close();
}
catch (FileNotFoundException ex) {
System.out.println("File not found!");
}
catch (IOException ex) {
System.out.println("An error has occured: " + ex.getMessage());
}
Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++){
String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
for(int j = 0; j < regionSplit.length; j++){
newStrSet.add(regionSplit[j]);
}
}
for (String p: newStrSet) {
System.out.printf("%s -> ", p);
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.getPersonName());
}
}
System.out.println();
}
}
}
Java Class:
public class Codes2 implements Comparable<Codes2> {
private String personName;
private String userNameGenerator;
public Codes2(String personName, String userNameGenerator) {
this.personName = personName;
this.userNameGenerator = userNameGenerator;
}
public String getPersonName() {
return personName;
}
public String getUserNameGenerator() {
return userNameGenerator;
}
#Override
public int compareTo(Codes2 o) {
return getUserNameGenerator().compareTo(o.getUserNameGenerator());
}
public int compare(Object lOCR1, Object lOCR2) {
return ((Codes2)lOCR1).userNameGenerator
.compareTo(((Codes2)lOCR2).userNameGenerator);
}
#Override
public String toString() {
return userNameGenerator + " -> " + "[" + personName + "]" ;
}
}
Everything looks right in your code.
I think you should just call the method when you are trying to print it out:
for (Codes2 s: personFile) {
if (s.getUserNameGenerator().contains(p)) {
System.out.printf("%s, ", s.toString());
}
}
This follows the fact that the class that prints out the object is not so closely coupled with the class that hold the data.
Try:
#Override
public String toString() {
return String.format("%s -> [%s]",this.userNameGenerator,this.personName);
}

String from other class .. only get "null"

I want to use a String out of an other class, but I only get null.
I tried to get the values with the Code here:
System.out.println("Auftrag: " + super.getSollAuftrag1());
System.out.println("Quote: " + super.getSollQuote1());
System.out.println("Teil: " + super.getSollTeil1());
System.out.println("Stueck: " + super.getSollStueck1());
public class ReadText {
public static String sollAuftrag1;
public static String sollQuote1;
public static String sollTeil1;
public static String sollStueck1;
public static String parts;
public static String getParts() {
return parts;
}
public static void setParts(String parts) {
ReadText.parts = parts;
}
protected String getSollAuftrag1() {
return sollAuftrag1;
}
protected void setSollAuftrag1(String sollAuftrag) {
ReadText.sollAuftrag1 = sollAuftrag;
}
public String getSollQuote1() {
return sollQuote1;
}
public void setSollQuote1(String sollQuote) {
ReadText.sollQuote1 = sollQuote;
}
public String getSollTeil1() {
return sollTeil1;
}
public void setSollTeil1(String sollTeil) {
ReadText.sollTeil1 = sollTeil;
}
public String getSollStueck1() {
return sollStueck1;
}
public void setSollStueck1(String sollStueck) {
ReadText.sollStueck1 = sollStueck;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = null;
String file_at_path_to_desktop = System.getProperty("user.home") + "\\" + "Desktop" + "\\" + "SollAuftrag.txt";
try {
br = new BufferedReader(new FileReader(new File(file_at_path_to_desktop)));
String line = null;
while ((line = br.readLine()) != null) {
new ArrayList<String>(Arrays.asList(line.split(";")));
String[] parts = line.split(";");
sollAuftrag1 = (parts[0]);
sollQuote1 = (parts[1]);
sollTeil1 = (parts[0]);
sollStueck1 = (parts[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Auftrag: " + sollAuftrag1);
System.out.println("Unterauftrag: " + sollQuote1);
System.out.println("Teil: " + sollTeil1);
System.out.println("Stueck: " + sollStueck1);
}
}

wrapper class is it a design pattern

i'm new to design pattern , and now i'm working on an open ware code : so i'm trying to understand the architecture of the code : layers , used design pattern ...
So i found the a package containing classes named EntityWrapper.java here's an example :
The wrapper class :
package org.objectweb.salome_tmf.api.data;
/**
* #author marchemi
*/
public class ActionWrapper extends DataWrapper{
String awaitedResult;
int orderIndex;
int idTest;
/**
* #return Returns the orderIndex.
*/
public int getOrderIndex() {
return orderIndex;
}
/**
* #param orderIndex The orderIndex to set.
*/
public void setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
}
/**
* #return Returns the waitedResult.
*/
public String getAwaitedResult() {
return awaitedResult;
}
/**
* #param waitedResult The waitedResult to set.
*/
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
/**
* #return Returns the idTest.
*/
public int getIdTest() {
return idTest;
}
/**
* #param idTest The idTest to set.
*/
public void setIdTest(int idTest) {
this.idTest = idTest;
}
}
The entity class:
package org.objectweb.salome_tmf.data;
import java.io.File;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.api.Util;
import org.objectweb.salome_tmf.api.data.ActionWrapper;
import org.objectweb.salome_tmf.api.data.FileAttachementWrapper;
import org.objectweb.salome_tmf.api.data.ParameterWrapper;
import org.objectweb.salome_tmf.api.data.SalomeFileWrapper;
import org.objectweb.salome_tmf.api.data.UrlAttachementWrapper;
import org.objectweb.salome_tmf.api.sql.ISQLAction;
public class Action extends WithAttachment {
static ISQLAction pISQLAction = null;
private String awaitedResult;
public String getAwaitedResult() {
return awaitedResult;
}
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
private int orderIndex;
private Hashtable parameterHashTable;
private Test pTest = null;
public Action(Test pTest, String name, String description) {
super(name, description);
awaitedResult = "";
orderIndex = 0;
parameterHashTable = new Hashtable();
this.pTest = pTest;
if (pISQLAction == null){
pISQLAction = Api.getISQLObjectFactory().getISQLAction();
}
}
public Action(ActionWrapper pAction, Test pTest) {
this(pTest, pAction.getName(), pAction.getDescription());
awaitedResult = pAction.getAwaitedResult();
orderIndex = pAction.getOrderIndex();
idBdd = pAction.getIdBDD();
}
public Action(Action pAction, Test pTest) {
this(pTest, pAction.getNameFromModel(), pAction.getDescriptionFromModel());
awaitedResult = pAction.getAwaitedResultFromModel();
} // Fin du constructeur Action/1
protected void reloadBaseFromDB() throws Exception {
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
ActionWrapper pActionWrapper = pISQLAction.getActionWrapper(idBdd);
awaitedResult = pActionWrapper.getAwaitedResult();
orderIndex = pActionWrapper.getOrderIndex();
name = pActionWrapper.getName();
description = pActionWrapper.getDescription();
}
public void reloadFromDB(boolean base, Hashtable paramsInModel, boolean attach)
throws Exception {
int transNuber = -1;
try {
transNuber = Api.beginTransaction(101, ApiConstants.LOADING);
if (base){
reloadBaseFromDB();
}
reloadUsedParameterFromDB(paramsInModel);
if (attach){
reloadAttachmentDataFromDB(false);
}
Api.commitTrans(transNuber);
} catch (Exception e){
Api.forceRollBackTrans(transNuber);
throw e;
}
}
public void clearCache() {
/* TODO ClearAttachement */
}
/******************************************************************************/
/** ACCESSEURS ET
MUTATEURS ***/
/******************************************************************************/
public String getAwaitedResultFromModel() {
return awaitedResult;
}
public void setAwaitedResultInModel(String string) {
awaitedResult = string;
}
public int getOrderIndexFromModel() {
return orderIndex;
}
public void setOrderIndex(int i) {
orderIndex = i;
}
public Test getTest(){
return pTest;
}
/////////////////////////////// Basic Operation /////////////////////////
/* Used by Manuel Test */
void addInDB(Test pTest) throws Exception {
//boolean needUpdate = false;
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
if (!pTest.isInBase()){
throw new Exception("Test " + pTest.getNameFromModel() + " is not in BDD");
}
int id = pISQLAction.insert(pTest.getIdBdd(), name, description, awaitedResult);
setIdBdd(id);
orderIndex = pISQLAction.getActionWrapper(id).getOrder();
/*if (orderIndex != rowCount){
needUpdate = true;
}
return needUpdate;*/
Project.pCurrentProject.notifyChanged( ApiConstants.INSERT_ACTION ,this);
}
/* Used by Manuel Test */
void addInModel(Test pTest){
this.pTest = pTest;
}
/* Used by Manuel Test */
void addInDBAndModel(Test pTest)throws Exception {
//boolean res;
addInDB(pTest);
addInModel(pTest);
//return res;
}
public void updateInDB(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.update(idBdd, newActionName, newActionDesc, newActionResAttendu );
Project.pCurrentProject.notifyChanged( ApiConstants.UPDATE_ACTION ,this, new String(name), newActionName);
}
public void updateInModel(String newActionName, String newActionDesc, String newActionResAttendu) {
setNameInModel(newActionName);
updateDescriptionInModel(newActionDesc);
setAwaitedResultInModel(newActionResAttendu);
}
public void updateInDBAndModel(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
updateInDB(newActionName, newActionDesc, newActionResAttendu);
updateInModel(newActionName, newActionDesc, newActionResAttendu);
}
public void updateInDBAndModel(String newName, String newDesc) throws Exception {
updateInDB(newName, newDesc, awaitedResult);
updateInModel(newName, newDesc, awaitedResult);
}
public void updateOrderInDBAndModel(boolean inc) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
orderIndex = pISQLAction.updateOrder(idBdd, inc);
}
/* Used by Manuel Test */
void deleteInDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.delete(idBdd);
Project.pCurrentProject.notifyChanged( ApiConstants.DELETE_ACTION ,this);
}
/* Used by Manuel Test */
void deleteInModel(){
pTest=null;
parameterHashTable.clear();
clearAttachInModel();
}
/* Used by Manuel Test */
void deleteInDBAndModel() throws Exception {
deleteInDB();
deleteInModel();
}
//////////////// PARAMETERS ////////////////////////
public void setParameterHashSetInModel(HashSet set) {
parameterHashTable.clear();
for (Iterator iter = set.iterator(); iter.hasNext();) {
Parameter param = (Parameter)iter.next();
parameterHashTable.put(param.getNameFromModel(), param);
}
}
public void setParameterHashtableInModel(Hashtable table) {
parameterHashTable.clear();
parameterHashTable = table;
}
public Hashtable getCopyOfParameterHashTableFromModel(){
Hashtable copyParameter = new Hashtable();
Enumeration enumKey = parameterHashTable.keys();
while (enumKey.hasMoreElements()){
Object key = enumKey.nextElement();
copyParameter.put(key, parameterHashTable.get(key));
}
return copyParameter;
}
public void reloadUsedParameterFromDB(Hashtable parametersInModel) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] paramActionArray = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < paramActionArray.length; i++) {
Parameter param = null;
ParameterWrapper pParameterWrapper = paramActionArray[i];
if (parametersInModel != null){
param = (Parameter)parametersInModel.get(pParameterWrapper.getName());
if (param == null){
param = new Parameter(pParameterWrapper);
}
}
setUseParamInModel(param);
}
}
public void setUseParamInModel(Parameter pParam) {
parameterHashTable.put(pParam.getNameFromModel(), pParam);
if (pTest != null) {
if (pTest.getUsedParameterFromModel(pParam.getNameFromModel()) == null){
pTest.setUseParamInModel(pParam);
}
}
}
public void setUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.addUseParam(idBdd,paramId);
}
public void setUseParamInDBAndModel(Parameter pParam) throws Exception {
//DB
setUseParamInDB(pParam.getIdBdd());
//model
setUseParamInModel(pParam);
}
public void deleteUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteParamUse(idBdd, paramId);
}
public void deleteUseParamInDBAndModel(Parameter pParam) throws Exception {
deleteUseParamInDB(pParam.getIdBdd());
deleteUseParamInModel(pParam);
}
public void deleteUseParamInModel(Parameter pParam) {
// Clean Action
String newDesc = null ;
if (getDescriptionFromModel()!=null)
newDesc = clearStringOfParameter(getDescriptionFromModel(), pParam);
String newResult = null;
if (getAwaitedResultFromModel()!=null)
newResult = clearStringOfParameter(getAwaitedResultFromModel(), pParam);
description = newDesc;
awaitedResult = newResult;
Object o= parameterHashTable.remove(pParam.getNameFromModel());
Util.log("[Action->deleteUseParamInModel] Delete Use Parameter " + pParam + ", in Action " + name + " res is " +o);
}
public Parameter getParameterFromModel(String name) {
Enumeration paramList = parameterHashTable.elements();
while (paramList.hasMoreElements()){
Parameter param = (Parameter)paramList.nextElement();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public Parameter getParameterFromDB(String name) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = getParameterHashSetFromDB();
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
Parameter param = (Parameter)iter.next();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public HashSet getParameterHashSetFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = new HashSet();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Vector getParameterVectorFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
Vector result = new Vector();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Hashtable getParameterHashSetFromModel() {
return parameterHashTable;
}
////////////// ATTACHEMENT ///////////////////////
public void addAttachementInDB (Attachment attach )throws Exception {
if (attach instanceof FileAttachment) {
addAttachFileInDB((FileAttachment) attach);
} else {
addAttachUrlInDB((UrlAttachment) attach);
}
}
void addAttachFileInDB(FileAttachment file) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
File f = file.getLocalFile();
int id = pISQLAction.addFileAttach(idBdd,new SalomeFileWrapper(f),file.getDescriptionFromModel());
file.setIdBdd(id);
}
void addAttachUrlInDB(UrlAttachment url) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
int id = pISQLAction.addUrlAttach(idBdd, url.getNameFromModel(),url.getDescriptionFromModel());
url.setIdBdd(id);
}
public void deleteAttachementInDB(int attachId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteAttachment(idBdd, attachId);
}
public void deleteAttachementInDBAndModel(Attachment attach)throws Exception {
deleteAttachementInDB(attach.getIdBdd());
deleteAttachmentInModel(attach);
}
public Vector getAttachFilesFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
FileAttachementWrapper[] fawArray = pISQLAction.getAllAttachFile(idBdd);
Vector result = new Vector();
for(int i = 0; i < fawArray.length; i++) {
result.add(fawArray[i]);
}
return result;
}
public Vector getAttachUrlsFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
UrlAttachementWrapper[] uawArray = pISQLAction.getAllAttachUrl(idBdd);
Vector result = new Vector();
for(int i = 0; i < uawArray.length; i++) {
result.add(uawArray[i]);
}
return result;
}
//////// PROTECTED //////////////
protected String clearStringOfParameter(String prtString, Parameter pParam) {
String result = prtString;
result = result.replaceAll("[$]" + pParam.getNameFromModel() + "[$]", "");
return result;
}
public static boolean isInBase(Test pTest, String actionName) {
try {
int id = pISQLAction.getID(pTest.getIdBdd(), actionName);
if (id > 0){
return true;
}
return false;
} catch (Exception e) {
}
return false;
} // Fin de la methode isInBase/1
public boolean existeInBase() throws Exception {
if (!isInBase()) {
return false;
}
return pISQLAction.getID(pTest.getIdBdd(), name) == idBdd;
}
}
So what is the utility of the wrapper class , is it a kind of design pattern ?
I can not see, what ActionWrapper wraps, for me is just implementation of DataWrapper interface.
There 3 "kinds" of wrappers design patterns:
Facade design pattern = take a lot of classes/interfaces, do some logic inside and get out small interface. For example "Car start" encapsulate inside: open car, put key, set DVD, correct chair, ignition.
Decorator design pattern = take some class with behavior and make ability to add behaviors in run time. for example, instead of do class CarWithLCDWithDVDWithTurbo you can do: new LCDDecorator(new DVDDecorator(TurboDecorator(new car)));
Adapter design pattern = take some new interface and adapt it to some known interface.
The fact that something ends with the Wrapper word doesn´t make it a wrapper. To be a wrapper it has to wrap something. This is, it has to encapsulate one or more components, probably a whole third-party API.
There are different types of wrappers as #zzfima says. And yes, proxy could be a wrapper in some cases and also bridges could be.
Your code doesn´t encapsulate any other component and then, it is not a wrapper (at least for me)
call something "wrapper" doesn't make it a wrapper. Basically it needs to encapsulate something or wrap something, whatever you call it

Categories

Resources