I have a search method in the database that brings me the following result:
As you see that inside the Object [4] comes another array containing People, Pessoas, and PessoasEnderecos and more objects that have relantionship with Pessoas.
I would like it to return only this way and not inside another array as it is happening now, it should look like this:
elementData=Object[10](id=144)
[0]=Pessoas(id=166)
[1]=PessoasEnderecos(id=167)
...
i have this method:
#RequestMapping(method = RequestMethod.GET, value = "/pessoas")
public ResponseEntity<Collection<Pessoas>> buscarPessoas(HttpServletRequest request) throws Exception {
String idEntidadeCrypt = request.getHeader("DataBase");
Long idEntidade = Long.parseLong(Crypto.decode(idEntidadeCrypt));
Collection<Pessoas> pessoasBuscados = pessoasService.buscarFiltro(idEntidade);
return new ResponseEntity<>(pessoasBuscados, HttpStatus.OK);
}
and :
#Repository
public interface PessoasRepository extends JpaRepository<Pessoas, Integer> {
#Query( value="select pes, pEnd, pFis, pJur "
+ "from "
+ "Pessoas pes, "
+ "PessoasEnderecos pEnd,"
+ "PessoasFisicas pFis,"
+ "PessoasJuridicas pJur"
+ " where "
+ "pes.entidade.idEntidade = pEnd.entidade.idEntidade "
+ "and pes.idPessoa = pEnd.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pFis.entidade.idEntidade "
+ "and pes.idPessoa = pFis.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pJur.entidade.idEntidade "
+ "and pes.idPessoa = pJur.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = :parametroId " )
public Collection<Pessoas> encontrar(#Param("parametroId") Long usuarioEntidade);
how can i solve that ?
ArrayList<> does not work with magic, it has an actual implementation. elementData is the array where it stores its elements. As you can see (that is a link in the previous sentence), it is a private member of the class, so you do not interact with it, but you see it in a debugger because it exists.
If you want to return an array instead of a List, you can always use toArray() which all Lists implement.
Related
I'm trying to filter a table called Measure through its field customerId. This is what the beginning of the controller for the path looks like:
#RequestMapping(method = GET, path = "/nodes/{id}/ports/{portid}/measures")
#ResponseBody
public ResponseEntity<?> getPortMeasures(#PathVariable long id, #PathVariable long portid,
#RequestParam Optional<Long> from,
#RequestParam Optional<String> order,
#RequestParam Optional<String> countername,
#RequestParam Optional<Long> to) {
Followed by the method that calls the query undernath
if (order.isPresent() && order.get().equals("asc")) {
return ResponseRestBuilder.createSuccessResponse(
measureRepository.
searchAsc
(networkElementList.get(0).ip, portList.get(0).rack, portList.get(0).frame, portList.get(0).slot,
portList.get(0).portSerial, countername.get(), from.orElse(0L), to.orElse(99999999999999999L)));
}
else{
return ResponseRestBuilder.createSuccessResponse(
measureRepository.
searchDesc
(networkElementList.get(0).ip, portList.get(0).rack, portList.get(0).frame, portList.get(0).slot,
portList.get(0).portSerial, countername.get(), from.orElse(0L), to.orElse(99999999999999999L)));
}
This is what the queries look like:
#Query("SELECT mes FROM Measure mes WHERE " +
"mes.nodeIp = (:nodeIp) AND " +
"mes.rack = (:rack) AND " +
"mes.frame = (:frame) AND " +
"mes.slot = (:slot) AND " +
"mes.portSerial = (:portSerial) AND " +
"lower(mes.counterName) LIKE concat('%', lower(:countername), '%') AND"+
"mes.timestamp > (:timestamp1) AND " +
"mes.timestamp < (:timestamp2) "+
"ORDER BY mes.timestamp DESC")
List<Measure> searchDesc(#Param("nodeIp") String nodeIp, #Param("rack") String rack, #Param("frame") String frame,
#Param("slot") String slot, #Param("portSerial") String portSerial, #Param("countername") String countername,
#Param("timestamp1") Long timestamp1, #Param("timestamp2") Long timestamp2);
#Query("SELECT mes FROM Measure mes WHERE " +
"mes.nodeIp = :nodeIp AND " +
"mes.rack = :rack AND " +
"mes.frame = :frame AND " +
"mes.slot = :slot AND " +
"mes.portSerial = :portSerial AND " +
"lower(mes.counterName) LIKE concat('%', lower(:countername), '%') AND " +
"mes.timestamp > :timestamp1 AND " +
"mes.timestamp < :timestamp2 "+
"ORDER BY mes.timestamp ASC")
List<Measure> searchAsc(#Param("nodeIp") String nodeIp, #Param("rack") String rack, #Param("frame") String frame,
#Param("slot") String slot, #Param("portSerial") String portSerial, #Param("countername") String countername,
#Param("timestamp1") Long timestamp1, #Param("timestamp2") Long timestamp2);
It's not filtering anything because the controller replies with 0 rows. I'm 100% confident there are actual rows because I've checked with other rest calls. What am I doing wrong?
EDIT: debug
Most probably the issue is with the timestamp field ,it seems from the code that you are passing a long, but actually it's waiting for a timestamp literal , timestamp literal in jpa is in the format {ts '2009-11-05 12-45-52.325'} ... just to check , try removing the timestamp from the query then put it again and provide the literals manually ... if it works, you then need to find a way to parse the passed long to the corresponding literal
The problem with it was the field portList.get(0).rack being "null". Appartently this made the whole query not work.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So for example I have this class that outputs my detailed flight output that is in the java doc "Flight.java" :
public String toDetailedString() {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
and I have an Itinerary class "Itinerary.java" and I want to pull the info from Flight.java without making toDetailedString static, is that possible?
For added info, each of the variables you see "source, number, destination" are all private variables in Flight.java which I know are enclosed encapsulation. Any help is greatly valuable.
Example implementation in Itinerary.java
public String toString() {
return "The total cost is" + getTotalCost() + Flight.toDetailedString();
}
UPDATE:
In my Flight constructor I have:
public Flight(Plane plane, String number, double cost, Time departure, int duration, Airport source, Airport destination) {
this.plane = plane;
this.number = number;
this.cost = cost;
this.departure = departure;
this.duration = duration;
this.source = source;
this.destination = destination;
}
In which I created the object "f1" in my ItineraryTest class:
Flight f1 = new Flight(new Plane(Airline.American, "Airbus A321"),
"495",
79,
new Time(7, 10), 100,
Airport.PHX, Airport.LAX);
Thus I linked my object to the toDetailedString() the object "f1" was renamed to "first" in my Itinerary.java and a second object was created called "f2" and moved to "second" (to avoid confusion) :
public String toString() {
return "The total cost: "
+ getTotalCost()
+ " "
+ first.toDetailedString()
+ second.toDetailedString();
}
I thought I answered my own question, but now receive an error of:
Exception in thread "main" java.lang.NullPointerException at
Itinerary.toString(Itinerary.java:117) at
java.lang.String.valueOf(String.java:2994) at
java.io.PrintStream.println(PrintStream.java:821) at
ItineraryTest.main(ItineraryTest.java:20)
Possible, clean option is creating another class named FlightToDetailedString, with (possibly static) method toDetailedString. That method would accept instance of Flight as parameter
class FlightToDetailedString {
public String toDetailedString(Flight flight) {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
}
In my example method is not static. With non-static member mehod, FlightToDetailedString could have (and use in toDetailedString) fields of FlightToDetailedString class. For example, Airport could be member variable of FlightToDetailedString. Are you sure you want to limit yourself to one airport?
Why you do not like toDetailedString as non-static member of Flight class in first place? In example you give it is most natural solution. if your Itinerary needs to access details of Flight class, just pass instance of Flight object as argument!
The consumer of toDetailedString() doesn't need access to anything inside Flight.
Your NullPointerException is likely caused by one of the fields in the Flight instance being null.
Finally, consider using a StringBuilder instead of concatenating strings.
Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.
I want some help to find a quick solution for my problem. Given a json object that is large with a recursive model. I want to list the JSON sub elements & its immediate parent Object( only the sub object which satisfies the given key value condition).
Ex :
{
Object : {
id : "0001",
parent:"A",
child: {
id:"0001A",
Country:"US",
parent:"B",
child:{
id:"0001AA",
Country:"UK",
parent:"C",
child:{
id:"0000AAA",
Country:"US",
parent:"D",
child:{
.........
}
}
}
}
}
}
I want to list the id's of the subObject whose country is 'US' and it's parent id..
is there available any readymade plugins to handle these kind of scenarios in JAVA , without using object mappers/custom class objects..
Ps provide any possible idea ..
Yes, it is possible write code using the Jackson Tree Model API which would traverse a JSON tree and select the nodes that satisfy criteria. Here is an example:
public class JacksonTree2 {
public static final String JSON = "{\"Ex\" : {\"Object\" : {\n" +
" \"id\" : \"0001\",\n" +
" \"parent\":\"A\",\n" +
" \"child\": {\n" +
" \"id\":\"0001A\",\n" +
" \"Country\":\"US\",\n" +
" \"parent\":\"B\",\n" +
" \"child\":{\n" +
" \"id\":\"0001AA\",\n" +
" \"Country\":\"UK\",\n" +
" \"parent\":\"C\",\n" +
" \"child\":{\n" +
" \"id\":\"0000AAA\",\n" +
" \"Country\":\"US\",\n" +
" \"parent\":\"D\",\n" +
" \"child\":{\n" +
" \n" +
" }\n" +
" }\n" +
" }\n" +
"\t}\n" +
"}}}";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(JSON);
for (JsonNode node : root.findParents("Country")) {
if ("UK".equals(node.get("Country").asText())) {
System.out.println(node.get("id"));
break;
}
}
}
}
Output:
"0001AA"
How to write test cases for the class below. It checks for values of the given query in a database.
public class DboQueryCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Start DboDaoService");
DboDaoService dboDaoServcice = new DboDaoService();
dboDaoServcice.build();
String query = " select o.org_name, l.organization_id from " +
" code_value cv,code_value cv_loc,code_value_outbound cvo,location l,organization o" +
" where " +
" (cv.cdf_meaning = 'INGENI' or cv.cdf_meaning = 'MEDNEC')" +
" and cvo.contributor_source_cd = cv.code_value" +
" and cvo.alias_type_meaning = 'FACILITY'" +
" and l.location_cd = cvo.code_value" +
" and cv_loc.code_value = l.location_cd" +
" and cv_loc.code_set = 220" +
" and o.organization_id = l.organization_id" +
" order by o.org_name, cv_loc.display, cv.cdf_meaning";
System.out.println();
dboDaoServcice.report(query);
}
}
You don't. In your example, you are testing more than just a unit. Therefor, by definition, you cannot 'unit' test this. If you want to test this, at least consider using DBUnit or an in memory database like H2/HSQLDB database.
Alternatively, you could test the generated SQL commands, but I wonder what the value of that would be.