PriorityQueue incl. .poll() and Compareable explanation? (Java) - java

I am currently stuck at the following problem:
I have a class "WaitingRoom" and "Patient". Patients with the status "emergency" are the first ones in the queue (PriorityQueue waitingRoom) (time does not matter) and the others are sorted by their appointment.
I am testing my program with the following code:
WaitingRoom wz = new WaitingRoom();
Calendar c = Calendar.getInstance(Locale.GERMANY);
c.set(2009, Calendar.OCTOBER, 21, 9, 35);
wz.comesIn(new Patient("Smith Jones", c.getTime(), false));
c.set(2009, Calendar.OCTOBER, 21, 9, 30);
wz.comesIn(new Patient("Mueller Johan", c.getTime(), false));
wz.comesIn(new Patient("Emergency Brooklyn", new Date(), true));
c.set(2009, Calendar.OCTOBER, 21, 8, 30);
wz.comesIn(new Patient("Richard Smith", c.getTime(), false));
c.set(2009, Calendar.OCTOBER, 21, 9, 31);
wz.comesIn(new Patient("Kimberly Adams", c.getTime(), false));
c.set(2009, Calendar.OCTOBER, 21, 9, 29);
wz.comesIn(new Patient("Random Name", c.getTime(), false));
Patient patient = wz.getNextPatient();
assertEquals("Emergency Brooklyn", patient.getName());
patient = wz.getNextPatient();
assertEquals("Richard Smith", patient.getName());
patient = wz.getNextPatient();
assertEquals("Random Name", patient.getName());
The method .getNextPatient() returns waitingRoom.poll();
And my compareTo:
public int compareTo(Patient other) {
if (other.emergency) {
return 1;
} else {
if (this.emergency) {
return -1;
} else {
return this.appointment.compareTo(other.appointment);
}
}
}
The code works fine. But I do not understand how the sorting works. I tried understanding it by using the debugger.. but I still don't get it. It sorts it when a next patient comes in (how does it choose the other patient?) and another time when I use the function .poll().
Could you please explain me how it works?
Thank you advance!

Related

OPC UA calling Acknowlagement method and fetching Bad_EventIdUnkown in java

Currently i am developing OPCUA client using Eclipse Milo. I am able to read data from OPC UA cpp server and able to write setpoint data to server.
I am not able to perform acknowledgement of OPCUA ALarm and events.
I tried with node-red opcua server and getting alarms,now i want to acknowledge the same , so i had tried code for calling acknowledgement method for opcua. Here it is:
byte[] b=new byte[] {-66, -115, -121, -6, -39, 40, 89, 114, 60, -66, -126, -79, -72, -128, -21, 23, 0, 0, 4, -4};
LocalizedText lt = new LocalizedText("bagiya");
ByteString bs=new ByteString(b);
Variant evntid1 = new Variant(bs);
System.out.println("jangli id :=>"+vs[1]);
Variant lt1 = new Variant(lt);
Variant[] v = new Variant[] { evntid1,lt1 = new Variant(lt)};
System.out.println(vs[1].getDataType());
CallMethodRequest rec = new CallMethodRequest(NodeId.parse("ns=1;i=1003"), NodeId.parse("ns=1;i=1022"), v);
System.out.println( rec.getTypeId()+"::=>"+client.call(rec).get());
this byte array string is given by node-red opcua server using eclipse milo code of Event Subscription Example.
EventFilter eventFilter = new EventFilter(new SimpleAttributeOperand[] {
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "EventId") }, AttributeId.Value.uid(), null),
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "EventType") }, AttributeId.Value.uid(), null),
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "Severity") }, AttributeId.Value.uid(), null),
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "Time") }, AttributeId.Value.uid(), null),
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "Time") }, AttributeId.Value.uid(), null),
new SimpleAttributeOperand(Identifiers.BaseEventType,
new QualifiedName[] { new QualifiedName(0, "Message") }, AttributeId.Value.uid(), null) },
new ContentFilter(null));
So we are getting this below given status:
CallMethodResult{StatusCode=StatusCode{name=Bad_EventIdUnknown, value=0x809A0000, quality=bad}, InputArgumentResults=[StatusCode{name=Good, value=0x00000000, quality=good}, StatusCode{name=Good, value=0x00000000, quality=good}], InputArgumentDiagnosticInfos=[], OutputArguments=[]}
Kindly give me some suggestions to troubleshoot this problem.
In this line of code :
CallMethodRequest rec = new CallMethodRequest(NodeId.parse("ns=1;i=1003"),
NodeId.parse("ns=1;i=1022"), v);
You parse two node Id's. And the "CallMethodResult" Status depicts that:
ns=1;i=1003 :
StatusCode{name=Bad_EventIdUnknown, value=0x809A0000, quality=bad}, InputArgumentResults=[StatusCode{name=Good, value=0x00000000, quality=good}
Meaning
Bad_EventIdUnknown, 0x809A0000 : The specified event ID is not recognized.
(with reference to here).
ns=1;i=1022 :
StatusCode{name=Good, value=0x00000000, quality=good}], InputArgumentDiagnosticInfos=[], OutputArguments=[]
Therefore, I would like to conclude that there might be some problems with parsing
ns=1;i=1003 : node id.

Joda DateTime deserialized from JSON as current timestamp instead of provided data

I have a JSON with Joda DateTime field. It has some sample values. But whenever I convert it to Object it automatically takes the current DateTime instead of the DateTime present in the JSON.
PFB the sample JSON
[{
"pas": "CSP",
"policyNumber": "ZU131874",
"schemeName": "PepsiCo employee scheme20",
"policyStatus": "ACTIVE",
"productCode": "GPP",
"totalSavings": 100000,
"investmentReturn": 55000,
"effectiveDate": {
"startDate": {
"dayOfYear": 2,
"year": 2014,
"dayOfMonth": 2,
"dayOfWeek": 4,
"era": 1,
"weekOfWeekyear": 1,
"millisOfSecond": 0,
"secondOfMinute": 0,
"minuteOfDay": 0,
"centuryOfEra": 20,
"yearOfCentury": 14,
"hourOfDay": 0,
"monthOfYear": 1,
"weekyear": 2014,
"minuteOfHour": 0,
"yearOfEra": 2014,
"secondOfDay": 0,
"millisOfDay": 0,
"millis": 1388601000000
},
"endDate": null
}
}, {
"pas": "CSP",
"policyNumber": "ZU146271",
"schemeName": "PepsiCo employee scheme7",
"policyStatus": "ACTIVE",
"productCode": "GPP",
"totalSavings": 100000,
"investmentReturn": 55000,
"effectiveDate": {
"startDate": {
"dayOfYear": 156,
"year": 2015,
"dayOfMonth": 5,
"dayOfWeek": 5,
"era": 1,
"weekOfWeekyear": 23,
"millisOfSecond": 0,
"secondOfMinute": 0,
"minuteOfDay": 0,
"centuryOfEra": 20,
"yearOfCentury": 15,
"hourOfDay": 0,
"monthOfYear": 6,
"weekyear": 2015,
"minuteOfHour": 0,
"yearOfEra": 2015,
"secondOfDay": 0,
"millisOfDay": 0,
"millis": 1433442600000
},
"endDate": null
}
}]
I am using following code to convert list of JSON objects to a list Of Java objects.
policies = new ArrayList<Policy>();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader("./src/test/resources/" + "sample-zurich-pensions.json"));
Type listType = new TypeToken<List<Policy>>(){}.getType();
List<Policy> policyList = new Gson().fromJson(jsonElement, listType);
policies.addAll(policyList);
In the jsonElement I am getting the exact value, but in the policyList the DateTime is set to the current date.
PFB the classes
Policy.java
private String pas;
private String policyNumber;
private String schemeName;
private String policyStatus;
private String productCode;
private BigDecimal totalSavings;
private BigDecimal investmentReturn;
private EffectiveDate effectiveDate;
EffectiveDate.java
private DateTime startDate;
private DateTime endDate;
During deserialization from JSON, Gson is creating a new DateTime() (which is equal to current system DateTime). The fields present in your JSON are based on getters in DateTime, but there are no setters for them present, so the object cannot be adjusted to the timestamp represented by the JSON. You are much better off using a standard date-time representation like ISO 8601. Then, implement a JsonSerializer and JsonDeserializer for DateTime as suggested on the Gson site:
class DateTimeTypeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
#Override
public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
#Override
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
return new DateTime(json.getAsString());
}
}
or use one of the solutions provided in this post (linked also by #user2762451). You can register the serializer/deserializer like this:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter());
Gson gson = gsonBuilder.create();

how to initialize objects of the array?

i have an array of 10 objects and i would like to initialize them for the array.
private Flight[] flight = new Flight[10];
flight[0] = new Flight("AA101", "Boston", "Sacremento", 421.33, 22, 6);
flight[1] = new Flight("AA102", "Lincolin", Jacksonville, 612.08, 22 6);
flight[2] = new Flight("AA103", "Rochester", "Columbia", 510.83, 22, 6);
flight[3] = new Flight("AA104", "Boise", "Aspen", 411.12, 22, 6);
flight[4] = new Flight("AA105", "Fort Collins", "Louiseville", 654.22, 22, 6);
flight{5} = new Flight("AA106", "Seattle", "Dallas" 326.14, 22, 6);
flight{6} = new Flight("AA107", "Phoenix", "Little Rock", 974.22, 22, 6);
flight[7] = new Flight("AA108", "Cheyenne", "Louiseville", 521.43 , 22, 6);
flight[8] = new Flight("AA109", "Louiseville", "Buffalo", 452.21, 22, 6);
flight[9] = new Flight("AA100", "Anchorage" , "Tampa", 874.72, 22, 6);
but i get tons of errors such as:
ReservationGUI.java:31: error: ']' expected
ReservationGUI.java:31: error: illegal start of type
ReservationGUI.java:31: error: ';' expected
ReservationGUI.java:31: error: expected
there are 100 of them.
use square brackets instead of curly brackets for 5 and 6 elements
You have many typos, and all programming languages are very unforgiving about typos.
Another approach:
private Flight[] flight = new Flight[] {
new Flight("AA101", "Boston", "Sacremento", 421.33, 22, 6),
new Flight("AA102", "Lincolin", "Jacksonville", 612.08, 22, 6),
new Flight("AA103", "Rochester", "Columbia", 510.83, 22, 6),
new Flight("AA104", "Boise", "Aspen", 411.12, 22, 6),
new Flight("AA105", "Fort Collins", "Louiseville", 654.22, 22, 6),
new Flight("AA106", "Seattle", "Dallas", 326.14, 22, 6),
new Flight("AA107", "Phoenix", "Little Rock", 974.22, 22, 6),
new Flight("AA108", "Cheyenne", "Louiseville", 521.43, 22, 6),
new Flight("AA109", "Louiseville", "Buffalo", 452.21, 22, 6),
new Flight("AA100", "Anchorage" , "Tampa", 874.72, 22, 6)
};

How do you turn an array into a list or how can you set up an array to be used in stickyheaders?

I have a set of data in an array and would like to turn it into a list or added the data to a list. The stickyheaders library uses lists and I need to change mine into a list since I'm having difficulty in using the stickyheaders as arrays it only shows a blank recyclerview.
This is my set of sample data, this is data is just used for creating a new event in a calendar. I retrieve the day and format it to show (e.g Monday). This is what the header will be.
If anyone can help turning this array into a list or how to add these data to a list, it would be appreciated, or if someone is familiar with stickyheaders and used arrays for it some sample code is appreciated.
public static final Event[] EventList = {
new Event("The Theory of Everything", "1:00 PM", "Cinema 1", 2015, 2, 5, 13, 0),
new Event("Kingsman the Secret Service", "3:00 PM", "Cinema 2", 2015, 2, 5, 15, 0),
new Event("Fifty Shades of Grey", "5:00 PM", "Cinema 3", 2015, 2, 5, 17, 0),
new Event("Focus", "7:00 PM", "Cinema 4", 2015, 2, 5, 19, 0),
new Event("Crazy Beautiful You", "9:00 PM", "Cinema 5", 2015, 2, 5, 21, 0),
new Event("The Theory of Everything", "1:00 PM", "Cinema 1", 2015, 2, 6, 13, 0),
new Event("Kingsman the Secret Service", "3:00 PM", "Cinema 2", 2015, 2, 6, 15, 0),
new Event("Fifty Shades of Grey", "5:00 PM", "Cinema 3", 2015, 2, 6, 17, 0),
new Event("Focus", "7:00 PM", "Cinema 4", 2015, 2, 6, 19, 0),
new Event("Crazy Beautiful You", "9:00 PM", "Cinema 5", 2015, 2, 6, 21, 0)
};
You're almost there. After that you can do:
List<Event> eventList = Arrays.asList(EventList);

having some issues adding mysql data to JTables

I am learning how to connect to a database, and as a project I am making a JTable display database information. I am using a database called world that has a table called city with columns id, name, countrycode, district, population. Here is my code, I made it after looking at the java doc and some other various sources, but I am not sure if I am doing it right, and I have never used vectors before either.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class JTableTest extends JFrame {
Vector<String> columnNames;
Vector<Object> row;
JTable table;
public static void main(String[] args) {
JTableTest test = new JTableTest();
test.connectDB();
}
public void buildGui() {
setSize(500, 600);
setVisible(true);
JScrollPane scrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(scrollPane);
}
public void connectDB() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/world";
String user = "root";
String pass = "root";
String sql = "Select id, name, countrycode, district, population from city where id < 100";
Connection conn;
Statement stmt;
ResultSet rs;
try {
Class.forName(driver);
System.out.println("connecting..");
conn = DriverManager.getConnection(url, user, pass);
System.out.println("connected!");
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
table = new JTable(rsToTableModel(rs));
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public TableModel rsToTableModel(ResultSet rs) {
try {
ResultSetMetaData md = rs.getMetaData();
int numberOfColumns = md.getColumnCount();
columnNames = new Vector<String>();
for (int i = 1; i < numberOfColumns; i++) {
columnNames.addElement(md.getColumnLabel(i));
}
row = new Vector<Object>();
while (rs.next()) {
for (int i = 1; i < numberOfColumns; i++) {
row.addElement(rs.getObject(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new DefaultTableModel(row, columnNames);
}
}
Here is my error
connecting..
connected!
[1, Kabul, AFG, Kabol, 2, Qandahar, AFG, Qandahar, 3, Herat, AFG, Herat, 4, Mazar-e-Sharif, AFG, Balkh, 5, Amsterdam, NLD, Noord-Holland, 6, Rotterdam, NLD, Zuid-Holland, 7, Haag, NLD, Zuid-Holland, 8, Utrecht, NLD, Utrecht, 9, Eindhoven, NLD, Noord-Brabant, 10, Tilburg, NLD, Noord-Brabant, 11, Groningen, NLD, Groningen, 12, Breda, NLD, Noord-Brabant, 13, Apeldoorn, NLD, Gelderland, 14, Nijmegen, NLD, Gelderland, 15, Enschede, NLD, Overijssel, 16, Haarlem, NLD, Noord-Holland, 17, Almere, NLD, Flevoland, 18, Arnhem, NLD, Gelderland, 19, Zaanstad, NLD, Noord-Holland, 20, ´s-Hertogenbosch, NLD, Noord-Brabant, 21, Amersfoort, NLD, Utrecht, 22, Maastricht, NLD, Limburg, 23, Dordrecht, NLD, Zuid-Holland, 24, Leiden, NLD, Zuid-Holland, 25, Haarlemmermeer, NLD, Noord-Holland, 26, Zoetermeer, NLD, Zuid-Holland, 27, Emmen, NLD, Drenthe, 28, Zwolle, NLD, Overijssel, 29, Ede, NLD, Gelderland, 30, Delft, NLD, Zuid-Holland, 31, Heerlen, NLD, Limburg, 32, Alkmaar, NLD, Noord-Holland, 33, Willemstad, ANT, Curaçao, 34, Tirana, ALB, Tirana, 35, Alger, DZA, Alger, 36, Oran, DZA, Oran, 37, Constantine, DZA, Constantine, 38, Annaba, DZA, Annaba, 39, Batna, DZA, Batna, 40, Sétif, DZA, Sétif, 41, Sidi Bel Abbès, DZA, Sidi Bel Abbès, 42, Skikda, DZA, Skikda, 43, Biskra, DZA, Biskra, 44, Blida (el-Boulaida), DZA, Blida, 45, Béjaïa, DZA, Béjaïa, 46, Mostaganem, DZA, Mostaganem, 47, Tébessa, DZA, Tébessa, 48, Tlemcen (Tilimsen), DZA, Tlemcen, 49, Béchar, DZA, Béchar, 50, Tiaret, DZA, Tiaret, 51, Ech-Chleff (el-Asnam), DZA, Chlef, 52, Ghardaïa, DZA, Ghardaïa, 53, Tafuna, ASM, Tutuila, 54, Fagatogo, ASM, Tutuila, 55, Andorra la Vella, AND, Andorra la Vella, 56, Luanda, AGO, Luanda, 57, Huambo, AGO, Huambo, 58, Lobito, AGO, Benguela, 59, Benguela, AGO, Benguela, 60, Namibe, AGO, Namibe, 61, South Hill, AIA, –, 62, The Valley, AIA, –, 63, Saint John´s, ATG, St John, 64, Dubai, ARE, Dubai, 65, Abu Dhabi, ARE, Abu Dhabi, 66, Sharja, ARE, Sharja, 67, al-Ayn, ARE, Abu Dhabi, 68, Ajman, ARE, Ajman, 69, Buenos Aires, ARG, Distrito Federal, 70, La Matanza, ARG, Buenos Aires, 71, Córdoba, ARG, Córdoba, 72, Rosario, ARG, Santa Fé, 73, Lomas de Zamora, ARG, Buenos Aires, 74, Quilmes, ARG, Buenos Aires, 75, Almirante Brown, ARG, Buenos Aires, 76, La Plata, ARG, Buenos Aires, 77, Mar del Plata, ARG, Buenos Aires, 78, San Miguel de Tucumán, ARG, Tucumán, 79, Lanús, ARG, Buenos Aires, 80, Merlo, ARG, Buenos Aires, 81, General San Martín, ARG, Buenos Aires, 82, Salta, ARG, Salta, 83, Moreno, ARG, Buenos Aires, 84, Santa Fé, ARG, Santa Fé, 85, Avellaneda, ARG, Buenos Aires, 86, Tres de Febrero, ARG, Buenos Aires, 87, Morón, ARG, Buenos Aires, 88, Florencio Varela, ARG, Buenos Aires, 89, San Isidro, ARG, Buenos Aires, 90, Tigre, ARG, Buenos Aires, 91, Malvinas Argentinas, ARG, Buenos Aires, 92, Vicente López, ARG, Buenos Aires, 93, Berazategui, ARG, Buenos Aires, 94, Corrientes, ARG, Corrientes, 95, San Miguel, ARG, Buenos Aires, 96, Bahía Blanca, ARG, Buenos Aires, 97, Esteban Echeverría, ARG, Buenos Aires, 98, Resistencia, ARG, Chaco, 99, José C. Paz, ARG, Buenos Aires]
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.Vector
at javax.swing.table.DefaultTableModel.justifyRows(Unknown Source)
at javax.swing.table.DefaultTableModel.setDataVector(Unknown Source)
at javax.swing.table.DefaultTableModel.<init>(Unknown Source)
at JTableTest.rsToTableModel(JTableTest.java:80)
at JTableTest.connectDB(JTableTest.java:51)
at JTableTest.main(JTableTest.java:22)
My first question is am I doing the vectors right? I am not sure if its supposed to add everything to the row vector as just one huge entry separated by commas. Am I approaching this right? I feel like I am missing something ..I am assuming I get this error because the object has 5 columns including ints and strings, but not sure where to go from here. All I know is a Jtable accepts (vector,vector) or (object[][],object(). I am getting confused as its my first time working with mysql and jtables.
row = new Vector();
representing single row, not 2D set of rows
you have to create 2D array e.g. Vector<Vector<Object>>() data = new Vector<Vector<Object>>();, then add a new row = new Vector<Object>(); to Vector<Vector<Object>>(); after data are filled inside while (rs.next()) {
change return new DefaultTableModel(row, columnNames); to return new DefaultTableModel(data, columnNames);
override getColumnClass for DefaultTableModel
don't reinvent the wheel, search for ResultSetTableModel, TableFromDatabase
According to the method definition mentioned here, the first argument of DefaultTableModel constructor should be a Vector of Vectors.
In your while loop declare another Vector variable
while (rs.next()) {
java.util.Vector<Object> rowData = new java.util.Vector<Object>();
for (int i = 1; i < numberOfColumns; i++) {
rowData.addElement(rs.getObject(i));
}
// Here add that row data to the row vector
row.addElement(rowData);
}

Categories

Resources