I have this XML file which I parse into an ArrayList
In this ArrayList I have countries and the alarmnumbers for the countries in it.
I want to search to a country and get it's police, ambulance or firedep. number.
Here is the code to help you out.
Parsing XML into ArrayList:
protected ArrayList<Alarmdiensten> getAlarmdiensten() {
ArrayList<Alarmdiensten> lijst = new ArrayList<Alarmdiensten>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
land.politie = Xml.innerHtml(Xml.getChildByTagName(node, "politie"));
land.ambulance = Xml.innerHtml(Xml.getChildByTagName(node, "ambulance"));
land.brandweer = Xml.innerHtml(Xml.getChildByTagName(node, "brandweer"));
land.telamba = Xml.innerHtml(Xml.getChildByTagName(node, "telamba"));
land.adresamba = Xml.innerHtml(Xml.getChildByTagName(node, "adresamba"));
lijst.add(land);
}
} catch (Exception e) {;
}
return lijst;
}
The method that will use the alarmnumbers:
public void AlarmMenu(){
String landcode;
ArrayList<Alarmdiensten> diensten = getAlarmdiensten();
if(fakelocation = true) {
landcode = sfakelocation;
}
else {
try {
landcode = getAddressForLocation(this, locationNow).getCountryCode();
} catch (IOException e) {
e.printStackTrace();
}
}
So I have the landcode, and I want to search in the ArrayList diensten for the numbers that belong with the landcode.
How can I do this?
Well at the moment you've got an ArrayList of Alarmdiensten objects. I would suggest you might want to change that to a Map so that you are storing a Map of land codes vs your Alarmdiensten objects.
That way you get the Alarmdiensten out of the Map using the landcode and then simply call the getPolitie() etc methods on your Alarmdiensten object.
I would make sure that you encapsulate your Alarmdiensten object BTW, accessing it's private members directly is a bit of a no-no :)
So something like:
protected Map<String, Alarmdiensten> getAlarmdiensten()
{
Map<String, Alarmdiensten> alarmNumbersForCountries
= new HashMap<String, Alarmdiensten>();
try
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("alarmdiensten.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i = 0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
Alarmdiensten land = new Alarmdiensten();
land.setLand(Xml.innerHtml(Xml.getChildByTagName(node, "naam")));
land.setLandcode(Xml.innerHtml(Xml.getChildByTagName(node, "code")));
land.setPolitie(Xml.innerHtml(Xml.getChildByTagName(node, "politie")));
land.setAmbulance(Xml.innerHtml(Xml.getChildByTagName(node, "ambulance")));
land.setBrandweer(Xml.innerHtml(Xml.getChildByTagName(node, "brandweer")));
land.setTelamba(Xml.innerHtml(Xml.getChildByTagName(node, "telamba")));
land.setAdresamba(Xml.innerHtml(Xml.getChildByTagName(node, "adresamba")));
alarmNumbersForCountries.put(land.getLandCode(), land);
}
}
catch (Exception e)
{
// Handle Exception
}
return alarmNumbersForCountries;
}
To get the entry out of the Map
Alarmdiensten land = alarmNumbersForCountries.get(landcode);
Another YMMV point is that you might want to split out the part of your method that builds Alarmdiensten objects from the XML parsing. "Each method should do one thing and one thign well."
Use a for loop and search for it
for(Alarmdiensten land :diensten){
if(land.landcode.equals(landcode) ){
// yes i got it, The current land.
break;
}
}
Just iterate over the list:
String landcode = getLandCode();
for (Alarmdiensten dienst:diensten) {
if (dienst.landcode.equals(landcode)) {
// do what has to be done
}
}
Consider using a map instead of a list, if you have to lookup the values more frequently:
Map<String, List<Alarmdiensten>> servicesInCountry
= new HashMap<String, List<Alarmdiensten>>();
for (Alarmdiensten dienst:diensten) {
List<Alarmdiensten> list = servicesInCountry.get(dienst.landcode);
if (list == null) {
list = new ArrayList<Alarmdiensten>();
servicesInCountry.put(dienst.landcode, list);
}
list.add(dienst);
}
// ... and later on
List<Alarmdiensten> servicesInSweden = servicesInCountry.get("SWE");
Related
I have a categorized Notes view, let say the first categorized column is TypeOfVehicle the second categorized column is Model and the third categorized column is Manufacturer.
I would like to collect only the values for the first category and return it as json object:
I am facing two problems:
- I can not read the value for the category, the column values are emptry and when I try to access the underlying document it is null
the script won't hop over to the category/sibling on the same level.
can someone explain me what am I doing wrong here?
private Object getFirstCategory() {
JsonJavaObject json = new JsonJavaObject();
try{
String server = null;
String filepath = null;
server = props.getProperty("server");
filepath = props.getProperty("filename");
Database db;
db = utils.getSession().getDatabase(server, filepath);
if (db.isOpen()) {
View vw = db.getView("transport");
if (null != vw) {
vw.setAutoUpdate(false);
ViewNavigator nav;
nav = vw.createViewNav();
JsonJavaArray arr = new JsonJavaArray();
Integer count = 0;
ViewEntry tmpentry;
ViewEntry entry = nav.getFirst();
while (null != entry) {
Vector<?> columnValues = entry.getColumnValues();
if(entry.isCategory()){
System.out.println("entry notesid = " + entry.getNoteID());
Document doc = entry.getDocument();
if(null != doc){
if (doc.hasItem("TypeOfVehicle ")){
System.out.println("category has not " + "TypeOfVehicle ");
}
else{
System.out.println("category IS " + doc.getItemValueString("TypeOfVehicle "));
}
} else{
System.out.println("doc is null");
}
JsonJavaObject row = new JsonJavaObject();
JsonJavaObject jo = new JsonJavaObject();
String TypeOfVehicle = String.valueOf(columnValues.get(0));
if (null != TypeOfVehicle ) {
if (!TypeOfVehicle .equals("")){
jo.put("TypeOfVehicle ", TypeOfVehicle );
} else{
jo.put("TypeOfVehicle ", "Not categorized");
}
} else {
jo.put("TypeOfVehicle ", "Not categorized");
}
row.put("request", jo);
arr.put(count, row);
count++;
tmpentry = nav.getNextSibling(entry);
entry.recycle();
entry = tmpentry;
} else{
//tmpentry = nav.getNextCategory();
//entry.recycle();
//entry = tmpentry;
}
}
json.put("data", arr);
vw.setAutoUpdate(true);
vw.recycle();
}
}
} catch (Exception e) {
OpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
}
return json;
}
What you're doing wrong is trying to treat any single view entry as both a category and a document. A single view entry can only be one of a category, a document, or a total.
If you have an entry for which isCategory() returns true, then for the same entry:
isDocument() will return false.
getDocument() will return null.
getNoteID() will return an empty string.
If the only thing you need is top-level categories, then get the first entry from the navigator and iterate over entries using nav.getNextSibling(entry) as you're already doing, but:
Don't try to get documents, note ids, or fields.
Use entry.getColumnValues().get(0) to get the value of the first column for each category.
If the view contains any uncategorised documents, it's possible that entry.getColumnValues().get(0) might throw an exception, so you should also check that entry.getColumnValues().size() is at least 1 before trying to get a value.
If you need any extra data beyond just top-level categories, then note that subcategories and documents are children of their parent categories.
If an entry has a subcategory, nav.getChild(entry) will get the first subcategory of that entry.
If an entry has no subcategories, but is a category which contains documents, nav.getChild(entry) will get the first document in that category.
Assuming I have a Vertex (let's call it "PokemonMaster")
PokemonMaster
{
name, (STRING)
age, (INTEGER)
pokemons, (EMBEDDEDMAP) of Pokemon
}
in my DB containing an EMBEDDEDMAP (I also tried with LINKMAP but I'm not sure of what i'm doing) of a class "Pokemon".
I'm trying with Java to create the Vertex and put in the field "pokemons", some pokemons.
let's say a Pokemon looks like :
Pokemon
{
name, (STRING)
}
I'm doing something like :
Vertex v = graph.addVertex("class:PokemonMaster",
"name", "Sacha",
"age", "42",
"pokemons", new ODocument("Pokemon").field("name", "Pikachu"));
I assume this would create a first element (Pikachu) in the map. And I was hoping to be able to add some Pokemons to my map later by doing something like :
v.setProperty("pokemons", new ODocument("Pokemon").field("name", "Raichu"));
All of this is actually not working and that's why i'm here, am I totally wrong?
I get the error :
The field 'PokemonMaster.pokemons' has been declared as EMBEDDEDMAP but an incompatible type is used. Value: Pokemon{name:Pikachu}
Thank you !
Edit
I found the solution.
Creating a map like :
Map<String, ODocument> foo = new HashMap<>();
Putting some pokemons in it :
ODocument doc = new ODocument("Pokemon").field("name", "Pikachu");
ODocument doc2 = new ODocument("Pokemon").field("name", "Raichu");
foo.put("pikachu", doc);
foo.put("raichu", doc2);
doc.save();
doc2.save();
and simply giving the map as parameter :
Vertex v = graph.addVertex("class:PokemonMaster",
"name", "Sacha",
"age", "42",
"pokemons", foo);
Hope it will help someone !
UPDATE:
In case of embeddedmap, to create the schema:
OrientGraphNoTx graphOne = new OrientGraphNoTx(URL, USER, USER);
try {
OSchema schema = graphOne.getRawGraph().getMetadata().getSchema();
OClass pokemon = schema.createClass("Pokemon");
pokemon.createProperty("name", OType.STRING);
OClass vClass = schema.getClass("V");
OClass pokemonMaster = schema.createClass("PokemonMaster");
pokemonMaster.setSuperClass(vClass);
pokemonMaster.createProperty("name", OType.STRING);
pokemonMaster.createProperty("age", OType.INTEGER);
pokemonMaster.createProperty("pokemons", OType.EMBEDDEDMAP, pokemon);
} finally {
graphOne.shutdown();
}
Create a master with a pokemon:
String pmRID = "";
OrientGraph graphTwo = new OrientGraph(URL, USER, USER);
try {
ODocument pokemon = new ODocument("Pokemon");
pokemon.field("name", "Pikachu");
Map<String,ODocument> foo = new HashMap();
foo.put("pikachu", pokemon);
OrientVertex v = graphTwo.addVertex("class:PokemonMaster",
"name", "Sacha",
"age", "42",
"pokemons", foo);
graphTwo.commit();
pmRID = v.getIdentity().toString();
} catch (Exception e) {
// ...
} finally {
graphTwo.shutdown();
}
Add a second pokemon:
OrientGraph graphThree = new OrientGraph(URL, USER, USER);
try {
ODocument pokemon = new ODocument("Pokemon");
pokemon.field("name", "Raichu");
OrientVertex v = graphThree.getVertex(pmRID);
Map<String, ODocument> pokemons = v.getProperty("pokemons");
if (pokemons == null) {
pokemons = new HashMap();
}
pokemons.put("raichu", pokemon);
v.setProperty("pokemons", pokemons);
graphThree.commit();
} catch (Exception e) {
// ...
} finally {
graphThree.shutdown();
}
You could also use an embeddedlist. See here.
I have a JSON with an array of 3 objects. So when I retrieveEventJSON(), I am simply setting the attributes to an Event object. And when I call the plotEventOnMap() from another activity, I expect to see 3 markers on the map.
public void retrieveEventJSON() throws JSONException {
String page;
JSONArray jsonArray;
try {
// Code to retrieve data from servlet
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void plotEventOnMap(Context context) {
graphicIcon = new PictureMarkerSymbol(res);
Point p = new Point(Double.parseDouble(eventModel.getEventX()),
Double.parseDouble(eventModel.getEventY()));
Symbol symbol = graphicIcon;
HashMap<String, Object> attrMap = new HashMap<String, Object>();
attrMap.put("eventName", eventModel.getEventName());
attrMap.put("eventBy", eventModel.getEventBy());
ENeighbourhoodActivity.graphicsLayer.addGraphic(new Graphic(p, symbol,
attrMap));
}
But with these codes, it just display the last row of record in my JSON instead of looping and plot each of them. Any guides?
Thanks in advance.
You need to call .plotEventOnMap(), or otherwise do something with the EventModel you've constructed, from inside your loop, after setting all the EventModel properties. At the moment, you're just overwriting your EventModel without ever using it.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
Just before the loop ends, you need to do something with the EventModel you've now constructed. This might be plotting it, or adding it to some collection, or whatever. But at the moment, you're going straight back into the loop, and then in the next iteration, overwriting all the good work you've done. The reason you're only ending up with the last one is that when you've done the last iteration, what's left in eventModel is what you wrote the last time you went through the loop.
In fact I think you also want
EventModel eventModel = new EventModel();
as the first thing inside your loop. (I don't know if this is exactly right because we haven't seen the code for EventModel so I don't know what the constructor looks like.) If you want to keep a List (or similar) of all of them, you need to make sure they're all different instances.
I would suggest recasting like this:
List<EventModel> events = new ArrayList<EventModel>(); //NEW
for (int i = 0; i < length; i++) {
EventModel eventModel = new EventModel(); //NEW
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
events.add(eventModel); //NEW
}
After the loop has finished, you'll have a list of EventModels that you can send to your plotting method or whatever's appropriate.
eventModel.setEventName(eventName); returns the latest element added to it because on every iteration you are resetting it.
You may add the object to the list after each iteration so that the list will have the elements. Declare the your EventModel object inside the for loop to have the instance for every iteration.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
EventModel eventModel=new eventModel();
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
list.add(eventModel);
}
i'm trying to get folder structure of a rule using java TEAMSERVER API .
IlrSessionFactory factory = new IlrRemoteSessionFactory();
try {
factory.connect(login, password, serverUrl, datasource);
IlrSession session = factory.getSession();
IlrRuleProject ruleProject = (IlrRuleProject) IlrSessionHelper.getProjectNamed(session, project);
IlrBaseline currentBaseline = IlrSessionHelper.getCurrentBaseline(session, ruleProject);
session.setWorkingBaseline(currentBaseline);
String query = new String("Find all business rules such that the name of each business rule is \"R105_1_krl\"");
IlrDefaultSearchCriteria criteria = new IlrDefaultSearchCriteria( query.toString());
List summaries = session.findElements(criteria, IlrModelConstants.ELEMENT_SUMMARY);
for (int i = 0; i < summaries.size(); i++) {
IlrElementSummary ruleSummary = (IlrElementSummary) summaries.get(i);
String ruleName = ruleSummary.getName();
System.out.println("\t" + ruleName);
}
If there is as named R105_1_krl rule , I can reach using java and DECİSİON CENTER API. But i need location of this rule. Such as XYZ package / abc folder / def folder
In addition , when i wrote the following two line in loop , i can reach these properties ;
Expiration Date, Effective Date, Created By, Last Changed On ... But, i can not reach folder information of properties of a rule.
IlrActionRule rule = (IlrActionRule) elementDetails;
String lastChangedBy = String.valueOf(rule.getPropertyValue("lastChangedBy"));
Here is the solution.
public static String getHierarchyPath (IlrElementDetails element) {
try {
if (!(element instanceof IlrRule)) return element.getName();
IlrRule rule = (IlrRule)element;
StringBuffer sb = new StringBuffer ();
// Get the rule name
String name = rule.getName();
// Get the rule package
IlrRulePackage current = rule.getRulePackage();
Stack<String> stack = new Stack<String> ();
while (true) {
if (current==null) break;
// Push the package name onto the stack
stack.push("/" + current.getName());
// Next parent ...
current = current.getParent();
}
// Pop the stack and build the path
while (!stack.empty()) {
String folder = (String) stack.pop();
sb.append(folder);
}
// Append the rule name to the path
sb.append("/").append(name);
// Return the built path
return sb.toString();
} catch (Exception e) {
return element.getName();
}
}
hello there i'm a little bit confuse with this code....sorry for my bad grammar..still new in this java.
private void loadSessionEvents() {
ArgumentBuilder arg = new ArgumentBuilder();
arg.addArg(getSessionLogId());
DBResult result = DBOperator.getInstance().doOperation(
FileOperation.class, "loadSessionLogEvents", arg.getTypeInfo());
// ArrayList<MsmLogIveScreenshots> logEvent =
// (ArrayList<MsmLogIveScreenshots>) result
// .getValue("RETURN");
// setSessionLogEvents(logEvent);
ArrayList<Object> logList = (ArrayList<Object>) result
.getValue("RETURN");
ArrayList<SessionLogEventModel> windowLogs = null;
if (ValidationUtils.nonNullAndNotEmpty(logList)) {
windowLogs = new ArrayList<SessionLogEventModel>();
for (int i = 0; i < logList.size(); i++) {
Object obj = logList.get(i);
if (obj instanceof MsmLogIveScreenshots) {
SessionLogEventModel log = convertSessionLogToModel((MsmLogIveScreenshots) obj);
windowLogs.add(log);
} else if (obj instanceof MsmDbAuditOracle) {
SessionLogEventModel log = convertOracleLogToModel((MsmDbAuditOracle) obj);
windowLogs.add(log);
}
}
setSessionLogEventModel(windowLogs);
}
i understand that for loop will eventually load all the data..but what i want is it will still load all the data but only choose 50 list of data to show in jsp..sorry again for my grammar..
The most common practise here is to take the 50 most recent values. So what I would do is check the length, and use subList.
Example
if(logList.size() > 50)
{
// you've got more than 50 objects here.
logList = logList.subList(logList.size() - 50, logList.size());
}
If you have less than or equal to 50 elements in your List, then there's no need to cut it.