Getting and putting Json into Pojo class - java

So I've made an app that should be able to search for an artist off the Spotify API. The response returns a 200 code. But the returned object is null. Meaning that either the response code should be 204 or that something is wrong with my class. The class is made with pojo and seems right.
I can't seem to figure out what is wrong.
Here are the code.
Artist Class
public class Artists {
#SerializedName("href")
#Expose
private String href;
#SerializedName("items")
#Expose
private List<Item> items;
#SerializedName("limit")
#Expose
private Integer limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private Integer offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total")
#Expose
private Integer total;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Object getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
#Override
public String toString() {
return "Artists{" +
"href='" + href + '\'' +
", items=" + items +
", limit=" + limit +
", next='" + next + '\'' +
", offset=" + offset +
", previous='" + previous + '\'' +
", total=" + total +
'}';
}
Item Class
public class Item {
#SerializedName("external_urls")
#Expose
private ExternalUrls externalUrls;
#SerializedName("followers")
#Expose
private Followers followers;
#SerializedName("genres")
#Expose
private List<String> genres;
#SerializedName("href")
#Expose
private String href;
#SerializedName("id")
#Expose
private String id;
#SerializedName("images")
#Expose
private List<Image> images;
#SerializedName("name")
#Expose
private String name;
#SerializedName("popularity")
#Expose
private Integer popularity;
#SerializedName("type")
#Expose
private String type;
#SerializedName("uri")
#Expose
private String uri;
public ExternalUrls getExternalUrls() {
return externalUrls;
}
public void setExternalUrls(ExternalUrls externalUrls) {
this.externalUrls = externalUrls;
}
public Followers getFollowers() {
return followers;
}
public void setFollowers(Followers followers) {
this.followers = followers;
}
public List<String> getGenres() {
return genres;
}
public void setGenres(List<String> genres) {
this.genres = genres;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPopularity() {
return popularity;
}
public void setPopularity(Integer popularity) {
this.popularity = popularity;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
#Override
public String toString() {
return "Item{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
'}';
}
MainActivity
public void searchForArtist(View view) {
String q = "Justin Bieber";
TrackService trackService = ApiUtils.getTrackService();
Call<Artists> artistSearch = trackService.SearchForArtist("Bearer " + AuthToken, Accept, contentType, q, type, market, limit, offset);
Log.d("TEST", artistSearch.request().url().toString());
Log.d("TEST", " " + artistSearch.request().headers());
Log.d("Tokens", AuthToken);
Log.d("Tokens", " " + RefreshToken);
artistSearch.enqueue(new Callback<Artists>() {
#Override
public void onResponse(Call<Artists> call, Response<Artists> response) {
if (response.isSuccessful()) {
if (response.body().getItems() != null) {
Item artists = response.body().getItems().get(0);
artistID = artists.getId();
Toast.makeText(MainActivity.this, "Yeehaw", Toast.LENGTH_LONG).show();
searchForTracks(artistID);
} else {
Toast.makeText(MainActivity.this, "No content in Items", Toast.LENGTH_LONG).show();
Log.d("BODY",response.body().toString());
}
} else {
String message = "Problem " + response.code() + " " + response.body();
Log.d("Tracks", message);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Artists> call, Throwable t) {
Toast.makeText(MainActivity.this, "REEEEEEEE", Toast.LENGTH_LONG).show();
}
});
}

Related

JSON is returning a list type object when it has 1 position as object and not as a list

I have a list of objects instantiated in a return class in a service's response. But when this list has 1 position, it is returning as an object and not as a list. can anybody help me?
#XmlRootElement(name = "exame")
public class ExameVO implements Serializable {
private static final long serialVersionUID = -5840337332057658386L;
private long id;
#NotNull
private String cpf;
#NotNull
private String dataNascimento;
#NotNull
private int tipoExame;
#NotNull
private String excluido;
private List<ExameArquivoVO> resultadoExameArquivos;
private String observacao;
private String dataInclusao;
public ExameVO() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public int getTipoExame() {
return tipoExame;
}
public void setTipoExame(int tipoExame) {
this.tipoExame = tipoExame;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getExcluido() {
return excluido;
}
public void setExcluido(String excluido) {
this.excluido = excluido;
}
public List<ExameArquivoVO> getResultadoExameArquivos() {
return resultadoExameArquivos;
}
public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
this.resultadoExameArquivos = resultadoExameArquivos;
}
public String getDataInclusao() {
return dataInclusao;
}
public void setDataInclusao(String dataInclusao) {
this.dataInclusao = dataInclusao;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "ResultadoExameVO [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
+ tipoExame + ", observacao=" + observacao + ", excluido=" + excluido + ", dataInclusao=" + dataInclusao
+ ", resultadoExameArquivos=" + resultadoExameArquivos + "]";
}
}
#Override
public List<ExameVO> listarExames(String cpf, String dtNascimento, Long tipoExame) throws WebServiceException {
List<ExameVO> examesVO = new ArrayList<ExameVO>();
try {
examesVO = exameDAO.listarExames(cpf, dtNascimento, tipoExame);
if(!examesVO.isEmpty()) {
for(ExameVO exameVO : examesVO) {
exameVO.setResultadoExameArquivos(new ArrayList<ExameArquivoVO>());
exameVO.getResultadoExameArquivos().addAll(exameDAO.listarExameArquivos(exameVO.getId()));
}
}
return examesVO;
} catch (Exception e) {
throw new WebServiceException(e);
}
}
Response to postman: Notice that there is 1 object that has 2 objects inside the file list and another object that has 1 and it returns as an object and not as a list with 1 object.

My List<Object> is not being passed correctly as object of my ModelAndView

In my Spring Controller I have:
List<User> Users = this.userService.UsersList();
mav = new ModelAndView("users");
mav.addObject("Users", Users);
When I iterate over Users I can see all the attributes values of every element of my list.
This is my .jsp code:
<c:forEach items="${Users}" var="usr">
${usr}
</c:forEach>
This is my users class:
#Entity
#Table(name="usuario")
public class User implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#JoinColumn(name = "id_perfil")
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Perfil perfil;
#Column(name="nombre")
private String nombre;
#Column(name="usuario")
private String usuario;
#Column(name="contrasenia")
private String contrasenia;
#Column(name="correo")
private String correo;
#Column(name="telefono")
private String telefono;
#Column(name="imagen_perfil")
private String imagen_perfil;
#Column(name="intento_fallido")
private int intento_fallido;
#Column(name="intranet_id")
private Integer intranet_id;
#Column(name="intranet_notaria")
private Integer intranet_notaria;
#Column(name="intranet_token_codigo")
private String intranet_token_codigo;
#Column(name="intranet_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date intranet_token_fecha;
#Column(name="tesoreria_token_codigo")
private String tesoreria_token_codigo;
#Column(name="tesoreria_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date tesoreria_token_fecha;
#Column(name="activo")
private int activo;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Perfil getPerfil() { return perfil; }
public void setPerfil(Perfil perfil) { this.perfil = perfil; }
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getUsuario() { return usuario; }
public void setUsuario(String usuario) { this.usuario = usuario; }
public String getContrasenia() { return contrasenia; }
public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getTelefono() { return telefono; }
public void setTelefono(String telefono) { this.telefono = telefono; }
public String getImagenPerfil() { return imagen_perfil; }
public void setImagenPerfil(String imagen_perfil) { this.imagen_perfil = imagen_perfil; }
public int getIntentoFallido() { return intento_fallido; }
public void setIntentoFallido(int intento_fallido) { this.intento_fallido = intento_fallido; }
public Integer getIntranetId() { return intranet_id; }
public void setIntranetId(Integer intranet_id) { this.intranet_id = intranet_id; }
public Integer getIntranetNotaria() { return intranet_notaria; }
public void setIntranetNotaria(Integer intranet_notaria) { this.intranet_notaria = intranet_notaria; }
public String getIntranetTokenCodigo() { return intranet_token_codigo; }
public void setIntranetTokenCodigo(String intranet_token_codigo) { this.intranet_token_codigo = intranet_token_codigo; }
public Date getIntranetTokenFecha() { return intranet_token_fecha; }
public void setIntranetTokenFecha(Date intranet_token_fecha) { this.intranet_token_fecha = intranet_token_fecha; }
public String getTesoreriaTokenCodigo() { return tesoreria_token_codigo; }
public void setTesoreriaTokenCodigo(String tesoreria_token_codigo) { this.tesoreria_token_codigo = tesoreria_token_codigo; }
public Date getTesoreriaTokenFecha() { return tesoreria_token_fecha; }
public void setTesoreriaTokenFecha(Date tesoreria_token_fecha) { this.tesoreria_token_fecha = tesoreria_token_fecha; }
public int getActivo() { return activo; }
public void setActivo(int activo) { this.activo = activo; }
#Override
public String toString() {
return "Id:" + id + ", " + "Perfil:" + perfil.getNombre() + ", " + "Id_Perfil:" + perfil.getId() + ", " + "Nombre:" + nombre + ", " + "Usuario:" + usuario + ", " + "Correo:" + correo + ", " + "Teléfono:" + telefono + ", " + "Image_Perfil:" + imagen_perfil + ", " + "Intranet_Id:" + intranet_id + ", " + "Intranet_Notaria:" + intranet_notaria + ", " + "Activo:" + activo;
}
}
The problem is that ${usr} is only displaying some of my attributes, but not all! I need to display all the attributes in my jsp.
Try using camelCase notation if you are not doing so. For example instead of ${usr.imagen_perfil} use ${usr.imagenPerfil}. I think it will be expecting to use the object getters getImagenPerfil().

what meaning this error "java.util.stream.ReferencePipeline$3 cannot be cast to org.springframework.data.domain.Page"

i want filter my task depend the work id
but when run my code i have this error
java.util.stream.ReferencePipeline$3 cannot be cast to org.springframework.data.domain.Page
how i can solve these
this is my component
my services here:
public Page<TaskDataDTO> findAll(String workOrderId,Pageable pageable) {
log.debug("Request to get all TaskData");
if(workOrderId!=null)
return (Page<TaskDataDTO>) taskDataRepository.findAll(pageable).stream().filter(x-> x.getWorkOrderId()==workOrderId).map(taskDataMapper::toDto);
else
return null;
}
and my Controller here :
#GetMapping("/task-data/{workOrderId}")
public ResponseEntity<List<TaskDataDTO>> getAllTaskData(#PathVariable String workOrderId,Pageable pageable) {
if(workOrderId!=null)
{
log.debug("REST request to get a page of TaskData");
Page<TaskDataDTO> page = taskDataService.findAll(workOrderId,pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
else {
return null;
}
}
the task entity :
package com.asc.skyalign.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.io.Serializable;
/**
* A TaskData.
*/
#Document(collection = "task_data")
public class TaskData implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String id;
#Field("roll")
private String roll;
#Field("azimuth")
private String azimuth;
#Field("tilt")
private String tilt;
#Field("sector_location_lat")
private String sectorLocationLat;
#Field("amt_imei")
private String amtImei;
#Field("wakeu_up_interval")
private String wakeuUpInterval;
#Field("sector_id")
private String sectorID;
#Field("sector_location_long")
private String sectorLocationLong;
#Field("task_name")
private String taskName;
#Field("task_description")
private String taskDescription;
#Field("work_order_id")
private String workOrderId;
private WorkOrder workOrder;
public void setWorkOrder(WorkOrder workOrder) {
this.workOrder = workOrder;
}
public WorkOrder getWorkOrder() {
return workOrder;
}
// jhipster-needle-entity-add-field - JHipster will add fields here
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRoll() {
return roll;
}
public TaskData roll(String roll) {
this.roll = roll;
return this;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getAzimuth() {
return azimuth;
}
public TaskData azimuth(String azimuth) {
this.azimuth = azimuth;
return this;
}
public void setAzimuth(String azimuth) {
this.azimuth = azimuth;
}
public String getTilt() {
return tilt;
}
public TaskData tilt(String tilt) {
this.tilt = tilt;
return this;
}
public void setTilt(String tilt) {
this.tilt = tilt;
}
public String getSectorLocationLat() {
return sectorLocationLat;
}
public TaskData sectorLocationLat(String sectorLocationLat) {
this.sectorLocationLat = sectorLocationLat;
return this;
}
public void setSectorLocationLat(String sectorLocationLat) {
this.sectorLocationLat = sectorLocationLat;
}
public String getAmtImei() {
return amtImei;
}
public TaskData amtImei(String amtImei) {
this.amtImei = amtImei;
return this;
}
public void setAmtImei(String amtImei) {
this.amtImei = amtImei;
}
public String getWakeuUpInterval() {
return wakeuUpInterval;
}
public TaskData wakeuUpInterval(String wakeuUpInterval) {
this.wakeuUpInterval = wakeuUpInterval;
return this;
}
public void setWakeuUpInterval(String wakeuUpInterval) {
this.wakeuUpInterval = wakeuUpInterval;
}
public String getSectorID() {
return sectorID;
}
public TaskData sectorID(String sectorID) {
this.sectorID = sectorID;
return this;
}
public void setSectorID(String sectorID) {
this.sectorID = sectorID;
}
public String getSectorLocationLong() {
return sectorLocationLong;
}
public TaskData sectorLocationLong(String sectorLocationLong) {
this.sectorLocationLong = sectorLocationLong;
return this;
}
public void setSectorLocationLong(String sectorLocationLong) {
this.sectorLocationLong = sectorLocationLong;
}
public String getTaskName() {
return taskName;
}
public TaskData taskName(String taskName) {
this.taskName = taskName;
return this;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskDescription() {
return taskDescription;
}
public TaskData taskDescription(String taskDescription) {
this.taskDescription = taskDescription;
return this;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getWorkOrderId() {
return workOrderId;
}
public TaskData workOrderId(String workOrderId) {
this.workOrderId = workOrderId;
return this;
}
public void setWorkOrderId(String workOrderId) {
this.workOrderId = workOrderId;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TaskData)) {
return false;
}
return id != null && id.equals(((TaskData) o).id);
}
#Override
public int hashCode() {
return 31;
}
// prettier-ignore
#Override
public String toString() {
return "TaskData{" +
"id=" + getId() +
", roll='" + getRoll() + "'" +
", azimuth='" + getAzimuth() + "'" +
", tilt='" + getTilt() + "'" +
", sectorLocationLat='" + getSectorLocationLat() + "'" +
", amtImei='" + getAmtImei() + "'" +
", wakeuUpInterval='" + getWakeuUpInterval() + "'" +
", sectorID='" + getSectorID() + "'" +
", sectorLocationLong='" + getSectorLocationLong() + "'" +
", taskName='" + getTaskName() + "'" +
", taskDescription='" + getTaskDescription() + "'" +
", workOrderId='" + getWorkOrderId() + "'" +
"}";
}
}
and the TaskDto is here:
package com.asc.skyalign.service.dto;
import java.io.Serializable;
/**
* A DTO for the {#link com.asc.skyalign.domain.TaskData} entity.
*/
public class TaskDataDTO implements Serializable {
private String id;
private String roll;
private String azimuth;
private String tilt;
private String sectorLocationLat;
private String amtImei;
private String wakeuUpInterval;
private String sectorID;
private String sectorLocationLong;
private String taskName;
private String taskDescription;
private String workOrderId;
private WorkOrderDTO workOrderDTO;
public void setWorkOrderDTO(WorkOrderDTO workOrderDTO) {
this.workOrderDTO = workOrderDTO;
}
public WorkOrderDTO getWorkOrderDTO() {
return workOrderDTO;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getAzimuth() {
return azimuth;
}
public void setAzimuth(String azimuth) {
this.azimuth = azimuth;
}
public String getTilt() {
return tilt;
}
public void setTilt(String tilt) {
this.tilt = tilt;
}
public String getSectorLocationLat() {
return sectorLocationLat;
}
public void setSectorLocationLat(String sectorLocationLat) {
this.sectorLocationLat = sectorLocationLat;
}
public String getAmtImei() {
return amtImei;
}
public void setAmtImei(String amtImei) {
this.amtImei = amtImei;
}
public String getWakeuUpInterval() {
return wakeuUpInterval;
}
public void setWakeuUpInterval(String wakeuUpInterval) {
this.wakeuUpInterval = wakeuUpInterval;
}
public String getSectorID() {
return sectorID;
}
public void setSectorID(String sectorID) {
this.sectorID = sectorID;
}
public String getSectorLocationLong() {
return sectorLocationLong;
}
public void setSectorLocationLong(String sectorLocationLong) {
this.sectorLocationLong = sectorLocationLong;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getWorkOrderId() {
return workOrderId;
}
public void setWorkOrderId(String workOrderId) {
this.workOrderId = workOrderId;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TaskDataDTO)) {
return false;
}
return id != null && id.equals(((TaskDataDTO) o).id);
}
#Override
public int hashCode() {
return 31;
}
// prettier-ignore
#Override
public String toString() {
return "TaskDataDTO{" +
"id=" + getId() +
", roll='" + getRoll() + "'" +
", azimuth='" + getAzimuth() + "'" +
", tilt='" + getTilt() + "'" +
", sectorLocationLat='" + getSectorLocationLat() + "'" +
", amtImei='" + getAmtImei() + "'" +
", wakeuUpInterval='" + getWakeuUpInterval() + "'" +
", sectorID='" + getSectorID() + "'" +
", sectorLocationLong='" + getSectorLocationLong() + "'" +
", taskName='" + getTaskName() + "'" +
", taskDescription='" + getTaskDescription() + "'" +
", workOrderId='" + getWorkOrderId() + "'" +
"}";
}
}
Thank you.
return (Page<TaskDataDTO>) taskDataRepository.findAll(pageable).stream().filter(x-> x.getWorkOrderId()==workOrderId).map(taskDataMapper::toDto);
The line above is missing a terminal operation to consume the stream. Try adding something like .collect(Collectors.toList())
Here's the package description for java.util.stream

parse json array with no name

I am trying to parse the JSON array and add it to my adapter class.
My code:
String url = "https://api.github.com/users";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray(); // error in this line since there is no array name
for(int i = 0;i < results.length();i++){
JSONObject result = results.getJSONObject(i);
String name = result.getString("login");
users.add(new User(name.substring(0,1).toUpperCase() + name.substring(1),result.getString("avatar_url")));
}
// notify that data has changed in recyclerview
notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Log.e("cs50", "Json error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50","Github User List error",error);
}
});
You can see that I'm trying to get a response from Github API URL but I'm getting error as there is no array name but my code requires a parameter. how can I parse it ?
Change this line
StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://api.github.com/users", response -> {
Log.d(TAG, "_ApiGetGithubUsers: " + response);
if (response != null && !response.isEmpty()) {
try {
JSONArray usersArray = new JSONArray(response);
for (int i = 0; i < usersArray.length(); i++) {
JSONObject user = usersArray.getJSONObject(i);
Log.d(TAG, "_ApiGetGithubUsers: "+user.getString("login"));
}
} catch (Exception e) {
Log.d(TAG, "_ApiGetGithubUsers: " + e);
Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();
}
} else
Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();
}, error -> {
});
AppController.getInstance().addToRequestQueue(stringRequest);
This is the method i used and it is working and parsing attaching the log image for reference.
I think you can use retrofit library, add the dependencies to app gradle.
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.5'
Create User Class to get Response.
public class User {
#SerializedName("login")
#Expose
private String login;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("node_id")
#Expose
private String nodeId;
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
#SerializedName("gravatar_id")
#Expose
private String gravatarId;
#SerializedName("url")
#Expose
private String url;
#SerializedName("html_url")
#Expose
private String htmlUrl;
#SerializedName("followers_url")
#Expose
private String followersUrl;
#SerializedName("following_url")
#Expose
private String followingUrl;
#SerializedName("gists_url")
#Expose
private String gistsUrl;
#SerializedName("starred_url")
#Expose
private String starredUrl;
#SerializedName("subscriptions_url")
#Expose
private String subscriptionsUrl;
#SerializedName("organizations_url")
#Expose
private String organizationsUrl;
#SerializedName("repos_url")
#Expose
private String reposUrl;
#SerializedName("events_url")
#Expose
private String eventsUrl;
#SerializedName("received_events_url")
#Expose
private String receivedEventsUrl;
#SerializedName("type")
#Expose
private String type;
#SerializedName("site_admin")
#Expose
private Boolean siteAdmin;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getGravatarId() {
return gravatarId;
}
public void setGravatarId(String gravatarId) {
this.gravatarId = gravatarId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHtmlUrl() {
return htmlUrl;
}
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
public String getFollowersUrl() {
return followersUrl;
}
public void setFollowersUrl(String followersUrl) {
this.followersUrl = followersUrl;
}
public String getFollowingUrl() {
return followingUrl;
}
public void setFollowingUrl(String followingUrl) {
this.followingUrl = followingUrl;
}
public String getGistsUrl() {
return gistsUrl;
}
public void setGistsUrl(String gistsUrl) {
this.gistsUrl = gistsUrl;
}
public String getStarredUrl() {
return starredUrl;
}
public void setStarredUrl(String starredUrl) {
this.starredUrl = starredUrl;
}
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
public void setSubscriptionsUrl(String subscriptionsUrl) {
this.subscriptionsUrl = subscriptionsUrl;
}
public String getOrganizationsUrl() {
return organizationsUrl;
}
public void setOrganizationsUrl(String organizationsUrl) {
this.organizationsUrl = organizationsUrl;
}
public String getReposUrl() {
return reposUrl;
}
public void setReposUrl(String reposUrl) {
this.reposUrl = reposUrl;
}
public String getEventsUrl() {
return eventsUrl;
}
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
public void setReceivedEventsUrl(String receivedEventsUrl) {
this.receivedEventsUrl = receivedEventsUrl;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getSiteAdmin() {
return siteAdmin;
}
public void setSiteAdmin(Boolean siteAdmin) {
this.siteAdmin = siteAdmin;
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", id=" + id +
", nodeId='" + nodeId + '\'' +
", avatarUrl='" + avatarUrl + '\'' +
", gravatarId='" + gravatarId + '\'' +
", url='" + url + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", followersUrl='" + followersUrl + '\'' +
", followingUrl='" + followingUrl + '\'' +
", gistsUrl='" + gistsUrl + '\'' +
", starredUrl='" + starredUrl + '\'' +
", subscriptionsUrl='" + subscriptionsUrl + '\'' +
", organizationsUrl='" + organizationsUrl + '\'' +
", reposUrl='" + reposUrl + '\'' +
", eventsUrl='" + eventsUrl + '\'' +
", receivedEventsUrl='" + receivedEventsUrl + '\'' +
", type='" + type + '\'' +
", siteAdmin=" + siteAdmin +
'}';
}
}
Create a API interface for endpoint URL.
public interface APIInterface {
#GET("/users")
Call<List<User>> getGitHubUser();
}
Create Retrofit API Client.
public class APIClient {
/**
* Get Retrofit Instance
*/
private static Retrofit getRetrofitInstance() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
return new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static APIInterface getApiInterface() {
return getRetrofitInstance().create(APIInterface.class);
}
}
Then Call the below method to get your parse data.
public void getUserList() {
APIInterface apiInterface=APIClient.getApiInterface();
Call<List<User>> call= apiInterface.getGitHubUser();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
List<User> userList= response.body();
System.out.println(userList);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
}

JPA 2.2: Using find method to retrieve data from mysqlDB

I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?

Categories

Resources