I'm using retrofit with gson in android, i'm following a tutorial so the guy on the tutorial make it work but i can't
it looks like my json data is lost when i call the retrofit method here are my call in android
ANDROID ACTIVITY.JAVA
public void addProspecto(Prospecto p){
prospectoService= Apis.getProspectoService();
Call<Prospecto>call=prospectoService.addProspecto(p);
call.enqueue(new Callback<Prospecto>() {
#Override
public void onResponse(Call<Prospecto> call, Response<Prospecto> response) {
if(response.isSuccessful()){
Toast.makeText(ProspectoActivity.this,"Se agrego con éxito",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Prospecto> call, Throwable t) {
Log.e("Error:",t.getMessage());
}
});
ANDROIDINTERFACE.JAVA
#POST("agregar")
Call<Prospecto>addProspecto(#Body Prospecto prospecto);
backend in springtools java
ProspectoController.java
#RestController
#RequestMapping("/prospectos")
public class ProspectoController {
#Autowired
private ProspectoService service;
#GetMapping("/listar")
public List<Map<String, Object>> listar(){
return service.listar();
}
#PostMapping("/agregar")
#ResponseBody
public String save(#RequestBody Prospecto p) {
System.out.println("#############################");
System.out.println(p.getNombre());
int id=service.add(p);
if(id==0) {
return "No se pudo Regsitrar!";
}
return "Se registró con éxito!";
}
Prospecto model.java
#Data
public class Prospecto {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ID;
private String nombre;
private String apPaterno;
private String apMaterno;
private String calle;
private String numero;
private String colonia;
private String cP;
private String telefono;
private String rFC;
private File documentos;
private String statusProspecto;
}
And for the last the repository or the file where i use the sql querys :
ProspectoDAO
#Repository
public class ProspectoDAO implements ProspectoInterface {
#Autowired
JdbcTemplate template;
#Override
public List<Map<String, Object>> listar() {
// TODO Auto-generated method stub
List<Map<String, Object>>lista=template.queryForList("Select * from prospectos");
return lista;
}
#Override
public List<Map<String, Object>> listar(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public int add(Prospecto p) {
String sql = "insert into prospectos(Nombre, apPaterno, apMaterno, Calle, Numero, Colonia, CP, Telefono, RFC, Documentos, statusProspecto)values(?,?,?,?,?,?,?,?,?,?,?)";
return template.update(sql,
p.getNombre(),
p.getApPaterno(),
p.getApMaterno(),
p.getCalle(),
p.getNumero(),
p.getColonia(),
p.getCP(),
p.getTelefono(),
p.getRFC(),
p.getDocumentos(),
p.getStatusProspecto()
);
}
Please help, i'm sending the object ''Prospecto'' with ''nombre'' and all the data needed for it and in my backend it stills says that i don't have the data
In my database the column ''nombre'' were ''Nombre'' with capitals so thats was all i guess. For anyone who have the same problem check the getters and setters and put it the same as they are in the columns database.
Related
findAll() of mongoRepository returns empty list. what is wrong with the below code?
API used for counting the number of documents in the collection works fine.
Controller
#RestController
#RequestMapping("/api/api-management/scopes")
public class AuthScopesController {
private final ScopesService scopesService;
#Autowired
AuthScopesController(ScopesService scopesService) {
this.scopesService = scopesService;
}
#PostMapping("/")
public AuthScope createScope(#RequestBody AuthScope authScope) {
return scopesService.createAuthScope(authScope);
}
#GetMapping("/")
public List<AuthScope> getAllScopes() {
return scopesService.getAuthScopes();
}
}
service
#Service
public class ScopesService {
private final AuthScopeRepository authScopeRepository;
public ScopesService(AuthScopeRepository authScopeRepository) {
this.authScopeRepository = authScopeRepository;
}
public AuthScope createAuthScope(AuthScope authScope) {
return authScopeRepository.save(authScope);
}
//TODO: recheck
public List<AuthScope> getAuthScopes() {
return authScopeRepository.findAll();
}
}
repository
#Repository
public interface AuthScopeRepository extends MongoRepository<AuthScope, String> {
Optional<AuthScope> findByScope(String id);
}
model is as follows
#Data
#Document("auth-scopes")
public class AuthScope {
#Id
private String scope;
private String belongsToApi;
private String belongsToApiTitle;
private String description;
}
found the issue. in order to findAll() to work, the model has to have deleted status.
I've updated the model as follows
#Data
#Document("auth-scopes")
public class AuthScope {
#Id
private String scope;
private String belongsToApi;
private String belongsToApiTitle;
private String description;
private boolean deleted;
}
I am developing an api using Springboot, which will check the DB and find all the email ids
in an action table and send alert emails.I could start the springboot applciation with no error. But when i send the http://localhost:8082/send-due-emails request in postman, I get the below error in the application
Cannot invoke "com.emailschedulerfinal.repository.EmailRepository.findDueEmails()" because "this.emailrepo" is null
The query I use is returning the results in DB. It has got two email ids in the results. Can you please help me with this issue? Anything wrong in the way I gave the query in the repository? Or any issue with the return statements here?
This is my Controller
#RestController
public class EmailController {
SchedulerService schedulerservice = new SchedulerService(null);
#RequestMapping("send-due-emails")
public String send() {
try {
schedulerservice.sendEmailIds();
} catch (MailException mailException) {
System.out.println(mailException);
}
return "Congratulations! Your mail has been sent to the user.";
}
}
This is my model
#Entity
#Table(name = "actionitems")
public class actionitems {
#Id
#GeneratedValue
private int id;
private String action;
private String email;
private Date duedate;
#getters and setters omitted here
}
This is my repository
public interface EmailRepository extends JpaRepository<actionitems, Long> {
#Query("select email from actionitems where duedate< CURRENT_TIMESTAMP")
public List<String[]> findDueEmails();
}
This is my service
public class SchedulerService {
private JavaMailSender javaMailSender;
#Autowired
EmailRepository emailrepo;
public SchedulerService(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public List<String[]> findDueEmailsFromDB() {
return emailrepo.findDueEmails();
}
public void sendEmailIds() {
List<String[]> To = findDueEmailsFromDB();
String k[] = To.toArray(new String[To.size()]);
System.out.println("The list obtained is " + k);
// Iterating over above string array
for (String str : k) {
// Printing the elements in above array
System.out.println(str);
}
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(k);
mailMessage.setSubject("sample subject");
mailMessage.setText("Sample text");
mailMessage.setFrom("test#gmail.com");
javaMailSender.send(mailMessage);
}
}
I got a workaround for this. Instead of using query annotations, if I write a utility class which connect to db and run the query and return the results, it is sending emails to all those email ids .But still I would like to know how to make the same work using #Query annotation in springboot.
public static Connection connect() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static ArrayList<String> getdueEmails() throws SQLException, ClassNotFoundException{
ArrayList<String> a = new ArrayList<String>();
Connection con = connect();
PreparedStatement ps = con.prepareStatement("select email from actionitems_final where duedate< CURRENT_TIMESTAMP");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
a.add(rs.getString(1));
}
return a;
}
This is my service
public void sendEmail() throws MailException, ClassNotFoundException, SQLException {
SQLhelper sqlhelper = new SQLhelper();
/*
* This JavaMailSender Interface is used to send Mail in Spring Boot. This
* JavaMailSender extends the MailSender Interface which contains send()
* function. SimpleMailMessage Object is required because send() function uses
* object of SimpleMailMessage as a Parameter
*/
List<String> To = sqlhelper.getdueEmails();
String k[] = To.toArray(new String[To.size()]);
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo(k);
mail.setSubject("Email to all persons having due date");
mail.setText("This is sent to all email ids corresponding to actions which are due today...");
/*
* This send() contains an Object of SimpleMailMessage as an Parameter
*/
javaMailSender.send(mail);
}
Finally I found the issue with my query annotation. Earlier both the model class name and my DB table name were the same. We have to use the model class name inside the query annoatation and not the db table name.
This is my repository
public interface EmailRepository extends JpaRepository<ActionItems, String> {
#Query("select email from ActionItems where duedate< CURRENT_TIMESTAMP")
List<String> finddueemailsfromdb();
}
This is my entity
#Entity
#Table(name = "actionitemsFinal")
public class ActionItems {
#Id
#GeneratedValue
private int id;
private String action;
private String email;
private Date duedate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDuedate() {
return duedate;
}
public void setDuedate(Date duedate) {
this.duedate = duedate;
}
}
This is my Service
List<String> To = emailrepo.finddueemailsfromdb();
String k[] = To.toArray(new String[To.size()]);
SimpleMailMessage mail = new SimpleMailMessage();
/* mail.setTo(actions.getEmailAddress()); */
mail.setTo(k);
......rest of the code omitted
I want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.
Hi I am new ElasticSearch, I am using spring data. I have 2 API which saves data in article and discourse model using elastic search, now when a client app makes a API call for both article and discourse search it gives all article first and then discourse data. but i want to randomize the response how can i do that?
my article model class as follows
#AllArgsConstructor
#Data
#Document(indexName="articles", createIndex=true)
public class Article implements ITResult {
private String id;
private String hostContentId;
private String title;
private List<String> categories;
private String searchResultId;
#Override
public String getSummary() {
return excerpt;
}
#Override
public ContentType getContentType() {
return ContentType.ARTICLE;
}
#Override
public String getHostContentId() {
return hostContentId;
}
#Override
public String getUrl() {
return link;
}
#Override
public String getSearchResultId() {
return searchResultId;
}
public void setSearchResultId(String searchResultId) {
this.searchResultId = searchResultId;
}
}
I have done the following
SearchQuery query = new NativeSearchQueryBuilder().withIndices("articles","course")
.withPageable(new PageRequest(offset,limit))
.withFilter(multiMatchQuery(string, new String[] { "title", "excerpt", "author_name", "link"}))
.build();
I am new in spring boot.I wanna upload a small file use spring boot and save it in db use jpa.
But I don't have good resolution.
My program like these:
database table:
CREATE TABLE `report` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`logo` BLOB NOT NULL,
`created_time` int(10) NOT NULL,
`updated_time` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
jpa bean:
Report.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="mf_report")
public class Report implements Serializable{
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Lob
#Column(name="logo", length=100000)
private byte[] logo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getLogo() {
return logo;
}
public void setLogo(byte[] logo) {
this.logo = logo;
}
}
ReportReposity.java:
#Repository
public interface ReportRepository extends CrudRepository<Report,Long>{
}
ReportService.java:
#Service
public class ReportService extends CrudService<Report, ReportRepository> {
private final static Logger logger = LoggerFactory.getLogger(ReportService.class);
#Override
#Autowired
public void setRepo(ReportRepository repo) {
this.repo = repo;
}
#Override
public Report copy(Report from, Report to) {
to = from;
return to;
}
#Autowired
private ReportRepository reportRepository;
public boolean saveReportByRequestBean(ReportAddQueryRequest reportBeanQueryRequest){
try {
Report report = new Report();
report.setName(reportBeanQueryRequest.getName());
report.setLogo(reportBeanQueryRequest.getLogo());
long now = System.currentTimeMillis()/1000;
report.setCreateTime(now);
report.setUpdateTime(now);
this.save(report);
}catch (Exception e){
logger.error("save report error:", e);
return false;
}
return true;
}
}
ReportParamBean.java:
import org.hibernate.validator.constraints.NotEmpty;
import java.io.Serializable;
public class ReportParamBean extends AbsRequest implements Serializable {
private long reportId;
#NotEmpty(message = "Param 'name' can't be NULL")
private String name;
private String logo;// In fact, I don't know what type should logo be, File or ?
}
AbsRequest.java:
public class AbsRequest implements Serializable {
private static final long serialVersionUID = -8928786145900600868L;
#NotEmpty(message = "Param 'token' can't be NULL")
#NotNull
private String token;
#NotEmpty(message = "Param 'sign' can't be NULL")
private String sign;
#Min(value = 1, message = "Param 'time' is invalid")
private Long time;
#Min(value = -1, message = "Param 'nodeId' is invalid")
#NotNull(message = "Param 'nodeId' can't be NULL")
private Long nodeId;
private String nodeName;
#Override
public String toString() {
return new ToStringBuilder(this)
.append("token", token)
.append("sign", sign)
.append("time", time)
.append("nodeId", nodeId)
.append("nodeName", nodeName)
.toString();
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}
ReportController.java:
#RestController
#RequestMapping("/api")
public class ReportController {
#Autowired
private ReportService reportService;
#RequestMapping(value = "/report", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public JSONObject createReport(#RequestBody ReportAddQueryRequest reportBeanQueryRequest){
boolean result = reportService.saveReportByRequestBean(reportBeanQueryRequest);
if (!result){
return ResponseWrapper.buildResponse(RTCodeEnum.C_SERVICE_NOT_AVAILABLE, "add report failed");
}
return ResponseWrapper.buildResponse(RTCodeEnum.C_OK, "add report success");
}
}
I don't know whether I can post a file and other params to server in just one post request,then save the data in db.Could you give me resolution.
Special thanks.
Use Spring's multipart file. In simple implementation you can then get InputStream from it, read the content of the file (being saved on hdd) to a byte array and save it to database.
Consider up voting if this answer help you.
suppose you want to upload a file's data to database then you could do it in two steps:
upload your file as multipart file in your controller class.
#PostMapping("/uploadYourFile")
public String uploadFile( MultipartFile file) throws IOException {
FileInputStream inputStream = (FileInputStream) file.getInputStream();
//you can use inputStream object which currently has your "file" data
// you can process this to fetch your data.
return "file uploaded successfully ";
}
Read your uploaded file"inputStream" fetch the data and insert it into your DB through your db query
I have made an app to upload, download and delete files to/from database using Spring Boot Rest APIs. I also used Spring Web MultipartFile interface to handle HTTP multi-part requests.
Source code: https://github.com/OusamaELIDRISSI/upload-files-database
Happy coding 🙂