Essentially, this is the kind of data I want returned:
{
"Top10BidAsks":[
{
"Bid":{
"Price":10.0,
"Size":2.0,
"ExchangeID":"SMART",
"timeStamp":0
},
"Ask":{
"Price":12.0,
"Size":2.0,
"ExchangeID":"SMART",
"timeStamp":0
}
},
{
"Bid":{
"Price":0.0,
"Size":0.0,
"ExchangeID":"SMART",
"timeStamp":0
},
"Ask":{
"Price":13.0,
"Size":12.0,
"ExchangeID":"SMART",
"timeStamp":0
}
}
]
}
The {"Price":10.0,"Size":2.0,"ExchangeID":"SMART","timeStamp":0}, essentially represents a MarketData Object that I've created with those 4 fields.
The main function I'm calling is:
public MarketDataListLevel2 getMarketDataDepth() {
try {
MarketDataListLevel2 md = cs.getMarketDataDepth();
log.info(md.toString());
return md;
}
catch ( Exception e) {
....
}
}
Where cs is just an interface that retrieves the JSON data from a site.
The MarketDataLevel2 object is:
public class MarketDataListLevel2 {
public static class MarketDataList {
public MarketData[] a;
}
public MarketDataList[] listofmarketdatalists;
public MarketDataListLevel2(#JsonProperty("Top10BidAsks") MarketDataList[] listofmarketdatalists) {
this.listofmarketdatalists = listofmarketdatalists;
}
I tried to make this object match the output I want (formatting wise), but apparently I might have a data structure error here, because I'm not getting the data I want returned.
When I run the first method that I listed:
MarketDataListLevel2 a = getDepthMarketData(coin);
When I debug this 'a' object, I see that each element in the listofmarketdatalists array is 'null'
instead of containing an object with this format: {"Bid":{"Price":10.0,"Size":2.0,"ExchangeID":"SMART","timeStamp":0},
"Ask":{"Price":12.0,"Size":2.0,"ExchangeID":"SMART","timeStamp":0}}.
Any advice would be awesome.
You have to create correct POJO classes which represent your JSON. See below example:
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(json, Root.class);
System.out.println(root.getTop10());
}
}
class Root {
#JsonProperty("Top10BidAsks")
private List<MarketDataEntity> top10;
public List<MarketDataEntity> getTop10() {
return top10;
}
public void setTop10(List<MarketDataEntity> top10) {
this.top10 = top10;
}
}
class MarketDataEntity {
private Map<String, MarketData> datas = new HashMap<String, MarketData>();
#JsonAnySetter
public void setMarketData(String key, MarketData data) {
datas.put(key, data);
}
#Override
public String toString() {
return datas.toString();
}
}
class MarketData {
#JsonProperty("Price")
private BigDecimal price;
#JsonProperty("Size")
private BigDecimal size;
#JsonProperty("ExchangeID")
private String exchangeId;
private int timeStamp;
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getSize() {
return size;
}
public void setSize(BigDecimal size) {
this.size = size;
}
public String getExchangeId() {
return exchangeId;
}
public void setExchangeId(String exchangeId) {
this.exchangeId = exchangeId;
}
public int getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(int timeStamp) {
this.timeStamp = timeStamp;
}
#Override
public String toString() {
return "MarketData [price=" + price + ", size=" + size + ", exchangeId=" + exchangeId + ", timeStamp=" + timeStamp + "]";
}
}
Above program prints:
[{Bid=MarketData [price=10.0, size=2.0, exchangeId=SMART, timeStamp=0], Ask=MarketData [price=12.0, size=2.0, exchangeId=SMART, timeStamp=0]}, {Bid=MarketData [price=0.0, size=0.0, exchangeId=SMART, timeStamp=0], Ask=MarketData [price=13.0, size=12.0, exchangeId=SMART, timeStamp=0]}]
Related
I have a simple pizza program in Java, made using the Factory Pattern.
Basically, when a factory is given as a parameter, it creates a particular pizza, which is then added to the list of pizzas of the PizzaShop.
I would like to create a method that displays how many particular pizzas I have. For instance, when the method is called, I would like it to display something like "We have 5 PizzaChicago and 3 PizzaNewYork". I am not sure how to do that.
This is my code.
public interface Pizza {
String name();
}
public class PizzaChicago implements Pizza{
public Integer price;
public PizzaChicago(Integer price){
this.price = price;
}
#Override
public String name() {
return this.getClass().getSimpleName();
}
}
public class PizzaNewYork implements Pizza{
public Integer price;
public PizzaNewYork(Integer price){
this.price = price;
}
#Override
public String name() {
return this.getClass().getSimpleName();
}
}
public interface PizzaFactory {
public Pizza createPizza(Integer price);
}
public class PizzaNewYorkFactory implements PizzaFactory{
#Override
public Pizza createPizza(Integer price) {
return new PizzaNewYork(6);
}
}
public class PizzaChicagoFactory implements PizzaFactory{
#Override
public Pizza createPizza(Integer price) {
return new PizzaChicago(8);
}
}
import java.util.ArrayList;
import java.util.List;
public class PizzaShop {
List<Pizza> pizzaList = new ArrayList<>();
public void createPizza(PizzaFactory factory, Integer price){
Pizza pizza = factory.createPizza(price);
System.out.println(pizza.name() + " " + "was created");
pizzaList.add(pizza);
}
}
`
What you have to do is iterate the list and check what is the type of every object.
int countPizzaNewYork = 0, countPizzaChicago = 0;
for(Pizza p: pizzaList){
if(p instanceOf PizzaNewYork)
{
countPizzaNewYork++;
}
else
{
countPizzaChicago++;
}
}
System.out.println("We have "+ countPizzaChicago+" PizzaChicago and "+countPizzaNewYork+" PizzaNewYork");
Alternate approach (use Map instead of a List):
public class PizzaShop {
Map<String, Integer> pizzaDiary = new HashMap<>();
public void createPizza(PizzaFactory factory, Integer price) {
Pizza pizza = factory.createPizza(price);
System.out.println(pizza.name() + " " + "was created");
int previousCount = pizzaDiary.getOrDefault(pizza.name(), 0);
pizzaDiary.put(pizza.name(), previousCount + 1);
}
}
Use the pizzaDiary map to print out your pizza counts.
Having a separate class for each pizza could be problematic and somewhat cumbersome. And for certain using the class name and instanceof is not the way to go. Have you considered using an Enum to represent the Pizzas? Here is an example of how it might work.
public class PizzaShopDemo {
enum Pizza {
CHICAGOPIZZA(8, "Chicago Pizza"),
NEWYORKPIZZA(6, "New York Pizza");
private double price;
private String name;
private int count = 0;
private Pizza(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public void update() {
count++;
}
public int getCount() {
return count;
}
}
public static void main(String[] args) {
new PizzaShopDemo().pizzaShop();
}
public void pizzaShop() {
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.CHICAGOPIZZA);
createPizza(Pizza.NEWYORKPIZZA);
for (Pizza p : Pizza.values()) {
System.out.println(p.getName() + ", " + p.getPrice()
+ ", " + p.getCount());
}
}
public void createPizza(Pizza type) {
type.update();
// other stuff here.
}
}
Prints
Chicago Pizza, 8.0, 4
New York Pizza, 6.0, 3
I am working on modeling several java objects that manage entities in a mySQL database using the JDBCTemplate.
I have run Add/Get JUnit tests on two other objects and I am not getting any errors, but I cannot figure out what is causing this error for my 'Organization' object.
Here is my 'Organization' dto code:
package com.sg.superherosightings.model;
import java.util.Objects;
public class Organization {
private int orgId;
private String orgName;
private String orgDescription;
private String orgPhone;
private String orgEmail;
private String orgStreetAddress;
private String orgCity;
private String orgState;
private String orgZipCode;
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getOrgDescription() {
return orgDescription;
}
public void setOrgDescription(String orgDescription) {
this.orgDescription = orgDescription;
}
public String getOrgPhone() {
return orgPhone;
}
public void setOrgPhone(String orgPhone) {
this.orgPhone = orgPhone;
}
public String getOrgEmail() {
return orgEmail;
}
public void setOrgEmail(String orgEmail) {
this.orgEmail = orgEmail;
}
public String getOrgStreetAddress() {
return orgStreetAddress;
}
public void setOrgStreetAddress(String orgStreetAddress) {
this.orgStreetAddress = orgStreetAddress;
}
public String getOrgCity() {
return orgCity;
}
public void setOrgCity(String orgCity) {
this.orgCity = orgCity;
}
public String getOrgState() {
return orgState;
}
public void setOrgState(String orgState) {
this.orgState = orgState;
}
public String getOrgZipCode() {
return orgZipCode;
}
public void setOrgZipCode(String orgZipCode) {
this.orgZipCode = orgZipCode;
}
#Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.orgId;
hash = 89 * hash + Objects.hashCode(this.orgName);
hash = 89 * hash + Objects.hashCode(this.orgDescription);
hash = 89 * hash + Objects.hashCode(this.orgPhone);
hash = 89 * hash + Objects.hashCode(this.orgEmail);
hash = 89 * hash + Objects.hashCode(this.orgStreetAddress);
hash = 89 * hash + Objects.hashCode(this.orgCity);
hash = 89 * hash + Objects.hashCode(this.orgState);
hash = 89 * hash + Objects.hashCode(this.orgZipCode);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Organization other = (Organization) obj;
if (this.orgId != other.orgId) {
return false;
}
if (!Objects.equals(this.orgName, other.orgName)) {
return false;
}
if (!Objects.equals(this.orgDescription, other.orgDescription)) {
return false;
}
if (!Objects.equals(this.orgPhone, other.orgPhone)) {
return false;
}
if (!Objects.equals(this.orgEmail, other.orgEmail)) {
return false;
}
if (!Objects.equals(this.orgStreetAddress, other.orgStreetAddress)) {
return false;
}
if (!Objects.equals(this.orgCity, other.orgCity)) {
return false;
}
if (!Objects.equals(this.orgState, other.orgState)) {
return false;
}
if (!Objects.equals(this.orgZipCode, other.orgZipCode)) {
return false;
}
return true;
}
}
Here is my Mapper Method in my DaoDBImpl:
img of OrgMapper Method before fix
This is my SuperSightings_DaoTest method causing the error:
package com.sg.superherosightings.dao;
import com.sg.superherosightings.model.Location;
import com.sg.superherosightings.model.Organization;
import com.sg.superherosightings.model.Power;
import com.sg.superherosightings.model.Sighting;
import com.sg.superherosightings.model.Supe;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SuperSightings_DaoTest {
SuperSightings_Dao dao;
public SuperSightings_DaoTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
ApplicationContext ctx
= new ClassPathXmlApplicationContext("test-applicationContext.xml");
dao = ctx.getBean("SuperSightings_Dao", SuperSightings_Dao.class);
// delete all supes
List<Supe> supes = dao.getAllSupes(); for (Supe currentSupe : supes) {
dao.deleteSupe(currentSupe.getSupeId());
}
// delete all powers
List<Power> powers = dao.getAllPowers(); for (Power currentPower : powers) {
dao.deletePower(currentPower.getPowerId());
}
//delete all organizations
List<Organization> orgs = dao.getAllOrganizations(); for (Organization currentOrg : orgs) {
dao.deleteOrganization(currentOrg.getOrgId());
}
// delete all locations
List<Location> locations = dao.getAllLocations(); for (Location currentLocation : locations) {
dao.deleteLocation(currentLocation.getLocationId());
}
// delete all sightings
List<Sighting> sightings = dao.getAllSightings(); for (Sighting currentSighting : sightings) {
dao.deleteSighting(currentSighting.getSightingId());
}
}
#After
public void tearDown() {
}
/**
* Test of addPower method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetPower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
}
/**
* Test of deletePower method, of class SuperSightings_Dao.
*/
#Test
public void testDeletePower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
dao.deletePower(power.getPowerId());
assertNull(dao.getPowerById(power.getPowerId()));
}
/**
* Test of getAllPowersBySupeId method, of class SuperSightings_Dao.
*/
#Test
public void testGetAllPowersBySupeId() {
}
/**
* Test of addOrganization method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetOrganization() {
Organization org = new Organization();
org.setOrgName("Legion of Doom");
org.setOrgDescription("evil organization");
org.setOrgPhone("333-444-5678");
org.setOrgEmail("lod#evil.org");
org.setOrgStreetAddress("344 Lowland Blvd.");
org.setOrgCity("Quahog");
org.setOrgState("RI");
org.setOrgZipCode("09678");
dao.addOrganization(org);
Organization fromDao = dao.getOrganizationById(org.getOrgId());
assertEquals(fromDao, org); //this is the line causing the error
}
This is the error I am getting:
testAddGetOrganization(com.sg.superherosightings.dao.SuperSightings_DaoTest)
Time elapsed: 0.107 sec <<< FAILURE! java.lang.AssertionError:
expected:com.sg.superherosightings.model.Organization#ae511546 but
was:com.sg.superherosightings.model.Organization#15fabf0f
Please let me know if I need to provide further information. i am trying to get better at how i post questions here. I searched for a long time before asking but all I can find is that it might be something with my equals/hash code. I'm just not sure what is getting changed when the comparison is made because it is not happening with my other objects.
Thank you for any hints, and please don't bite my head off!
It seems some fields are not equal. try to compare all fields one by one to identify non-equal fields: assertEquals(fromDao.getOrgId(), org.getOrgId() and all the rest of organization's fields)
Thank you all for your assistance! I was able to convert my org and fromDao objects to string to see them in the test window. The problem was with my Mapper method for the Organization object. See original and the fix below:
Original Version
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_street_address")); //wrong field
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}
}
Fixed OrgMapper:
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_email"));
org.setOrgStreetAddress(rs.getString("org_street_address"));
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}
I'm trying to convert a JSON object to POJOs, and ideally I would have a list of objects (of collection's) in my cluster object. However the JSON schema doesn't use a list, it uses a map of the collection name, which aren't known and might change. Is there a way to convert this to a list of POJOs using GSON?
The JSON in question:
{
"responseHeader":{
"status":0,
"QTime":333},
"cluster":{
"collections":{
"collection1":{
"shards":{
"shard1":{
"range":"80000000-ffffffff",
"state":"active",
"replicas":{
"core_node1":{
"state":"active",
"core":"collection1",
"node_name":"127.0.1.1:8983_solr",
"base_url":"http://127.0.1.1:8983/solr",
"leader":"true"},
"core_node3":{
"state":"active",
"core":"collection1",
"node_name":"127.0.1.1:8900_solr",
"base_url":"http://127.0.1.1:8900/solr"}}},
"shard2":{
"range":"0-7fffffff",
"state":"active",
"replicas":{
"core_node2":{
"state":"active",
"core":"collection1",
"node_name":"127.0.1.1:7574_solr",
"base_url":"http://127.0.1.1:7574/solr",
"leader":"true"},
"core_node4":{
"state":"active",
"core":"collection1",
"node_name":"127.0.1.1:7500_solr",
"base_url":"http://127.0.1.1:7500/solr"}}}},
"maxShardsPerNode":"1",
"router":{"name":"compositeId"},
"replicationFactor":"1",
"znodeVersion": 11,
"autoCreated":"true",
"configName" : "my_config",
"aliases":["both_collections"]
}
},
"aliases":{ "both_collections":"collection1,collection2" },
"roles":{
"overseer":[
"127.0.1.1:8983_solr",
"127.0.1.1:7574_solr"]
},
"live_nodes":[
"127.0.1.1:7574_solr",
"127.0.1.1:7500_solr",
"127.0.1.1:8983_solr",
"127.0.1.1:8900_solr"]
}
}
I recommend you could build the POJO models, and then do the conversion after you have imported the data.
stackoverflow/model/CoreNode.java:
package stackoverflow.model;
/**
* CoreNode
*/
public class CoreNode {
private String state;
private boolean leader;
private String core;
private String node_name;
private String base_url;
public CoreNode() {
super();
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public boolean getLeader() {
return this.leader;
}
public void isLeader(boolean leader) {
this.leader = leader;
}
public String getCore() {
return this.core;
}
public void setCore(String core) {
this.core = core;
}
public String getNode_name() {
return this.node_name;
}
public void setNode_name(String node_name) {
this.node_name = node_name;
}
public String getBase_url() {
return this.base_url;
}
public void setBase_url(String base_url) {
this.base_url = base_url;
}
}
stackoverflow/model/Shard.java:
package stackoverflow.model;
import java.util.Map;
/**
* Shard
*/
public class Shard {
private String range;
private String state;
private Map<String, CoreNode> replicas;
public Shard() {
super();
}
public String getRange() {
return this.range;
}
public void setRange(String range) {
this.range = range;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<CoreNode> getReplicas() {
return this.replicas;
}
public void setReplicas(List<CoreNode> replicas) {
this.replicas = replicas;
}
}
then in your main function, use a Map<String, Shard> structure for each collection. (and then a Map<String, Map<String, Shard>> for the genericcollections` structure)
Then, whichever map you wanted as a list, you can just do (in the case of Shards)
new ArrayList<CoreNode>(replicas.values());
You might use a TypeAdapter to have your object converted to a list of objects, or just get all objects inside cluster into a JsonArray and then parse it to a List<Collection>, something like this:
JsonArray jsonArr = new JsonArray();
JsonObject fullObj = new GsonBuilder().create().fromJson(jsonStr, JsonObject.class);
fullObj.getAsJsonObject("cluster")
.entrySet()
.forEach(col -> jsonArr.add(col.getValue()));
List<Collection> collections = gson.fromJson(jsonArr.toString(), Collection.class);
Hello I just want to ask how should i get the codes function into a method which is run by the main at the moment! Basically so that I can activate the working method from the main instead. I am new to programming so I am having quite a bit of trouble grasping everything properly
package bla_bla;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import javax.swing.text.html.parser.Element;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator.Id;
import org.json.*;
import argo.saj.InvalidSyntaxException;
public class supermonkey {
private static ArrayList<BugsList> bugsList;
private static ArrayList<BugsList> bugbug;
public static void main(String args[]) throws IOException {
bugsList = new ArrayList<BugsList>();
bugbug = new ArrayList<BugsList>();
Document doc = Jsoup.connect("https://bugzilla.mozilla.org/rest/bug?product=Input&f1=bug_mentor&o1=isnotempty").get();
String rawData = doc.body().text();
// System.out.println(title);
JSONObject obj = new JSONObject(rawData);
// System.out.println(obj);
System.out.println(obj.get("bugs"));
JSONArray jsonMainArr = new JSONArray(obj.get("bugs").toString());
for (int i = 0; i < jsonMainArr.length(); i++) { // **line 2**
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
JSONObject assigned = childJSONObject.getJSONObject("assigned_to_detail");
// JSONObject assigned2 = childJSONObject.getJSONObject("assigned_to_detail");
int id = assigned.getInt("id");
BugsList bug = new BugsList();
BugsList bug2 = new BugsList();
bug.setId(id);
String severity = childJSONObject.getString("severity");
String resolution = childJSONObject.getString("resolution");
String summary = childJSONObject.getString("summary");
String component = childJSONObject.getString("component");
bug.setSeverity(severity);
bug.setResolution(resolution);
bug.setSummary(summary);
bug.setComponent(component);
bugsList.add(bug);
// String severity = assigned.getString();
// System.out.println("sss "+ assigned);
}
getComponent("Code Quality");
// getSeverity(524276);
// getResolution(524276);
// getSummary(524276);
}
public static void getSeverity(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The id exists in the list " + bugsList.get(i).getSeverity());
}
}
}
public static void getResolution(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The id exists in the list and The resolution is" + bugsList.get(i).getResolution());
}
}
}
public static void getSummary(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The comp.. exists in the list and The summary is " + bugsList.get(i).getSummary());
}
}
}
// Current used method
public static ArrayList<BugsList> getComponent(String component){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getComponent().equals(component)){
System.out.println("(Code Quality) component contains summary " + bugsList.get(i).getSummary() +" /The resolution is " +
bugsList.get(i).getResolution() + " /Severity is " + bugsList.get(i).getSeverity());
bugbug.add(bugsList.get(i));
}
}
return bugbug;
}
}
package bla_bla;
public class BugsList {
private String severity;
private int id;
private String resolution;
private String summary;
private String component;
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
I think I understand you problem. You write your code into the main function and that not the solution.
Your main function should look something like that:
public static void main(String args[]) throws IOException {
Supermonkey supermonkey = new Supermonkey();
supermonkey.getComponent("componennt name ");
}
Your Class is Supermonkey and you create an instance call supermonkey (sometime people use mySupermonkey) . There is only one instance of this class that will use.
Then into the constructor method you can create everything to build your instance supermonkey as :
public class Supermonkey {
private ArrayList<BugsList> bugsList;
private ArrayList<BugsList> bugbug;
public Supermonkey(){
bugsList = new ArrayList<BugsList>();
bugbug = new ArrayList<BugsList>();
Document doc = Jsoup
.connect(
"https://bugzilla.mozilla.org/rest/bug?product=Input&f1=bug_mentor&o1=isnotempty")
.get();
String rawData = doc.body().text(); // ... partial code add everything about initialisation of your instance
Then you can have a method of this Class Supermonkey
// Current used method
public ArrayList<BugsList> getComponent(String component) {
for (int i = 0; i < bugsList.size(); i++) {
if (bugsList.get(i).getComponent().equals(component)) {
System.out
.println("(Code Quality) component contains summary "
+ bugsList.get(i).getSummary()
+ " /The resolution is "
+ bugsList.get(i).getResolution()
+ " /Severity is "
+ bugsList.get(i).getSeverity());
bugbug.add(bugsList.get(i));
}
}
return bugbug;
}
A this method is call from the public static void main(String args[]) with supermonkey.getComponent("componennt name ");
Also I think about to change the name of Class BugsList it seems to be a BugItem , may be ?
I have a method that return an object of a class.The object sets the properties of class and returns.
I have to traverse the object and get the value of the properties which the object has set before.
I tried to use for-each loop,iterator but failed to traverse.
Can someone please help me to get through this.Thanks in advance.
code:
public class ConsumerTool {
public MessageBean getMessages() {
MessageBean msgBean = new MessageBean();
msgBean.setAtmId(atmId.trim());
msgBean.setEventText(eventText.trim());
msgBean.setEventNumber(eventNumber.trim());
msgBean.setSeverity(severity.trim());
msgBean.setSubsystemID(subsystemID.trim());
msgBean.setUniqueEventID(uniqueEventID.trim());
msgBean.setTaskID(taskID.trim());
msgBean.setGenerator(generator.trim());
msgBean.setGeneratorBuildVsn(generatorBuildVsn.trim());
msgBean.setDateTime(dateTime.trim());
this.msgBean = msgBean;
return msgBean;
}
}
JavaBean class:
public class MessageBean implements java.io.Serializable {
public String dateTime;
public String severity;
public String eventText;
public String eventNumber;
public String generator;
public String generatorBuildVsn;
public String atmId;
public String uniqueEventID;
public String subsystemID;
public String taskID;
//System.out.println("dateTime2222222"+dateTime);
public String getAtmId() {
return this.atmId;
}
public void setAtmId(String n) {
this.atmId = n;
}
public String getDateTime() {
return this.dateTime;
}
public void setDateTime(String n) {
this.dateTime = n.trim();
}
public String getEventNumber() {
return this.eventNumber;
}
public void setEventNumber(String n) {
this.eventNumber = n;
}
public String getEventText() {
return this.eventText;
}
public void setEventText(String n) {
this.eventText = n;
}
public String getGenerator() {
return this.generator;
}
public void setGenerator(String n) {
this.generator = n;
}
public String getGeneratorBuildVsn() {
return this.generatorBuildVsn;
}
public void setGeneratorBuildVsn(String n) {
this.generatorBuildVsn = n;
}
public String getSeverity() {
return this.severity;
}
public void setSeverity(String n) {
this.severity = n;
}
public String getSubsystemID() {
return this.subsystemID;
}
public void setSubsystemID(String n) {
this.subsystemID = n;
}
public String getTaskID() {
return this.taskID;
}
public void setTaskID(String n) {
this.taskID = n;
}
public String getUniqueEventID() {
return this.uniqueEventID;
}
public void setUniqueEventID(String n) {
this.uniqueEventID = n;
}
}
The theme is the object sets the properties of javabean class and I have to get those values from UI.
In Jsp
<%
MessageBean consumer = msg.getMessages();
//Now here i want to iterate that consumer object
%>
As the MessagesBean seems to comply the javabeans specification, you can just use java.beans.Introspector for this.
MessageBean messageBean = consumerTool.getMessages();
// ...
BeanInfo beanInfo = Introspector.getBeanInfo(MessageBean.class);
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
String name = property.getName();
Object value = property.getReadMethod().invoke(messageBean);
System.out.println(name + "=" + value);
}
This all is under the covers using the reflection API.
Update your edit reveals that you're intending to use this to present the data in JSP. This is then not really the right approach. Bite the bullet and specify every property separately. This way you've full control over the ordering.